Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(recall): refuse an unreadable --since or an empty --session (#6944)
time-attack8705ba3219dd
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 390179a595..727176f92b 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/trust.ts` — `gbrain trust review|confirm|release|drop|revert|explain|allow|disable` (#5575 DX-7; `backfill` is dispatched by `src/cli/commands/trust.ts`). `runOwnerAction` previews, asks for the typed token when the action raises trust, then applies bound to the preview; `review --accept-all` needs a filter and takes one confirmation (DX-15). The backend is the local engine, or `maybeDelegateTrust` (called from `src/cli.ts` before connecting) routes through a resident PGLite owner's administration socket with the prompt in the invoking CLI (DX-2). `confirmTierCrossingAccepts` puts tier-crossing `decide proposals accept` through the same rule; `quarantine release|drop` are aliases (`src/cli/commands/quarantine.ts`). Refusals render through `writeCliError` (exit 3 for consent refusals).- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`. #6259: `clear` reads one snapshot (page, tags, revision) and, on a managed brain, publishes through `submitPageMutation` with that `expected_revision` (a concurrent edit is a `revision_conflict`, a pending receipt is reported as pending); `--force` writes a `quarantine_override` (see `src/core/quarantine-override.ts`) instead of disabling the gate, never mutation `force`. `scan --apply` refuses `writer_coordinator_required` on a managed brain. `scan` does not re-check a segmented page (it would hold the whole body as one string): it lists it in `skipped` (`page_body_segmented`) and goes on. It is a router (`QUARANTINE_SUBCOMMANDS`, `printUsage`). Tests: `test/quarantine-override.serial.test.ts`, `test/quarantine-cli.test.ts`.-- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Its help (`RECALL_HELP`, printed before the engine via `SELF_HELP_WITHOUT_ENGINE`) names `--question` for natural-language questions. Cat 41 run 4: `keylessQuestionFallback` — on a brain whose fact recall is keyword-only (`factRecallIsKeywordOnly`, `src/core/facts/keyword-only.ts`: embedding opted out or no provider), a multi-word positional that matched no entity and no fact text (#4720's fallback) is ranked as a question through `runRecallVerb`, with a stderr note; brains with embeddings keep their output and get a `--question` hint (`test/recall-keyless-question-fallback.test.ts`). `--question <q>` (or `--question=<q>`) is the question, never an entity: it routes through the recall op like `--budget-policy` (thin clients call the remote recall, an answer without `facts_order` prints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, each `relevance` and `facts_degraded` (`test/recall-question-cli.test.ts`). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.+- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Its help (`RECALL_HELP`, printed before the engine via `SELF_HELP_WITHOUT_ENGINE`) names `--question` for natural-language questions. Cat 41 run 4: `keylessQuestionFallback` — on a brain whose fact recall is keyword-only (`factRecallIsKeywordOnly`, `src/core/facts/keyword-only.ts`: embedding opted out or no provider), a multi-word positional that matched no entity and no fact text (#4720's fallback) is ranked as a question through `runRecallVerb`, with a stderr note; brains with embeddings keep their output and get a `--question` hint (`test/recall-keyless-question-fallback.test.ts`). `--question <q>` (or `--question=<q>`) is the question, never an entity: it routes through the recall op like `--budget-policy` (thin clients call the remote recall, an answer without `facts_order` prints a not-ranked note; it refuses the watch, cursor, rollup and context renders), and the renderer shows the ranking, each `relevance` and `facts_degraded` (`test/recall-question-cli.test.ts`). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). `--since` parses with `parseSinceParam` (`src/core/facts/since-parse.ts`, the parser the recall op uses); an unreadable or missing `--since` value and a `--session`/`--session-id` with no ID throw `invalid_params` from `parseFlags` (the bad value echoed, the accepted grammar in `why`) instead of dropping the bound (#6944, `test/recall-bounds-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:` (written via `engine.setPageAliases`) and, for linkable entity pages, rewrites the derived title-subject and declared rows (`writeDerivedAliases`, coordinated on managed brains). Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. A segmented linkable page derives from its body read back as strings (`materializedPage`); one over the single-string ceiling gets frontmatter and subject aliases only, as its streamed import did, and is listed in `body_not_scanned`; a per-page `page_body_segmented` refusal is listed in `skipped`. Pinned by `test/search/reindex-aliases.test.ts`.diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex d59b6c5a93..e6d0239fb6 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -40,7 +40,7 @@ import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../core/mcp-climport { readCursor, writeCursor } from '../core/recall-cursor-state.ts';import { resolveSourceId, resolveSourceIdEngineFree, SourceTargetError } from '../core/source-resolver.ts';import { usageError } from '../cli/cli-error.ts';-import { parseRelativeSince } from '../core/facts/since-parse.ts';+import { parseSinceParam, SINCE_GRAMMAR } from '../core/facts/since-parse.ts';// Same kebab-case shape gate the source-resolver applies. v0.32: applied// locally on thin-client where the canonical resolver's assertSourceExists@@ -120,8 +120,33 @@ function parseFlags(args: string[]): ParsedFlags {let rawBudget: string | undefined;for (let i = 0; i < args.length; i++) {const a = args[i];- if (a === '--since') { out.since = parseSinceParam(args[++i] ?? ''); continue; }- if (a === '--session' || a === '--session-id') { out.sessionId = args[++i] ?? null; continue; }+ if (a === '--since') {+ const raw = args[i + 1];+ const valueGiven = raw !== undefined && !raw.startsWith('--');+ const since = valueGiven ? parseSinceParam(raw) : null;+ if (!since || !Number.isFinite(since.getTime())) {+ throw usageError(valueGiven ? `--since is not a date or duration (got "${raw.slice(0, 60)}").` : '--since requires a date or duration.',+ `Pass ${SINCE_GRAMMAR}.`, {+ why: `An unreadable time bound must not silently widen recall to every fact. --since takes ${SINCE_GRAMMAR}.`,+ fix: { argv: ['gbrain', 'recall', '--help'], consent: [], actor: 'agent', why: 'Shows the accepted --since forms.', requires_exclusive: false },+ });+ }+ out.since = since;+ i++;+ continue;+ }+ if (a === '--session' || a === '--session-id') {+ const raw = args[i + 1];+ if (raw === undefined || raw.trim().length === 0 || raw.startsWith('--')) {+ throw usageError(`${a} requires a session ID.`, `Pass the session ID after the flag, e.g. ${a} <id>.`, {+ why: 'A missing session bound must not silently widen recall to every session.',+ fix: { argv: ['gbrain', 'recall', '--help'], consent: [], actor: 'agent', why: 'Shows the recall selectors.', requires_exclusive: false },+ });+ }+ out.sessionId = raw;+ i++;+ continue;+ }if (a === '--grep') { out.grep = (args[++i] ?? '').toLowerCase(); continue; }if (a === '--today') { out.today = true; continue; }if (a === '--supersessions') { out.supersessions = true; continue; }@@ -190,24 +215,6 @@ export function recallNeedsLocalEngine(args: string[]): boolean {return flags.budgetPolicy === null && flags.question === null && (flags.query !== null || flags.budgetTokens !== null);}-function parseSinceParam(raw: string): Date | null {- if (!raw) return null;- const iso = Date.parse(raw);- if (Number.isFinite(iso)) return new Date(iso);- const ago = raw.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)(?:\s+ago)?$/i);- if (ago) {- const n = parseInt(ago[1], 10);- const unit = ago[2].toLowerCase();- const ms =- unit.startsWith('s') ? n * 1000 :- unit.startsWith('m') ? n * 60 * 1000 :- unit.startsWith('h') ? n * 60 * 60 * 1000 :- n * 24 * 60 * 60 * 1000;- return new Date(Date.now() - ms);- }- return parseRelativeSince(raw);-}-function validateAndNormalizeFlags(flags: ParsedFlags): void {if (flags.sinceLastRun && flags.since) {process.stderr.write('Error: --since-last-run and --since are mutually exclusive.\n');@@ -283,6 +290,10 @@ positional is an entity name, then a literal piece of fact text.gbrain recall --since "8 hours ago" facts from a time window (--today: today, rendered by kind)gbrain recall --session <id> facts from one session+--since takes an ISO 8601 date or datetime, a duration ("8 hours ago", "30m",+"2d") or a relative phrase ("6 weeks ago", "last month"). An unreadable+--since or a --session with no ID is refused (invalid_params, exit 2).+Options: --limit N, --include-expired, --json, --as-context, --source <id>,--budget-tokens N, --budget-policy facts_first|query_first, --supersessions,--since-last-run, --pending, --rollup, --watch [SECONDS].diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex cc2f0f5bfc..4d8600f852 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -904,6 +904,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },+ // Wave 20 lane 1 (#6944).+ { since: '0.60.307.0', text: '`gbrain recall --since <value>` now refuses a value it cannot read (and a `--since` with no value) with `invalid_params` (exit 2), echoing the value and listing the accepted forms, instead of silently recalling every time window. `--session` / `--session-id` with no ID refuses the same way instead of recalling every session. The CLI and the recall operation now share one `--since` parser.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 9f8e4affad..42490ef95e 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -48,7 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--class', '--clear', '--clear-never-installed', '--client', '--close', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--conversation', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--fuzzy', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--non-interactive', '--now', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],@@ -74,7 +74,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],'hook': ['--allow-unverified-remote', '--auto', '--batch-check', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],- 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--audit', '--auto', '--auto-additive', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--catch-up', '--chat-model', '--check', '--clear-never-installed', '--close', '--confirm-relocated-root', '--conflicts', '--content-root', '--conversation', '--db-only', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--expand', '--expansion-model', '--expect', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--force-retry', '--from', '--from-meetings', '--full', '--git', '--grant-types', '--group-by', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-frontmatter', '--include-gitignored', '--install', '--issuer-url', '--json', '--keep', '--key', '--lanes', '--legacy-lock', '--limit', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--min-n', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-git', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-repair', '--no-schema-pack', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--older-than', '--once', '--only', '--oversized', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair-unknown-markers', '--repo', '--request', '--reset', '--resolve', '--resume', '--retry-failed', '--retry-parked', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--semantic', '--session', '--session-id', '--show-toplevel', '--since', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--surface', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--type', '--wait'],'jobs': ['--abbrev-ref', '--access', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--close', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--purge', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--scopes', '--section', '--segment-limit', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],diff --git a/src/core/facts/since-parse.ts b/src/core/facts/since-parse.tsindex 48ee4c23cd..69b34ed884 100644--- a/src/core/facts/since-parse.ts+++ b/src/core/facts/since-parse.ts@@ -1,8 +1,8 @@/**- * Relative `since` phrases for recall (a dependency-free leaf shared by the- * recall op and the recall CLI). Both parsers try their existing grammar- * first (ISO 8601, epoch millis, "8 hours ago", "2d") and fall back to this- * one, so every input that parsed before keeps its result.+ * Recall's `since` grammar (a dependency-free leaf). parseSinceParam is the one+ * parser the recall op and the recall CLI share: it tries ISO 8601, epoch+ * millis and "8 hours ago" / "2d" first and falls back to the relative+ * phrases below, so every input that parsed before keeps its result.** Accepted (case-insensitive, any spacing):* - "6 weeks ago", "a week ago", "an hour ago", "one month ago"@@ -51,3 +51,38 @@ export function parseRelativeSince(raw: string, now: number = Date.now()): Dateif (!Number.isSafeInteger(count)) return null;return step(now, count, unit);}++/**+ * Parse a `since` parameter into a Date. Accepts ISO 8601, plain duration+ * shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), Unix+ * epoch millis, or a relative phrase (parseRelativeSince: "6 weeks ago",+ * "last month"). Returns null on unparseable input.+ */+export function parseSinceParam(raw: unknown): Date | null {+ if (raw == null) return null;+ if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw);+ if (typeof raw !== 'string') return null;+ const s = raw.trim();+ if (!s) return null;++ // Try ISO first.+ const iso = Date.parse(s);+ if (Number.isFinite(iso)) return new Date(iso);++ // "N (minutes|hours|days) ago" or compact forms.+ const ago = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)(?:\s+ago)?$/i);+ if (ago) {+ const n = parseInt(ago[1], 10);+ const unit = ago[2].toLowerCase();+ const ms =+ unit.startsWith('s') ? n * 1000 :+ unit.startsWith('m') ? n * 60 * 1000 :+ unit.startsWith('h') ? n * 60 * 60 * 1000 :+ n * 24 * 60 * 60 * 1000;+ return new Date(Date.now() - ms);+ }+ return parseRelativeSince(s);+}++/** The accepted `since` grammar, for refusals that echo a bad value. */+export const SINCE_GRAMMAR = 'an ISO 8601 date or datetime ("2026-08-11", "2026-08-11T09:00:00Z"), a duration ("8 hours ago", "30m", "2d"), or a relative phrase ("6 weeks ago", "last month")';diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 4a247d7fbd..f25730af08 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -50,7 +50,7 @@ import { activationSuppressionNotice, suppressionSummary } from '../eligibility/import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';-import { parseRelativeSince } from '../facts/since-parse.ts';+import { parseSinceParam } from '../facts/since-parse.ts';import { parseQuestionParam, questionRecallNotices, rankFactsByQuestion, recallHintNotice, unlinkedNamesakes, type EntityCandidate, type QuestionRecall } from '../facts/question-recall.ts';// ============================================================@@ -1355,37 +1355,7 @@ export function clampRecallLimit(raw: unknown): number {return Math.min(raw, 100);}-/**- * Parse a `since` parameter into a Date. Accepts ISO 8601, plain duration- * shorthand ("8 hours ago", "3 days ago", "30m", "1h", "2d", "7d"), Unix- * epoch millis, or a relative phrase (since-parse.ts: "6 weeks ago",- * "last month"). Returns null on unparseable input.- */-export function parseSinceParam(raw: unknown): Date | null {- if (raw == null) return null;- if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw);- if (typeof raw !== 'string') return null;- const s = raw.trim();- if (!s) return null;-- // Try ISO first.- const iso = Date.parse(s);- if (Number.isFinite(iso)) return new Date(iso);-- // "N (minutes|hours|days) ago" or compact forms.- const ago = s.match(/^(\d+)\s*(s|sec|seconds?|m|min|minutes?|h|hr|hours?|d|days?)(?:\s+ago)?$/i);- if (ago) {- const n = parseInt(ago[1], 10);- const unit = ago[2].toLowerCase();- const ms =- unit.startsWith('s') ? n * 1000 :- unit.startsWith('m') ? n * 60 * 1000 :- unit.startsWith('h') ? n * 60 * 60 * 1000 :- n * 24 * 60 * 60 * 1000;- return new Date(Date.now() - ms);- }- return parseRelativeSince(s);-}+export { parseSinceParam } from '../facts/since-parse.ts';/*** MEMORY_VERBS v1 — parse the `remember` verb's `ttl` param into adiff --git a/test/recall-bounds-envelope.test.ts b/test/recall-bounds-envelope.test.tsnew file mode 100644index 0000000000..6acb22fa97--- /dev/null+++ b/test/recall-bounds-envelope.test.ts@@ -0,0 +1,88 @@+/**+ * `gbrain recall --since` / `--session` are filters that narrow the result.+ * A malformed or missing value must refuse with invalid_params (exit 2), like+ * `gbrain delta --since` and `recall --limit`, instead of silently dropping the+ * bound and recalling every time window or every session. The flags are parsed+ * before any engine call, so no brain is opened.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { runRecall, recallNeedsLocalEngine } from '../src/commands/recall.ts';+import { renderCliError } from '../src/core/agent-output.ts';+import { OperationError } from '../src/core/ops/contract.ts';++const originalExit = process.exit;+afterEach(() => { process.exit = originalExit; });++/** The refusal recall throws; an engine stub of `{}` means any later I/O fails the test instead. */+async function refusal(args: string[]): Promise<OperationError> {+ process.exit = ((code?: number) => { throw new Error(`process.exit(${code}) instead of an invalid_params error`); }) as typeof process.exit;+ const error = await runRecall({} as never, args).then(() => null, (e: unknown) => e);+ expect(error).toBeInstanceOf(OperationError);+ return error as OperationError;+}++describe('recall --since invalid-input envelope', () => {+ test.each([+ ['unparseable', ['--since', 'not-a-date', '--json']],+ ['missing at the end', ['--json', '--since']],+ ['followed by another flag', ['--since', '--json']],+ ['empty', ['--since', '', '--json']],+ ])('%s value refuses before any engine call', async (_label, args) => {+ const r = renderCliError(await refusal(args), { json: true, command: 'recall', tty: false });+ expect(r.exitCode).toBe(2);+ const env = JSON.parse(r.stdout!);+ expect(env.code).toBe('invalid_params');+ expect(env.message).toContain('--since');+ expect(env.why).toContain('time bound');+ });++ test('a missing value says so; a bad value is echoed with the accepted grammar', async () => {+ expect((await refusal(['--since'])).message).toBe('--since requires a date or duration.');+ const bad = await refusal(['--since', 'not-a-date']);+ expect(bad.message).toBe('--since is not a date or duration (got "not-a-date").');+ const env = JSON.parse(renderCliError(bad, { json: true, command: 'recall', tty: false }).stdout!);+ expect(JSON.stringify(env)).toContain('8 hours ago');+ });++ test('human output names the flag and the fix on stderr', async () => {+ const r = renderCliError(await refusal(['--since', 'yesterday-ish']), { json: false, command: 'recall', tty: false });+ expect(r.exitCode).toBe(2);+ expect(r.stderr).toContain('--since is not a date or duration (got "yesterday-ish")');+ expect(r.stderr).toContain('6 weeks ago');+ expect(r.stderr).toContain('Fix: gbrain recall --help');+ });+});++describe('recall --session invalid-input envelope', () => {+ test.each([+ ['--session', 'missing at the end', ['--json', '--session']],+ ['--session', 'followed by another flag', ['--session', '--today']],+ ['--session-id', 'blank', ['--session-id', ' ', '--json']],+ ['--session-id', 'missing at the end', ['--session-id']],+ ])('%s %s refuses before any engine call', async (flag, _label, args) => {+ const e = await refusal(args);+ expect(e.message).toBe(`${flag} requires a session ID.`);+ const env = JSON.parse(renderCliError(e, { json: true, command: 'recall', tty: false }).stdout!);+ expect(env.code).toBe('invalid_params');+ expect(env.why).toContain('every session');+ });+});++describe('the thin-client dispatch probe', () => {+ test('refuses malformed bounds the same way', () => {+ process.exit = ((code?: number) => { throw new Error(`process.exit(${code})`); }) as typeof process.exit;+ expect(() => recallNeedsLocalEngine(['--since', 'x'])).toThrow(OperationError);+ expect(() => recallNeedsLocalEngine(['--session'])).toThrow(OperationError);+ });++ test('still accepts valid ISO, relative, classic and --today bounds', () => {+ for (const args of [+ ['--since', '2026-09-01', '--session-id', 'session-example'],+ ['--since', '48 hours ago'],+ ['--since', '1h', '--grep', 'needle'],+ ['--since', 'last week'],+ ['--today', '--session', 'session-example'],+ ]) expect(recallNeedsLocalEngine(args)).toBe(false);+ expect(recallNeedsLocalEngine(['--session-id', 'session-example', '--query', 'what changed'])).toBe(true);+ });+});