The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Inspired by Amp: relative time bounds (7d/24h/2w) + wrapper forwarding for session_search after/before
Tekniume819846b10b8
diff --git a/tests/tools/test_session_search.py b/tests/tools/test_session_search.pyindex edc53c2a1a2..39beb780845 100644--- a/tests/tools/test_session_search.py+++ b/tests/tools/test_session_search.py@@ -99,7 +99,13 @@ class TestSchema:"sort","profile",]- assert parameters == [*historical_prefix, "detail"]+ assert parameters == [+ *historical_prefix,+ "detail",+ "after",+ "before",+ "exclude_session_ids",+ ]class TestFormatTimestamp:@@ -1220,6 +1226,75 @@ class TestDiscoveryTemporalNarrowing:))assert result["success"] is False+ def test_relative_after_keeps_only_recent_sessions(self, db):+ """Amp-style relative bounds: after="7d" = started within the last week."""+ _seed_modpack_sessions(db)+ now = int(time.time())+ db._conn.execute(+ "UPDATE sessions SET started_at = ? WHERE id = ?",+ (now - 2 * 86400, "s_newest"),+ )+ db._conn.execute(+ "UPDATE sessions SET started_at = ? WHERE id = ?",+ (now - 30 * 86400, "s_middle"),+ )+ db._conn.execute(+ "UPDATE sessions SET started_at = ? WHERE id = ?",+ (now - 60 * 86400, "s_oldest"),+ )+ db._conn.commit()++ result = json.loads(session_search(+ query="modpack", limit=5, after="7d", db=db,+ ))+ assert result["success"] is True+ sids = [r["session_id"] for r in result["results"]]+ assert "s_newest" in sids+ assert "s_middle" not in sids+ assert "s_oldest" not in sids++ def test_relative_before_finds_only_stale_sessions(self, db):+ """before="7d" = no session started more recently than a week ago."""+ _seed_modpack_sessions(db)+ now = int(time.time())+ db._conn.execute(+ "UPDATE sessions SET started_at = ? WHERE id = ?",+ (now - 2 * 86400, "s_newest"),+ )+ db._conn.execute(+ "UPDATE sessions SET started_at = ? WHERE id = ?",+ (now - 30 * 86400, "s_middle"),+ )+ db._conn.execute(+ "UPDATE sessions SET started_at = ? WHERE id = ?",+ (now - 60 * 86400, "s_oldest"),+ )+ db._conn.commit()++ result = json.loads(session_search(+ query="modpack", limit=5, before="7d", db=db,+ ))+ assert result["success"] is True+ sids = [r["session_id"] for r in result["results"]]+ assert "s_newest" not in sids+ assert "s_middle" in sids+ assert "s_oldest" in sids++ def test_relative_bound_units_hours_and_weeks(self):+ from tools.session_search_tool import _parse_iso_bound+ now = int(time.time())+ h = _parse_iso_bound("24h")+ d = _parse_iso_bound("1d")+ w = _parse_iso_bound("2w")+ assert h is not None and abs((now - h) - 86400) < 5+ assert d is not None and abs((now - d) - 86400) < 5+ assert w is not None and abs((now - w) - 2 * 604800) < 5+ # Case-insensitive + internal whitespace tolerated+ assert _parse_iso_bound("7D") is not None+ # Bad units still error+ with pytest.raises(ValueError):+ _parse_iso_bound("7x")+def test_window_finds_in_range_session_buried_by_fts_limit(self, db, monkeypatch):"""A June hit must survive even if FTS rank would fill the scan with August.diff --git a/tools/session_search_tool.py b/tools/session_search_tool.pyindex dc56ab5969b..f84c6b3175b 100644--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@ -10,6 +10,8 @@ No LLM calls — every shape returns actual DB messages.import jsonimport logging+import re+import timefrom datetime import datetime, timezonefrom typing import Any, Dict, List, Optional, Union@@ -32,6 +34,9 @@ _DEMOTED_SESSION_SOURCES = ("cron",)_DISCOVER_SCAN_LIMIT = 300# exclude_session_ids: ids already inspected this task; capped so a runaway list can't fan out lineage walks._EXCLUDE_SESSION_IDS_CAP = 20+# Relative time bounds: "7d" / "24h" / "2w" = now minus N hours/days/weeks.+_RELATIVE_BOUND_RE = re.compile(r"^(\d+)\s*(h|d|w)$", re.IGNORECASE)+_RELATIVE_UNIT_SECONDS = {"h": 3600, "d": 86400, "w": 604800}# Raw FTS rows are only a plan input; the response hydrates its own window/bookends._DISCOVER_SEARCH_FIELDS = ("id", "session_id", "role", "snippet", "source", "model", "session_started")# Compaction handoff summaries (agent/context_compressor.py); excluded from bookends.@@ -111,21 +116,26 @@ def _resolve_lineage(db, session_id: str) -> str:def _parse_iso_bound(value: Optional[str], *, as_exclusive_end: bool = False) -> Optional[int]:- """Parse an ISO date/datetime into a UTC unix timestamp.+ """Parse an ISO date/datetime OR a relative duration into a UTC unix timestamp.- A date-only value (``YYYY-MM-DD``) is midnight UTC on that day. When- ``as_exclusive_end`` is True, that midnight is the exclusive upper bound- (``before=2026-07-01`` keeps June, drops July 1 00:00).+ ISO: a date-only value (``YYYY-MM-DD``) is midnight UTC on that day; with+ ``as_exclusive_end`` that midnight is the exclusive upper bound+ (``before=2026-07-01`` keeps June, drops July 1 00:00). Relative: ``"7d"``,+ ``"24h"``, ``"2w"`` = now minus N hours/days/weeks, so ``after="7d"`` is the+ last week and ``before="7d"`` is everything older than a week."""if value is None:return Nonetext = str(value).strip()if not text:return None+ if rel := _RELATIVE_BOUND_RE.match(text):+ return int(time.time()) - int(rel.group(1)) * _RELATIVE_UNIT_SECONDS[rel.group(2).lower()]try:parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))except ValueError:- raise ValueError(f"invalid ISO timestamp: {value!r}") from None+ raise ValueError(f"invalid time bound: {value!r} (expected ISO date/datetime like "+ "2026-07-01, or a relative duration like 7d, 24h, 2w)") from Noneif parsed.tzinfo is None:parsed = parsed.replace(tzinfo=timezone.utc)return int(parsed.timestamp())@@ -691,17 +701,18 @@ SESSION_SEARCH_SCHEMA = {"type": "string","description": ("Discovery shape only. Inclusive lower bound on session start "- "time (ISO date or datetime, e.g. 2026-06-01). Use only when the "- "user names a time frame. sort is a ranking bias, not a bound."+ "time. ISO date/datetime (e.g. 2026-06-01) or relative duration "+ "(7d, 24h, 2w = within the last N). Use only when the user names "+ "a time frame. sort is a ranking bias, not a bound."),},"before": {"type": "string","description": ("Discovery shape only. Exclusive upper bound on session start "- "time (ISO date or datetime, e.g. 2026-07-01). A date-only value "- "is midnight UTC that day. Use only when the user names a time "- "frame."+ "time. ISO date/datetime (a date-only value is midnight UTC that "+ "day) or relative duration (7d = older than a week). Use only "+ "when the user names a time frame."),},"exclude_session_ids": {diff --git a/website/docs/reference/tools-reference.md b/website/docs/reference/tools-reference.mdindex 20f30ae40cd..b7bdb69c284 100644--- a/website/docs/reference/tools-reference.md+++ b/website/docs/reference/tools-reference.md@@ -184,7 +184,7 @@ Tools for driving desktop [Projects](../user-guide/cli.md) — named, multi-fold| Tool | Description | Requires environment ||------|-------------|----------------------|-| `session_search` | Search past sessions stored in the local session DB, or scroll inside one. FTS5-backed retrieval; returns actual messages from the DB (no LLM calls). Four shapes: discovery (pass `query`), scroll (pass `session_id` + `around_message_id`), read (pass `session_id` only), browse (no args). | — |+| `session_search` | Search past sessions stored in the local session DB, or scroll inside one. FTS5-backed retrieval; returns actual messages from the DB (no LLM calls). Four shapes: discovery (pass `query`), scroll (pass `session_id` + `around_message_id`), read (pass `session_id` only), browse (no args). Discovery supports time bounds (`after`/`before` — ISO dates or relative durations like `7d`, `24h`, `2w`) and `exclude_session_ids` for iterative re-finding. | — |## `skills` toolset