diff --git a/.changeset/1352-cli-flag-values.md b/.changeset/1352-cli-flag-values.md new file mode 100644 index 0000000000..c874b45f2c --- /dev/null +++ b/.changeset/1352-cli-flag-values.md @@ -0,0 +1,12 @@ +--- +"@schlessera/brain": minor +--- + +**Breaking (#1352):** core CLI commands now read flag values through one typed accessor, so a malformed value is a usage error (exit 1, message on stderr, nothing on stdout) in human and JSON modes, refused before any query runs. Valid values keep their meaning, a repeated flag still keeps its last value, and no new upper bound is introduced. + +- **`brain search --limit`**, before: read with `parseInt`, so `10abc` searched with 10, `1.5` with 1, `abc` came back empty with an `FTS search failed: datatype mismatch` warning, and `0` or `-5` was passed on to the query. **After:** a whole number of 1 or more; `abc`, `0`, `-5`, `1.5`, `10abc` and an empty value are refused. +- **`brain search --mode`**, before: an unknown mode ran neither lane and returned nothing without a warning. **After:** `fts`, `vector` or `hybrid`; anything else, including an empty value, is refused (`--mode must be one of fts, vector, hybrid, got "bogus"`). +- **`brain context --max-tokens`** and **`brain briefing --limit`**, before: `parseInt`, so `abc` reached the assembler as `NaN` and briefing silently fell back to 15. **After:** a whole number of 1 or more; `abc`, `0`, `1.5`, `10abc` and an empty value are refused. +- **A value flag with no value** (`brain search q --type`, `brain list --tag --status active`, `brain add "…" --tags`), before: flowed on as `true`, or for `add --tags` failed with exit 2. **After:** `-- needs a value`. + +`brain search --sort` and the date filters keep their existing usage errors. diff --git a/.changeset/cli-commands-no-sql.md b/.changeset/cli-commands-no-sql.md new file mode 100644 index 0000000000..ddee4b52f4 --- /dev/null +++ b/.changeset/cli-commands-no-sql.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain": patch +--- + +Internal refactor (#1353): the `accept-mtime`, `briefing`, `doctor`, `eval` and `tags` commands no longer run SQL themselves; they call named index functions in core's library, and `brain briefing`'s Silently Modified section and `brain hygiene`'s silent-edit check now share one query. No command's output changes. diff --git a/.changeset/graph-reader-profiles.md b/.changeset/graph-reader-profiles.md new file mode 100644 index 0000000000..02bebe43bc --- /dev/null +++ b/.changeset/graph-reader-profiles.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain": patch +--- + +Core's two graph readers, behind `brain graph` and the supported `./queries` graph reads, now share one internal reader with an explicit CLI profile and UI profile (#1354). Both keep their former results, defaults, caps, ordering and errors. No `--json` shape, query result or export changes. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 6929afe691..00077ecfc0 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -66,7 +66,7 @@ next to it. `packages/ui-server/src/brain/client.ts:180-248`, called at `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:451`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, - `packages/core/src/cli/commands/doctor.ts:503-507`) — the user's own Claude + `packages/core/src/cli/commands/doctor.ts:505-509`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's binary. - **Two moving parts.** The SDK is a runtime dependency of diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index e5062feea9..d01f6341f2 100644 --- a/docs/decisions/hygiene-review.md +++ b/docs/decisions/hygiene-review.md @@ -180,7 +180,7 @@ an invalidation can name the fields that changed. entries in `context/hygiene/dismissed.md`, snoozed ones in `snoozed.md`. Each records its time and the fingerprint it applied to. `until:` takes an ISO date-time or a date; a date is due at the start of that UTC day, as before -(`function dueAt`, `packages/core/src/lib/hygiene.ts:863-873`). A recorded +(`function dueAt`, `packages/core/src/lib/hygiene.ts:899-909`). A recorded fingerprint that no longer matches reopens the finding at once, with an `invalidated:` receipt naming the changed fields and the disposition's date. A snooze that comes due reopens it with no receipt. @@ -190,7 +190,7 @@ identity), the new finding carries the receipt only when the pairing is unambiguous. In one run, exactly one disposition in force with that category and path stops being detected, and exactly one new finding with them appears (`if (prior.length === 1 && siblings.length === 1)`, -`packages/core/src/lib/hygiene.ts:1538`). Otherwise the new finding opens +`packages/core/src/lib/hygiene.ts:1574`). Otherwise the new finding opens without one. Either way the old disposition does not suppress it. Entries moved by hand carry no fingerprint, so they keep their earlier behaviour. @@ -209,11 +209,11 @@ made (K1 A). It lives in `context/hygiene/kept.md`, which is never created empty. It holds only while the original's fingerprint is unchanged and its copy is a contained regular file outside `.brain/` and `workspaces/` that `media.track` keeps. Otherwise the original reopens with an `invalidated:` -receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:998-1008`). +receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:1034-1044`). Sync's count and review use one read-only function that applies these predicates to the log as it stands rather than trusting the file an entry sits -in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1778-1793`). +in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1814-1829`). Leave pending is a per-pass deferral in review state, never a log state: it skips the finding while its fingerprint holds, and the finding still counts. @@ -265,7 +265,7 @@ permission, premise revalidation and a real post-apply check before success. Do not implement dismissal by marking a still-detected finding resolved: existing reconciliation reopens such an entry (`const prev = field(entry, "resolved-by")`, -`packages/core/src/lib/hygiene.ts:1512-1515`). Keep review disposition distinct from +`packages/core/src/lib/hygiene.ts:1548-1551`). Keep review disposition distinct from actual check success and from notification acknowledgement. Markdown remains authoritative for findings, dispositions and confirmed content diff --git a/docs/decisions/index-query-api.md b/docs/decisions/index-query-api.md index 74886b6add..7d08ffc6b2 100644 --- a/docs/decisions/index-query-api.md +++ b/docs/decisions/index-query-api.md @@ -29,7 +29,7 @@ alone does not excuse changing the documented results or error behavior. Two packages currently own graph SQL. UI-server opens a short-lived read-only connection (`openBrainDb`, `packages/ui-server/src/db/brain-db.ts:75-97`), interprets graph availability ([pre-migration `getGraphMeta`](https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L437-L471)) and walks raw links for -interactive neighborhoods ([pre-migration `getNeighborhood`](https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L525-L540)). Core has its own cluster query (`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:181-204`). +interactive neighborhoods ([pre-migration `getNeighborhood`](https://github.com/schlessera/brain-kit/blob/33af7e2972873286144dbcc93c232c904e3ced47/packages/ui-server/src/graph/reader.ts#L525-L540)). Core has its own cluster query (`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:142-159`). Their defaults and responses differ. A wrapper around one existing helper is not automatically a behavior-preserving replacement for the other. diff --git a/docs/decisions/interpreted-briefing.md b/docs/decisions/interpreted-briefing.md index c71e768189..2b76387982 100644 --- a/docs/decisions/interpreted-briefing.md +++ b/docs/decisions/interpreted-briefing.md @@ -25,14 +25,14 @@ retain sanitized tool requests. ## What the source already supplies `generateBriefing` performs the mechanical work -(`generateBriefing`, `packages/core/src/cli/commands/briefing.ts:183-319`): +(`generateBriefing`, `packages/core/src/cli/commands/briefing.ts:186-293`): focus warnings and linked documents; non-archived deadlines from today through sixty days; overdue reviews strictly before today, with a five-item cap and remaining count; module-aware audit totals and hygiene counts; recent activity, silent modifications and taxonomy-driven staleness. Its existing `now` option permits the evaluation clock without changing product code. The CLI exposes the plain-text report -(`briefingCommand`, `packages/core/src/cli/commands/briefing.ts:321-340`). +(`briefingCommand`, `packages/core/src/cli/commands/briefing.ts:295-314`). The shipped `whatsup` skill gathers that report, may read up to three files, then interprets urgency, groups action and FYI, and writes terse bullets. diff --git a/docs/decisions/mechanical-hygiene.md b/docs/decisions/mechanical-hygiene.md index 8b0b83023d..d4a2078330 100644 --- a/docs/decisions/mechanical-hygiene.md +++ b/docs/decisions/mechanical-hygiene.md @@ -36,7 +36,7 @@ scratch state are excluded from source-byte scoring; an input hygiene file remains protected. The prototype reuses table detection (`indexTableLag`, -`packages/core/src/lib/hygiene.ts:541-583`), scalar table rendering +`packages/core/src/lib/hygiene.ts:577-619`), scalar table rendering (`renderRegistry`, `packages/core/src/lib/index-registry.ts:117-185`) and the surgical frontmatter editor (`editFrontmatter`, `packages/core/src/lib/frontmatter-edit.ts:216-224`). It intentionally refuses @@ -134,7 +134,7 @@ one explicit providerless CLI planner/apply operation for this supported grammar, with `--json` and dry-run output, followed by the existing reconciliation. Re-read every consulted input and use the existing unchanged-source writer (`replaceIfUnchanged`, -`packages/core/src/lib/hygiene.ts:1246-1256`) before application. Keep registry +`packages/core/src/lib/hygiene.ts:1282-1292`) before application. Keep registry ownership, inbox/archive exclusions and all unhandled cases visible as log-only. The skill delegates these two mechanical operations; canonical judgment remains with it. That follow-up needs the additive contract documentation and normal diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index 4b662ba027..370b867990 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -195,7 +195,7 @@ Paths may appear in local diagnostics; public fixtures use temporary paths. | --- | --- | --- | | Claude backend's SDK range | Retain `^0.3.241` | It is the published declaration (`"@anthropic-ai/claude-agent-sdk"`, `packages/ui-backend-claude/package.json:49`). Registry metadata on 2026-09-30 confirms 0.3.241 exists. This is a declared compatibility bound, not proof every allowed release passed current measurements. | | ui-server's content CLI floor | Retain `0.33.0` | `--` support is the reason documented immediately above `MIN_BRAIN_CLI_VERSION` (`MIN_BRAIN_CLI_VERSION`, `packages/ui-server/src/brain/client.ts:132`); the initial boot refusal test used 0.32.9. The current test exercises the corrected floor (`a 0.40.0 brain repo pin`, `packages/ui-server/tests/brain-client.test.ts:247-259`). | -| Bun engine floor | Retain existing `>=1.3.5` declarations | Existing engine metadata and the doctor's CVE-based warning (`const MIN_BUN`, `packages/core/src/cli/commands/doctor.ts:48`; `function checkRuntime`, `packages/core/src/cli/commands/doctor.ts:85-92`). This record introduces no new doctor verdict or blanket boot gate. | +| Bun engine floor | Retain existing `>=1.3.5` declarations | Existing engine metadata and the doctor's CVE-based warning (`const MIN_BUN`, `packages/core/src/cli/commands/doctor.ts:50`; `function checkRuntime`, `packages/core/src/cli/commands/doctor.ts:87-94`). This record introduces no new doctor verdict or blanket boot gate. | | Pi SDK requirements | Retain existing exact `0.87.1` declarations | `packages/ui-backend-pi/package.json`; a host floor composes with each actual imported Pi dependency's existing exact requirement. The Claude range ruling does not authorize changing Pi's pins. | | Additional default Claude runtime floor | None | There is no evidenced numerical incompatibility threshold in the existing record. The successful pairs are observations, not proof that the preceding release fails. A new library floor needs a feature requirement or reproducible incompatibility and its versioning review. | | Example host SDK/runtime floors | `0.3.283` / `2.1.283` | The installed SDK manifest and `MEASURED_RUNTIME` (`export const MEASURED_RUNTIME`, `packages/ui-backend-claude/src/measured-runtime.ts:18-25`) identify this measured pair, rechecked in commit `e1ce9600`. This is a host choosing the demonstrated baseline, not a new default package floor. | diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index 95396c9a90..bc20e5dc88 100644 --- a/docs/integration-contract/cli.md +++ b/docs/integration-contract/cli.md @@ -473,6 +473,12 @@ resumption. The host must retain a successful complete export at least every `--baseline` gate; `3` is runs that are not comparable, the report still printed). - Boolean flags never consume the following argument. +- A value flag given without a value (last, or followed by another `--flag`) + is a usage error in `brain search`, `list`, `add`, `read`, `context` and + `briefing` (`--type needs a value`). A repeated flag keeps its last + value. **Breaking in 0.45.0 (#1352):** such a flag used to flow on as `true` + (`brain search --type`, `brain list --tag --status active`), and a bare + `brain add --tags` failed with exit `2`. - End-of-options: a bare `--` stops flag parsing, and every later argument is positional verbatim. Output-mode and help flags after it are positional too (additive in 0.33.0). @@ -483,11 +489,11 @@ resumption. The host must retain a successful complete export at least every | Command | Shape | |---------|-------| -| `brain search "q" --json` | `{ "results": SearchResult[], "warnings": string[] }` — `warnings` reports degraded modes (no vectors, model mismatch, missing key, a reranker that did not run, a [withheld provider key](#withheld-provider-keys-additive-0440-1666)). `--rerank none\|heuristic\|jev`: `jev` added in 0.39.0, additively; unset, the configured `reranker.provider` (judgment requires `reranker.enabled: true`; otherwise local `heuristic`, or `none` when selected). `--rerank-dry-run` (0.39.0) prints the reranker's outbound request to stderr and sends nothing, even while disabled or keyless. Date filters `--updated-since`, `--updated-before`, `--deadline-from`, `--deadline-to` (`YYYY-MM-DD`, inclusive; a deadline filter drops undated docs), `--sort score\|updated\|deadline` (default `score`; `updated` newest first, `deadline` earliest first with undated docs last) and `--upcoming` (= `--deadline-from --sort deadline`) added in 0.38.0, additively. Stored dates are compared as their UTC day (sorts keep full timestamp precision). A stored value counts only as an ISO `YYYY-MM-DD`, optionally followed by `T` or a space, `HH:MM`, seconds, a fraction and a `Z` or `±HH:MM` offset. Anything else, `2026-02-30` and `now` included, counts as missing: it matches no bound and sorts last. With a query, a date sort picks the results by date from a candidate pool: the full-text lane's best `max(limit × 20, 500)` documents, plus the documents behind the vector lane's nearest chunks (at most that many documents, from at most 500 chunks). An invalid date or sort is a usage error (exit `1`) | +| `brain search "q" --json` | `{ "results": SearchResult[], "warnings": string[] }` — `warnings` reports degraded modes (no vectors, model mismatch, missing key, a reranker that did not run, a [withheld provider key](#withheld-provider-keys-additive-0440-1666)). `--rerank none\|heuristic\|jev`: `jev` added in 0.39.0, additively; unset, the configured `reranker.provider` (judgment requires `reranker.enabled: true`; otherwise local `heuristic`, or `none` when selected). `--rerank-dry-run` (0.39.0) prints the reranker's outbound request to stderr and sends nothing, even while disabled or keyless. Date filters `--updated-since`, `--updated-before`, `--deadline-from`, `--deadline-to` (`YYYY-MM-DD`, inclusive; a deadline filter drops undated docs), `--sort score\|updated\|deadline` (default `score`; `updated` newest first, `deadline` earliest first with undated docs last) and `--upcoming` (= `--deadline-from --sort deadline`) added in 0.38.0, additively. Stored dates are compared as their UTC day (sorts keep full timestamp precision). A stored value counts only as an ISO `YYYY-MM-DD`, optionally followed by `T` or a space, `HH:MM`, seconds, a fraction and a `Z` or `±HH:MM` offset. Anything else, `2026-02-30` and `now` included, counts as missing: it matches no bound and sorts last. With a query, a date sort picks the results by date from a candidate pool: the full-text lane's best `max(limit × 20, 500)` documents, plus the documents behind the vector lane's nearest chunks (at most that many documents, from at most 500 chunks). An invalid date or sort is a usage error (exit `1`). `--limit` is a whole number of `1` or more, default `20`, with no upper bound; the whole argument must be an integer literal. `--mode` is `fts`, `vector` or `hybrid`. Anything else (`--limit abc`, `0`, `-5`, `1.5`, `10abc`, an empty value, `--mode bogus`, or either flag, or a filter flag, without a value) is a usage error (exit `1`, a message on stderr, nothing on stdout) in human and JSON modes, and no query runs. **Breaking in 0.45.0 (#1352):** `--limit` used to be read with `parseInt`, so `10abc` searched with 10 and `1.5` with 1, `abc` came back as an empty result with an `FTS search failed: datatype mismatch` warning, and `0` or a negative was passed on to the query; an unknown `--mode` ran neither lane and returned nothing, without a warning | | `brain audit --json` | `{ "issues": AuditIssue[], "errors", "warnings", "infos", "mustFix", "informational" }` — markdown documents only (assets excluded). The three severity counts are the number of issues at each severity. `mustFix` is `errors + warnings` and `informational` is `infos` (both additive in 0.40.0): severity stays the one classification, and the two totals only name its halves. Every count is of issues, not of markers. **Breaking in 0.40.0:** `todo` and `verify` issues are grouped, one per document and category (see [`AuditIssue`](#auditissue)), and `verify` is `info` instead of `warning`, so a brain with markers reports fewer issues and fewer warnings than before for the same content. **Additive in 0.41.0:** `brain audit --fix --json` returns `AuditFixResult[]`, one result per finding in finding order: `{ path, issue, suggestion, canAutoFix, fix?, repair? }`. `path` is the finding path, `issue` its message, and `suggestion` its own advice (or "Manual review needed."); an unavailable `index-stale` instead names the failed repair premise, or says no registry content change is required. `canAutoFix` is true only for an actually available deterministic registry repair: safe contained path, valid opted-in registry with a content change, configured child types and no validation errors under the index directory. Available results also carry `repair: { capability: "registry", path: }`; all other categories and failed premises are manual with no `repair`. `repair` describes availability, grants no permission, and applies nothing. Optional `fix` means exact replacement text; this command never emits it. No completion provider is called, even if configured | -| `brain context "q" --max-tokens N` | assembled markdown context (text) | +| `brain context "q" --max-tokens N` | assembled markdown context (text). `--max-tokens` is a whole number of `1` or more, default `4000`; anything else (`abc`, `0`, `1.5`, or no value) is a usage error (exit `1`) and no query runs. **Breaking in 0.45.0 (#1352):** it used to be read with `parseInt`, so `10abc` meant 10 and `abc` reached the assembler as `NaN` | | `brain read [--section ] [--max-tokens N]` | the document text; the flags behave as `brain_read`'s `section` and `max_tokens`, and an unknown section exits `1` (flags additive in 0.38.0) | -| `brain briefing` | briefing text (mechanical: deadlines, reviews due, silent edits — no LLM) | +| `brain briefing` | briefing text (mechanical: deadlines, reviews due, silent edits — no LLM). `--limit` (recently active documents) is a whole number of `1` or more, default `15`; anything else (`abc`, `0`, `1.5`, or no value) is a usage error (exit `1`). **Breaking in 0.45.0 (#1352):** a malformed `--limit` used to fall back to 15 silently, and `10abc` meant 10 | | `brain index [--force] [--embeddings] --json` | `{ "total", "added", "updated", "deleted", "unchanged", "chunks", "embeddings", "assets", "graphMs", "graphNodes" }`, all numbers, each counting this run only. See [`brain index` counters](#brain-index-counters). Incremental by default, `--force` = full rebuild, `--incremental` accepted as no-op | | `brain index --forget-cache --json` | `{ "path", "forgotten" }` — `forgotten` is the number of sidecar lines removed for that document or asset (for an asset, every line for its bytes, whatever the title). Runs no index pass; the next `--embeddings` run regenerates what was forgotten. A path not in the index is a usage error (additive in 0.38.0) | | `brain index --compact --json` | `{ "compacted", "before": { "live", "allocated" }, "after": { "live", "allocated" } }` — rebuilds `vec_chunks` from its live rows and runs `VACUUM`, reclaiming the slots deleted vectors leave behind; `before`/`after` have the shape of `brain stats` `size.db.vectorSlots`. `compacted` is `false` only when there is no vector table. Makes no provider call and runs no index pass (additive in 0.38.0) | diff --git a/docs/investigations/note-disposition-investigation.md b/docs/investigations/note-disposition-investigation.md index 3d428b7585..5d503c81c9 100644 --- a/docs/investigations/note-disposition-investigation.md +++ b/docs/investigations/note-disposition-investigation.md @@ -38,7 +38,7 @@ proposals, show review requirements and delegate deterministic mutation to CLI code rather than describing a proposal as a completed move. `brain add` performs ingestion, with the smart branch handing off to an agent -(`addCommand`, `packages/core/src/cli/commands/add.ts:15-65`). +(`addCommand`, `packages/core/src/cli/commands/add.ts:15-68`). `brain archive` is a separate operation: it sets archived status, demotes primary/unset relevance, preserves other bytes, and moves only active projects to the archive directory (`archiveDocument`, diff --git a/docs/plans/index-query-api.md b/docs/plans/index-query-api.md index df402b543d..6464678315 100644 --- a/docs/plans/index-query-api.md +++ b/docs/plans/index-query-api.md @@ -269,7 +269,7 @@ resolved; direction affects an explicit root, not precomputed default distances. Preserve existing maintenance ordering, unresolved link text and stale cutoff. Core CLI graph helpers have different defaults, fields and cap behavior -(`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:181-204`). They may share private mechanics, but their public CLI `--json` +(`getClusterGraph`, `packages/core/src/lib/graph/queries.ts:142-159`). They may share private mechanics, but their public CLI `--json` shapes/defaults remain unchanged. Pi and MCP link walking default to depth 1/both. Pi and the supported link-walk query clamp depth to 1..4; core MCP's own cap is 5. It is a different result from the drawn graph: unresolved text is preserved and cycle/deduplication behavior diff --git a/packages/core/src/cli/commands/accept-mtime.ts b/packages/core/src/cli/commands/accept-mtime.ts index b447e84e05..8125bfdee7 100644 --- a/packages/core/src/cli/commands/accept-mtime.ts +++ b/packages/core/src/cli/commands/accept-mtime.ts @@ -1,4 +1,5 @@ import { openDatabase } from "../../lib/db.js"; +import { acceptMtimes } from "../../lib/hygiene.js"; import type { CoreCommand } from "../types.js"; import { emit, parseArgs, UsageError } from "../io.js"; @@ -16,22 +17,10 @@ export const acceptMtimeCommand: CoreCommand = { try { const relPath = pos[0]; - let changed: number; - if (relPath) { - const result = db - .prepare( - "UPDATE documents SET accepted_mtime = file_mtime WHERE path = ? AND file_mtime IS NOT NULL" - ) - .run(relPath); - changed = result.changes; - if (changed === 0) { - throw new UsageError(`No indexed document found at: ${relPath}`); - } - } else { - const result = db - .prepare("UPDATE documents SET accepted_mtime = file_mtime WHERE file_mtime IS NOT NULL") - .run(); - changed = result.changes; + // An empty path, like none, baselines every document. + const changed = acceptMtimes(db, relPath || undefined); + if (relPath && changed === 0) { + throw new UsageError(`No indexed document found at: ${relPath}`); } emit(cli.json, { accepted: changed, path: relPath ?? "(all)" }, () => { diff --git a/packages/core/src/cli/commands/add.ts b/packages/core/src/cli/commands/add.ts index 5656cb2e13..9b5738d8a2 100644 --- a/packages/core/src/cli/commands/add.ts +++ b/packages/core/src/cli/commands/add.ts @@ -1,7 +1,7 @@ -import type { DocumentType } from "../../lib/types.js"; import { ingest } from "../../lib/ingestion.js"; import { openDatabase } from "../../lib/db.js"; import type { CoreCommand } from "../types.js"; +import { stringFlag } from "../flags.js"; import { emit, parseArgs, UsageError } from "../io.js"; import { runAgent } from "../agent.js"; @@ -32,18 +32,21 @@ export const addCommand: CoreCommand = { return; } + // Read before the database is opened: a flag without a value writes nothing. + const type = stringFlag(flags, "type"); + const title = stringFlag(flags, "title"); + const tagList = stringFlag(flags, "tags"); + const tags = tagList ? tagList.split(",").map((t) => t.trim()) : undefined; + const db = openDatabase(cli.brain.dbPath); try { - const tags = flags.tags - ? (flags.tags as string).split(",").map((t) => t.trim()) - : undefined; // ingest() reindexes internally (incremental, no embeddings) via its // injected reindex → indexAll hook. const result = await ingest( { content, - type: flags.type as DocumentType | undefined, - title: flags.title as string | undefined, + type, + title, tags, }, db, diff --git a/packages/core/src/cli/commands/briefing.ts b/packages/core/src/cli/commands/briefing.ts index d0269d6cf9..d930ffa5a8 100644 --- a/packages/core/src/cli/commands/briefing.ts +++ b/packages/core/src/cli/commands/briefing.ts @@ -15,12 +15,15 @@ import { type AuditDoc, } from "../../lib/auditor.js"; import type { Taxonomy } from "../../lib/taxonomy.js"; +import { documentUpdated, focusLinkedDocuments, overdueReviewRows, upcomingDeadlines } from "../../lib/briefing-reads.js"; import { openDatabase } from "../../lib/db.js"; +import { silentEdits } from "../../lib/hygiene.js"; import { codeRanges, inRanges } from "../../lib/markdown-code.js"; import { filterSearch } from "../../lib/search-engine.js"; import { resolveStatsThresholds } from "../../lib/stats.js"; import { readStatsTrends } from "../../lib/stats-trends.js"; import type { CoreCommand } from "../types.js"; +import { positiveIntegerFlag } from "../flags.js"; import { parseArgs, UsageError } from "../io.js"; function addDays(dateStr: string, days: number): string { @@ -215,15 +218,7 @@ export async function generateBriefing(brain: BrainContext, limit = 15, opts: Br // 2. Focus-linked documents (wiki-links from the current-focus doc) if (focusRel) { - const focusLinks = db - .prepare( - `SELECT d.path, d.title, d.type, d.updated, d.summary - FROM links l - JOIN documents d ON d.id = l.target_id - WHERE l.source_id = (SELECT id FROM documents WHERE path = ?) - ORDER BY d.updated DESC` - ) - .all(focusRel) as any[]; + const focusLinks = focusLinkedDocuments(db, focusRel); if (focusLinks.length > 0) { lines.push("\n## Focus-Linked Documents\n"); for (const r of focusLinks) { @@ -234,13 +229,7 @@ export async function generateBriefing(brain: BrainContext, limit = 15, opts: Br // 3. Upcoming deadlines (next 60 days) const futureDate = addDays(todayStr, 60); - const deadlines = db - .prepare( - `SELECT deadline, path, title, summary FROM documents - WHERE deadline >= ? AND deadline <= ? AND status != 'archived' - ORDER BY deadline ASC` - ) - .all(todayStr, futureDate) as any[]; + const deadlines = upcomingDeadlines(db, todayStr, futureDate); if (deadlines.length > 0) { lines.push("\n## Upcoming Deadlines\n"); for (const r of deadlines) { @@ -250,13 +239,7 @@ export async function generateBriefing(brain: BrainContext, limit = 15, opts: Br // 4. Overdue reviews: due before today, as `brain audit` reads it // (findOverdueReviews), so the audit the cap points to lists every one. - const overdue = db - .prepare( - `SELECT next_review, path, title FROM documents - WHERE next_review IS NOT NULL AND next_review < ? AND status != 'archived' - ORDER BY next_review ASC` - ) - .all(todayStr) as any[]; + const overdue = overdueReviewRows(db, todayStr); if (overdue.length > 0) { lines.push("\n## Overdue Reviews\n"); for (const r of overdue.slice(0, reviewLimit)) { @@ -277,22 +260,13 @@ export async function generateBriefing(brain: BrainContext, limit = 15, opts: Br if (recent.length > 0) { lines.push("\n## Recently Active\n"); for (const r of recent) { - const row = db.prepare("SELECT updated FROM documents WHERE path = ?").get(r.path) as any; - lines.push(`- ${row?.updated || "?"} | ${r.type} | ${r.path} | ${r.title} | ${(r.summary || "").slice(0, 80)}`); + lines.push(`- ${documentUpdated(db, r.path) || "?"} | ${r.type} | ${r.path} | ${r.title} | ${(r.summary || "").slice(0, 80)}`); } } // 6. Silently modified (file changed but frontmatter `updated` not bumped). // Mtimes baselined via `brain accept-mtime` are exempt. - const silentMods = db - .prepare( - `SELECT file_mtime, updated, path, title FROM documents - WHERE file_mtime > updated - AND (accepted_mtime IS NULL OR file_mtime > accepted_mtime) - AND status != 'archived' - ORDER BY file_mtime DESC LIMIT 10` - ) - .all() as any[]; + const silentMods = silentEdits(db, { limit: 10 }); if (silentMods.length > 0) { lines.push("\n## Silently Modified\n"); for (const r of silentMods) { @@ -326,7 +300,7 @@ export const briefingCommand: CoreCommand = { --limit-reviews Overdue reviews to list before "… and N more" (default: 5)`, async run(args, cli) { const { flags } = parseArgs(args); - const limit = parseInt(flags.limit as string, 10) || 15; + const limit = positiveIntegerFlag(flags, "limit") ?? 15; let reviewLimit: number | undefined; if (flags["limit-reviews"] !== undefined) { reviewLimit = typeof flags["limit-reviews"] === "string" ? Number(flags["limit-reviews"]) : NaN; diff --git a/packages/core/src/cli/commands/context.ts b/packages/core/src/cli/commands/context.ts index a2bf09ce01..482299a14e 100644 --- a/packages/core/src/cli/commands/context.ts +++ b/packages/core/src/cli/commands/context.ts @@ -2,6 +2,7 @@ import { rerankSetup } from "../../lib/registry.js"; import { assembleContext } from "../../lib/context-assembler.js"; import { loadVecSupport } from "../../lib/db.js"; import type { CoreCommand } from "../types.js"; +import { positiveIntegerFlag } from "../flags.js"; import { openReadonlyDb, parseArgs, UsageError } from "../io.js"; const HELP = `brain context — assemble a token-limited context block @@ -20,12 +21,12 @@ export const contextCommand: CoreCommand = { throw new UsageError("Usage: brain context [--max-tokens N]"); } + // Read before the database is opened: a malformed budget runs no query. + const maxTokens = positiveIntegerFlag(flags, "max-tokens"); + const db = openReadonlyDb(cli.brain); try { await loadVecSupport(db); - const maxTokens = flags["max-tokens"] - ? parseInt(flags["max-tokens"] as string, 10) - : undefined; const context = await assembleContext(db, cli.brain, { query, maxTokens, diff --git a/packages/core/src/cli/commands/doctor.ts b/packages/core/src/cli/commands/doctor.ts index f6221e47a3..b013dbbbee 100644 --- a/packages/core/src/cli/commands/doctor.ts +++ b/packages/core/src/cli/commands/doctor.ts @@ -12,6 +12,8 @@ import { getMeta, embeddingIdentityMatches, SCHEMA_VERSION as EXPECTED_SCHEMA_VERSION, + vecVersion, + vectorCount, } from "../../lib/db.js"; import { indexAll } from "../../lib/indexer.js"; import { migrateSidecarCaches } from "../../lib/indexer/caches.js"; @@ -424,7 +426,7 @@ async function checkEmbeddings(cli: CliContext): Promise { let vecCount = 0; try { - vecCount = (db.prepare("SELECT COUNT(*) as n FROM vec_chunks").get() as { n: number }).n; + vecCount = vectorCount(db); } catch { /* vec table absent */ } @@ -620,7 +622,7 @@ async function checkSqliteVecMac(): Promise { const { load } = await import("sqlite-vec"); const db = new Database(":memory:"); load(db); - db.prepare("SELECT vec_version()").get(); + vecVersion(db); db.close(); return { id: "sqlite-vec-macos", status: "pass", detail: "sqlite-vec loads on this macOS SQLite" }; } catch (e) { diff --git a/packages/core/src/cli/commands/eval.ts b/packages/core/src/cli/commands/eval.ts index b5b1b674fc..64a4622294 100644 --- a/packages/core/src/cli/commands/eval.ts +++ b/packages/core/src/cli/commands/eval.ts @@ -5,7 +5,7 @@ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter" import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path"; import type { BrainContext } from "../../lib/context.js"; -import { loadVecSupport } from "../../lib/db.js"; +import { documentCount, isIndexedDocument, loadVecSupport, markdownContentHashes } from "../../lib/db.js"; import { getMarkdownFiles } from "../../lib/indexer.js"; import { rerankSetup, type RerankSetup } from "../../lib/registry.js"; import { envRerankMode } from "../../lib/reranker.js"; @@ -204,7 +204,6 @@ function resolveQueries(brain: BrainContext, queries: EvalQuery[], now: Date): R * points out of it is outside. */ function checkExpectedPaths(root: string, db: Database, queries: ResolvedQuery[]): void { - const indexed = db.prepare("SELECT 1 FROM documents WHERE path = ?"); const outside: string[] = []; const missing: string[] = []; const notFiles: string[] = []; @@ -216,7 +215,7 @@ function checkExpectedPaths(root: string, db: Database, queries: ResolvedQuery[] else if (!existsSync(full)) missing.push(`${query.id}: ${path}`); // `full` is canonical, so a symlink has already been followed here. else if (!statSync(full).isFile()) notFiles.push(`${query.id}: ${path}`); - else if (!indexed.get(path)) unindexed.push(`${query.id}: ${path}`); + else if (!isIndexedDocument(db, path)) unindexed.push(`${query.id}: ${path}`); } } if (outside.length > 0) { @@ -246,10 +245,7 @@ function checkExpectedPaths(root: string, db: Database, queries: ResolvedQuery[] * skips as well. */ function checkIndexFresh(brain: BrainContext, db: Database, scanner: ContaminationScanner): void { - const rows = db - .prepare("SELECT path, content_hash FROM documents WHERE asset_type = 'markdown'") - .all() as { path: string; content_hash: string | null }[]; - const hashes = new Map(rows.map((r) => [r.path, r.content_hash])); + const hashes = markdownContentHashes(db); const stale: string[] = []; const onDisk = getMarkdownFiles(brain.root, brain.taxonomy); @@ -690,7 +686,7 @@ async function runEval(args: string[], cli: CliContext): Promise { rows.push(...aggregate(mode, outcomes, ks)); } - const documents = (db.prepare("SELECT COUNT(*) AS n FROM documents").get() as { n: number }).n; + const documents = documentCount(db); const meta = { version: packageVersion(), source: checkoutSource(), diff --git a/packages/core/src/cli/commands/list.ts b/packages/core/src/cli/commands/list.ts index 963d31ae3f..a0b4cb9386 100644 --- a/packages/core/src/cli/commands/list.ts +++ b/packages/core/src/cli/commands/list.ts @@ -2,6 +2,7 @@ import type { SearchOptions } from "../../lib/types.js"; import { filterSearch } from "../../lib/search-engine.js"; import { DEFAULT_LIST_LIMIT, listLimitSchema, MAX_LIST_LIMIT } from "../../lib/ops/read.js"; import type { CoreCommand } from "../types.js"; +import { stringFlag } from "../flags.js"; import { emit, type Flags, openReadonlyDb, parseArgs, UsageError } from "../io.js"; const HELP = `brain list — list/browse documents @@ -34,18 +35,20 @@ export const listCommand: CoreCommand = { helpBlock: HELP, async run(args, cli) { const { flags } = parseArgs(args); - // Validated before the database is opened: a bad limit runs no query. + // Validated before the database is opened: a bad limit or a filter flag + // without a value runs no query. const limit = parseListLimit(flags.limit); + const status = stringFlag(flags, "status"); + const opts: SearchOptions = { + type: stringFlag(flags, "type"), + tag: stringFlag(flags, "tag"), + status, + relevance: stringFlag(flags, "relevance"), + includeArchived: status === "archived" || flags["include-archived"] === true, + limit, + }; const db = openReadonlyDb(cli.brain); try { - const opts: SearchOptions = { - type: flags.type as string | undefined, - tag: flags.tag as string | undefined, - status: flags.status as string | undefined, - relevance: flags.relevance as string | undefined, - includeArchived: flags.status === "archived" || flags["include-archived"] === true, - limit, - }; const results = filterSearch(db, opts); diff --git a/packages/core/src/cli/commands/read.ts b/packages/core/src/cli/commands/read.ts index d5a2d6aadc..31b0ddac58 100644 --- a/packages/core/src/cli/commands/read.ts +++ b/packages/core/src/cli/commands/read.ts @@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "fs"; import { readDocumentPart, SectionNotFoundError } from "../../lib/document-parts.js"; import { safeResolve } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; +import { stringFlag } from "../flags.js"; import { parseArgs, UsageError } from "../io.js"; const HELP = `brain read — print a document (frontmatter included) @@ -47,7 +48,7 @@ export const readCommand: CoreCommand = { try { console.log( readDocumentPart(readFileSync(fullPath, "utf-8"), { - section: flags.section as string | undefined, + section: stringFlag(flags, "section"), maxTokens, sectionHint: '--section ""', }) diff --git a/packages/core/src/cli/commands/search.ts b/packages/core/src/cli/commands/search.ts index 5b0732a19e..3484231e1f 100644 --- a/packages/core/src/cli/commands/search.ts +++ b/packages/core/src/cli/commands/search.ts @@ -3,8 +3,11 @@ import { hybridSearch, isIsoDate } from "../../lib/search-engine.js"; import { loadVecSupport } from "../../lib/db.js"; import { rerankSetup } from "../../lib/registry.js"; import type { CoreCommand } from "../types.js"; +import { enumFlag, positiveIntegerFlag, stringFlag } from "../flags.js"; import { emit, openReadonlyDb, parseArgs, today, UsageError } from "../io.js"; +const SEARCH_MODES = ["fts", "vector", "hybrid"] as const satisfies ReadonlyArray; + const DATE_FLAGS = ["updated-since", "updated-before", "deadline-from", "deadline-to"] as const; const HELP = `brain search — hybrid FTS5 + vector search @@ -48,9 +51,15 @@ export const searchCommand: CoreCommand = { throw new UsageError(`--${flag} needs a date written YYYY-MM-DD, got ${JSON.stringify(value)}`); } } - if (flags.sort !== undefined && !(SEARCH_SORTS as readonly unknown[]).includes(flags.sort)) { - throw new UsageError(`--sort must be one of ${SEARCH_SORTS.join(", ")}, got ${JSON.stringify(flags.sort)}`); - } + // Every flag is read here, before the database is opened: a malformed + // value is a usage error that runs no query (#1352). + const sort = enumFlag(flags, "sort", SEARCH_SORTS); + const mode = enumFlag(flags, "mode", SEARCH_MODES) ?? "hybrid"; + const limit = positiveIntegerFlag(flags, "limit") ?? 20; + const type = stringFlag(flags, "type"); + const tag = stringFlag(flags, "tag"); + const relevance = stringFlag(flags, "relevance"); + const status = stringFlag(flags, "status"); let setup; try { @@ -62,22 +71,23 @@ export const searchCommand: CoreCommand = { } const opts: SearchOptions = { query, - mode: (flags.mode as SearchOptions["mode"]) || "hybrid", + mode, rerank: setup.rerank, - type: flags.type as string | undefined, - tag: flags.tag as string | undefined, - relevance: flags.relevance as string | undefined, - status: flags.status as string | undefined, - includeArchived: flags.status === "archived" || flags["include-archived"] === true, + type, + tag, + relevance, + status, + includeArchived: status === "archived" || flags["include-archived"] === true, assetsOnly: flags["assets-only"] === true, chunks: flags.chunks === true, - limit: flags.limit ? parseInt(flags.limit as string, 10) : 20, - updatedSince: flags["updated-since"] as string | undefined, - updatedBefore: flags["updated-before"] as string | undefined, + limit, + // The date flags are checked above; these reads only narrow the type. + updatedSince: stringFlag(flags, "updated-since"), + updatedBefore: stringFlag(flags, "updated-before"), // --upcoming is sugar; an explicit --deadline-from or --sort wins. - deadlineFrom: (flags["deadline-from"] as string | undefined) ?? (flags.upcoming ? today() : undefined), - deadlineTo: flags["deadline-to"] as string | undefined, - sort: (flags.sort as SearchOptions["sort"]) ?? (flags.upcoming ? "deadline" : undefined), + deadlineFrom: stringFlag(flags, "deadline-from") ?? (flags.upcoming ? today() : undefined), + deadlineTo: stringFlag(flags, "deadline-to"), + sort: sort ?? (flags.upcoming ? "deadline" : undefined), }; const dated = opts.updatedSince || opts.updatedBefore || opts.deadlineFrom || opts.deadlineTo; diff --git a/packages/core/src/cli/commands/tags.ts b/packages/core/src/cli/commands/tags.ts index 9285e0512b..1c8ce5e441 100644 --- a/packages/core/src/cli/commands/tags.ts +++ b/packages/core/src/cli/commands/tags.ts @@ -1,6 +1,6 @@ import type { Database } from "bun:sqlite"; -import { openDatabase } from "../../lib/db.js"; +import { documentCount, openDatabase } from "../../lib/db.js"; import { tagReport } from "../../lib/tags.js"; import type { TagReport } from "../../lib/tags.js"; import { applyTagChanges, indexAndAccept } from "../../lib/tags-apply.js"; @@ -119,7 +119,7 @@ export const tagsCommand: CoreCommand = { if (!dryRun) { try { db = openDatabase(cli.brain.dbPath); - db.prepare("SELECT COUNT(*) FROM documents").get(); + documentCount(db); } catch (e) { closeQuietly(db); warnings.push(`cannot open the index (${(e as Error).message}); nothing was rewritten`); diff --git a/packages/core/src/cli/flags.ts b/packages/core/src/cli/flags.ts new file mode 100644 index 0000000000..c99dbc9b4e --- /dev/null +++ b/packages/core/src/cli/flags.ts @@ -0,0 +1,47 @@ +/** + * Typed reads of parsed CLI flags (#1352). `parseArgs` stores a flag's value + * as a string, or `true` when the flag has no value (it is last, or the next + * argument is another `--flag`); a repeated flag keeps its last value. These + * accessors turn a value of the wrong kind into a {@link UsageError} instead + * of letting `true`, `NaN` or an unknown enum member flow into a query. + * + * Each returns `undefined` when the flag is absent, so a command keeps its own + * default. Call them before opening the database: a malformed flag then runs + * no query. + */ + +import { type Flags, UsageError } from "./io.js"; + +/** The flag's string value. A flag given without a value is a usage error. */ +export function stringFlag(flags: Flags, name: string): string | undefined { + const raw = flags[name]; + if (raw === undefined) return undefined; + if (typeof raw !== "string") throw new UsageError(`--${name} needs a value`); + return raw; +} + +/** + * The flag as a whole number of 1 or more. The whole argument must be an + * integer literal, as for `brain list --limit`: `10abc` and `1.5` are refused + * rather than read as 10 and 1, and `0` or a negative is refused rather than + * passed on. There is no upper bound. + */ +export function positiveIntegerFlag(flags: Flags, name: string): number | undefined { + const raw = flags[name]; + if (raw === undefined) return undefined; + const value = typeof raw === "string" && /^-?\d+$/.test(raw) ? Number(raw) : NaN; + if (!(value >= 1)) { + throw new UsageError(`--${name} must be a whole number of 1 or more, got ${JSON.stringify(raw)}`); + } + return value; +} + +/** The flag's value when it is one of `values`; anything else is a usage error. */ +export function enumFlag(flags: Flags, name: string, values: readonly T[]): T | undefined { + const raw = flags[name]; + if (raw === undefined) return undefined; + if (typeof raw !== "string" || !(values as readonly string[]).includes(raw)) { + throw new UsageError(`--${name} must be one of ${values.join(", ")}, got ${JSON.stringify(raw)}`); + } + return raw as T; +} diff --git a/packages/core/src/lib/briefing-reads.ts b/packages/core/src/lib/briefing-reads.ts new file mode 100644 index 0000000000..23741c0308 --- /dev/null +++ b/packages/core/src/lib/briefing-reads.ts @@ -0,0 +1,71 @@ +/** + * The index reads `brain briefing` makes for its sections, kept out of the + * command so the CLI holds no SQL. The silent-edit section reads + * `silentEdits` (hygiene.ts), the one query hygiene shares. + */ +import type { Database } from "bun:sqlite"; + +/** A document the focus document links to. */ +export interface FocusLinkedDocument { + path: string; + title: string; + type: string; + updated: string; + summary: string | null; +} + +/** Every indexed document `path` wiki-links to, most recently updated first. */ +export function focusLinkedDocuments(db: Database, path: string): FocusLinkedDocument[] { + return db + .prepare( + `SELECT d.path, d.title, d.type, d.updated, d.summary + FROM links l + JOIN documents d ON d.id = l.target_id + WHERE l.source_id = (SELECT id FROM documents WHERE path = ?) + ORDER BY d.updated DESC` + ) + .all(path) as FocusLinkedDocument[]; +} + +/** A non-archived document with a deadline. */ +export interface DeadlineRow { + deadline: string; + path: string; + title: string; + summary: string | null; +} + +/** Non-archived documents whose deadline falls in `from`..`to` (inclusive), soonest first. */ +export function upcomingDeadlines(db: Database, from: string, to: string): DeadlineRow[] { + return db + .prepare( + `SELECT deadline, path, title, summary FROM documents + WHERE deadline >= ? AND deadline <= ? AND status != 'archived' + ORDER BY deadline ASC` + ) + .all(from, to) as DeadlineRow[]; +} + +/** A non-archived document whose `next_review` has passed. */ +export interface OverdueReviewRow { + next_review: string; + path: string; + title: string; +} + +/** Non-archived documents whose `next_review` is before `today`, longest overdue first. */ +export function overdueReviewRows(db: Database, today: string): OverdueReviewRow[] { + return db + .prepare( + `SELECT next_review, path, title FROM documents + WHERE next_review IS NOT NULL AND next_review < ? AND status != 'archived' + ORDER BY next_review ASC` + ) + .all(today) as OverdueReviewRow[]; +} + +/** The indexed frontmatter `updated` of `path`; null when it is not indexed or has none. */ +export function documentUpdated(db: Database, path: string): string | null { + const row = db.prepare("SELECT updated FROM documents WHERE path = ?").get(path) as { updated: string | null } | null; + return row?.updated ?? null; +} diff --git a/packages/core/src/lib/db.ts b/packages/core/src/lib/db.ts index a5c6154321..311ed95408 100644 --- a/packages/core/src/lib/db.ts +++ b/packages/core/src/lib/db.ts @@ -758,7 +758,7 @@ export function storedVectorWidth(db: Database, configured: number): number { */ export function hasVecSupport(db: Database): boolean { try { - db.prepare("SELECT vec_version()").get(); + vecVersion(db); return true; } catch { return false; @@ -811,3 +811,34 @@ export function setMeta(db: Database, key: string, value: string): void { [key, value] ); } + +/** + * The loaded sqlite-vec extension's version. Throws (with SQLite's message) + * when the extension is not loaded into `db`. + */ +export function vecVersion(db: Database): string { + return (db.prepare("SELECT vec_version() AS v").get() as { v: string }).v; +} + +/** How many vectors `vec_chunks` holds. Throws when the table is absent or sqlite-vec is not loaded. */ +export function vectorCount(db: Database): number { + return (db.prepare("SELECT COUNT(*) as n FROM vec_chunks").get() as { n: number }).n; +} + +/** How many documents the index holds. Throws when the index cannot be read. */ +export function documentCount(db: Database): number { + return (db.prepare("SELECT COUNT(*) AS n FROM documents").get() as { n: number }).n; +} + +/** Whether the index holds a document at `path`. */ +export function isIndexedDocument(db: Database, path: string): boolean { + return Boolean(db.query("SELECT 1 FROM documents WHERE path = ?").get(path)); +} + +/** The indexed content hash of every markdown document, by path. */ +export function markdownContentHashes(db: Database): Map { + const rows = db + .prepare("SELECT path, content_hash FROM documents WHERE asset_type = 'markdown'") + .all() as { path: string; content_hash: string | null }[]; + return new Map(rows.map((r) => [r.path, r.content_hash])); +} diff --git a/packages/core/src/lib/graph/queries.ts b/packages/core/src/lib/graph/queries.ts index 5e03a9c67b..73d82b2c4a 100644 --- a/packages/core/src/lib/graph/queries.ts +++ b/packages/core/src/lib/graph/queries.ts @@ -1,13 +1,14 @@ /** - * Read side of the graph, used by the `brain graph` CLI. - * - * ui-server has its own reader over the same tables (it deliberately does not - * depend on core). Both are governed by docs/integration-contract.md — change - * the table shapes and both must move. + * The `brain graph` CLI's graph modes: the CLI profile of the shared graph + * reader (`GraphReader`, `./reader.ts`). This adapter owns the `--json` + * shapes and node materialization; the reader's header lists every way this + * profile differs from the supported `./queries` API. Both read the same + * tables, which docs/integration-contract.md governs. */ import type { Database } from "bun:sqlite"; +import { CLI_GRAPH_PROFILE, GraphReader, VIRTUAL_ROOT_ID, parseGraphRootKey, type Walk } from "./reader.js"; import type { GraphDirection, GraphEdgeRecord, @@ -15,14 +16,12 @@ import type { GraphSubgraph, } from "./types.js"; -/** Depth beyond this stops being a neighbourhood and becomes the whole vault. */ -export const MAX_EGO_DEPTH = 3; -/** Discovery rings past this are noise at any realistic corpus size. */ -export const MAX_DISCOVERY_DEPTH = 8; -/** Default staleness horizon, matching the core taxonomy default. */ -export const DEFAULT_STALE_DAYS = 180; -/** The synthesized virtual-root node; no document carries id 0. */ -export const VIRTUAL_ROOT_ID = 0; +export { + DEFAULT_STALE_DAYS, + MAX_DISCOVERY_DEPTH, + MAX_NEIGHBORHOOD_DEPTH as MAX_EGO_DEPTH, + VIRTUAL_ROOT_ID, +} from "./reader.js"; interface DocumentRow { id: number; @@ -42,97 +41,49 @@ interface MetricsRow { } /** - * Nodes, both adjacency directions and degrees, straight from `links` — no - * derived table involved. Every mode that walks the graph per request (ego, - * arbitrary-root discovery, orphan detection) runs off this, so those modes - * keep working before the first precompute. + * The CLI's nodes, in document id order, over the reader's link structure. + * Degrees and walks come straight from `links` — no derived table involved — + * so the ego, explicit-root discovery and orphan modes keep working before the + * first precompute. */ -interface Adjacency { +interface CliGraph { + reader: GraphReader; docs: Map; - idByPath: Map; out: Map; in: Map; edges: GraphEdgeRecord[]; } -function loadAdjacency(db: Database): Adjacency { +/** Every CLI graph read selects the CLI profile here, and only here. */ +function cliReader(db: Database): GraphReader { + return new GraphReader(db, CLI_GRAPH_PROFILE); +} + +function openGraph(db: Database): CliGraph { + const reader = cliReader(db); const docs = new Map(); - const idByPath = new Map(); const rows = db .prepare( - `SELECT id, path, title, type, updated - FROM documents WHERE asset_type = 'markdown' ORDER BY id` + `SELECT d.id AS id, d.path AS path, d.title AS title, d.type AS type, d.updated AS updated + FROM documents d WHERE ${reader.scope} ORDER BY d.id` ) .all() as DocumentRow[]; - for (const row of rows) { - docs.set(row.id, row); - idByPath.set(row.path, row.id); - } - - const out = new Map(); - const inbound = new Map(); - const edges: GraphEdgeRecord[] = []; - const seen = new Set(); - - const linkRows = db - .prepare( - `SELECT source_id AS source, target_id AS target - FROM links WHERE target_id IS NOT NULL ORDER BY source_id, target_id` - ) - .all() as { source: number; target: number }[]; - - for (const link of linkRows) { - if (!docs.has(link.source) || !docs.has(link.target)) continue; - if (link.source === link.target) continue; - const key = `${link.source}>${link.target}`; - if (seen.has(key)) continue; - seen.add(key); - - edges.push({ source: link.source, target: link.target }); - - const outbound = out.get(link.source); - if (outbound) outbound.push(link.target); - else out.set(link.source, [link.target]); - - const incoming = inbound.get(link.target); - if (incoming) incoming.push(link.source); - else inbound.set(link.target, [link.source]); - } - - return { docs, idByPath, out, in: inbound, edges }; -} - -function neighbors(adjacency: Adjacency, id: number, direction: GraphDirection): number[] { - if (direction === "out") return adjacency.out.get(id) ?? []; - if (direction === "in") return adjacency.in.get(id) ?? []; - return [...(adjacency.out.get(id) ?? []), ...(adjacency.in.get(id) ?? [])]; -} - -/** - * A read-only connection never runs migrations, so these tables are simply - * absent on a pre-v8 database. Missing derived data degrades every mode to the - * links-only view rather than failing the command. - */ -function queryOrEmpty(db: Database, sql: string, params: unknown[] = []): T[] { - try { - return db.prepare(sql).all(...(params as never[])) as T[]; - } catch { - return []; - } + for (const row of rows) docs.set(row.id, row); + const links = reader.links(); + return { reader, docs, out: links.out, in: links.in, edges: links.edges }; } -function loadMetrics(db: Database): Map { +function loadMetrics(graph: CliGraph): Map { const metrics = new Map(); - for (const row of queryOrEmpty(db, "SELECT * FROM graph_metrics")) { + for (const row of graph.reader.derived("SELECT * FROM graph_metrics")) { metrics.set(row.document_id, row); } return metrics; } -function loadLayout(db: Database, mode = "clusters"): Map { +function loadLayout(graph: CliGraph, mode = "clusters"): Map { const layout = new Map(); - const rows = queryOrEmpty<{ id: number; x: number; y: number }>( - db, + const rows = graph.reader.derived<{ id: number; x: number; y: number }>( "SELECT document_id AS id, x, y FROM graph_layouts WHERE mode = ?", [mode] ); @@ -143,7 +94,7 @@ function loadLayout(db: Database, mode = "clusters"): Map = {} ): GraphQueryNode { @@ -152,8 +103,8 @@ function toNode( path: doc.path, title: doc.title, type: doc.type, - inDegree: metrics?.in_degree ?? (adjacency.in.get(doc.id) ?? []).length, - outDegree: metrics?.out_degree ?? (adjacency.out.get(doc.id) ?? []).length, + inDegree: metrics?.in_degree ?? (graph.in.get(doc.id) ?? []).length, + outDegree: metrics?.out_degree ?? (graph.out.get(doc.id) ?? []).length, }; if (metrics) { if (metrics.community !== null) node.community = metrics.community; @@ -162,9 +113,19 @@ function toNode( return { ...node, ...extra }; } -/** Edges with both endpoints inside `ids`. */ -function inducedEdges(adjacency: Adjacency, ids: Set): GraphEdgeRecord[] { - return adjacency.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target)); +function degree(graph: CliGraph, id: number): number { + return (graph.out.get(id) ?? []).length + (graph.in.get(id) ?? []).length; +} + +const EMPTY: () => GraphSubgraph = () => ({ nodes: [], edges: [], truncated: false }); + +/** Nodes for every reached id, in walk order, with edges among them. */ +function walkScene(graph: CliGraph, walk: Walk, cap: number): GraphSubgraph { + const metrics = loadMetrics(graph); + const nodes = [...walk.distances.entries()].map(([id, distance]) => + toNode(graph.docs.get(id)!, graph, metrics.get(id), { distance }) + ); + return graph.reader.scene(nodes, graph.edges, cap, walk.truncated); } export interface ClusterGraphOptions { @@ -179,27 +140,22 @@ export interface ClusterGraphOptions { * first v8 index run — the caller reports that, this returns no rows. */ export function getClusterGraph(db: Database, options: ClusterGraphOptions = {}): GraphSubgraph { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const layout = loadLayout(db); - const includeIsolates = options.includeIsolates ?? true; + const graph = openGraph(db); + const metrics = loadMetrics(graph); + const layout = loadLayout(graph); + const includeIsolates = graph.reader.includeIsolates(options.includeIsolates); const nodes: GraphQueryNode[] = []; - const ids = new Set(); - for (const doc of adjacency.docs.values()) { + for (const doc of graph.docs.values()) { const nodeMetrics = metrics.get(doc.id); if (options.community !== undefined && nodeMetrics?.community !== options.community) continue; - - const degree = - (adjacency.out.get(doc.id) ?? []).length + (adjacency.in.get(doc.id) ?? []).length; - if (!includeIsolates && degree === 0) continue; + if (!includeIsolates && degree(graph, doc.id) === 0) continue; const position = layout.get(doc.id); - nodes.push(toNode(doc, adjacency, nodeMetrics, position ? { x: position.x, y: position.y } : {})); - ids.add(doc.id); + nodes.push(toNode(doc, graph, nodeMetrics, position ? { x: position.x, y: position.y } : {})); } - return { nodes, edges: inducedEdges(adjacency, ids), truncated: false }; + return graph.reader.scene(nodes, graph.edges, graph.reader.profile.sceneNodes); } export interface EgoGraphOptions { @@ -214,34 +170,12 @@ export interface EgoGraphOptions { * one mode that works against a database that has never been precomputed. */ export function getEgoGraph(db: Database, options: EgoGraphOptions): GraphSubgraph { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const depth = Math.min(Math.max(options.depth ?? 1, 1), MAX_EGO_DEPTH); - const direction = options.direction ?? "both"; - - const centerId = adjacency.idByPath.get(options.center); - if (centerId === undefined) return { nodes: [], edges: [], truncated: false }; - - const distances = new Map([[centerId, 0]]); - let frontier = [centerId]; - for (let hop = 1; hop <= depth && frontier.length > 0; hop++) { - const next: number[] = []; - for (const id of frontier) { - for (const neighbor of neighbors(adjacency, id, direction)) { - if (distances.has(neighbor)) continue; - distances.set(neighbor, hop); - next.push(neighbor); - } - } - frontier = next; - } - - const ids = new Set(distances.keys()); - const nodes = [...distances.entries()].map(([id, distance]) => - toNode(adjacency.docs.get(id)!, adjacency, metrics.get(id), { distance }) - ); + const graph = openGraph(db); + const centerId = graph.reader.lookup(options.center); + if (centerId === null) return EMPTY(); - return { nodes, edges: inducedEdges(adjacency, ids), truncated: false }; + const walk = graph.reader.neighborhood(centerId, options.depth, options.direction); + return walkScene(graph, walk, graph.reader.profile.neighborhoodNodes); } export interface DiscoveryGraphOptions { @@ -261,73 +195,49 @@ export function getDiscoveryGraph( db: Database, options: DiscoveryGraphOptions = {} ): GraphSubgraph { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const direction = options.direction ?? "out"; - const maxDepth = Math.min(Math.max(options.maxDepth ?? MAX_DISCOVERY_DEPTH, 1), MAX_DISCOVERY_DEPTH); + const graph = openGraph(db); + const maxDepth = graph.reader.discoveryDepth(options.maxDepth); if (options.root) { - const rootId = adjacency.idByPath.get(options.root); - if (rootId === undefined) return { nodes: [], edges: [], truncated: false }; - - const distances = new Map([[rootId, 0]]); - let frontier = [rootId]; - for (let hop = 1; hop <= maxDepth && frontier.length > 0; hop++) { - const next: number[] = []; - for (const id of frontier) { - for (const neighbor of neighbors(adjacency, id, direction)) { - if (distances.has(neighbor)) continue; - distances.set(neighbor, hop); - next.push(neighbor); - } - } - frontier = next; - } + const rootId = graph.reader.lookup(options.root); + if (rootId === null) return EMPTY(); - const ids = new Set(distances.keys()); - const nodes = [...distances.entries()].map(([id, distance]) => - toNode(adjacency.docs.get(id)!, adjacency, metrics.get(id), { distance }) - ); - return { nodes, edges: inducedEdges(adjacency, ids), truncated: false }; + const walk = graph.reader.discovery(rootId, maxDepth, options.direction); + return walkScene(graph, walk, graph.reader.profile.sceneNodes); } - const rootKey = getGraphMetaValue(db, "graph_root"); - const rows = queryOrEmpty<{ id: number; distance: number; parentId: number | null }>( - db, - "SELECT document_id AS id, distance, parent_id AS parentId FROM graph_root_distances" - ); - + const metrics = loadMetrics(graph); + const root = parseGraphRootKey(getGraphMetaValue(db, "graph_root")); const nodes: GraphQueryNode[] = []; const ids = new Set(); - for (const row of rows) { - const doc = adjacency.docs.get(row.id); - if (!doc || row.distance > maxDepth) continue; - nodes.push(toNode(doc, adjacency, metrics.get(row.id), { distance: row.distance })); - ids.add(row.id); + for (const [id, distance] of graph.reader.rootDistances()) { + const doc = graph.docs.get(id); + if (!doc || distance > maxDepth) continue; + nodes.push(toNode(doc, graph, metrics.get(id), { distance })); + ids.add(id); } - const edges = inducedEdges(adjacency, ids); - - // A virtual root is drawn from its recorded seed list; an indexed root is - // already one of the nodes above at distance 0. - if (rootKey?.startsWith("virtual:")) { - const path = rootKey.slice("virtual:".length); + // A virtual root is drawn from its recorded seed list, after the edges + // between documents; an indexed root is already one of the nodes above at + // distance 0. + const edges = [...graph.edges]; + if (root?.virtual) { nodes.unshift({ id: VIRTUAL_ROOT_ID, - path, - title: path, + path: root.path, + title: root.path, type: "index", inDegree: 0, outDegree: 0, distance: 0, virtual: true, }); - for (const seedId of readRootLinks(db)) { + for (const seedId of graph.reader.rootLinks(getGraphMetaValue(db, "graph_root_links"))) { if (ids.has(seedId)) edges.push({ source: VIRTUAL_ROOT_ID, target: seedId }); } } - return { nodes, edges, truncated: false }; + return graph.reader.scene(nodes, edges, graph.reader.profile.sceneNodes); } export interface MaintenanceOptions { @@ -355,44 +265,31 @@ export function getMaintenanceFindings( db: Database, options: MaintenanceOptions = {} ): MaintenanceFindings { - const adjacency = loadAdjacency(db); - const metrics = loadMetrics(db); - const staleDays = options.staleDays ?? DEFAULT_STALE_DAYS; + const graph = openGraph(db); + const metrics = loadMetrics(graph); + const staleDays = graph.reader.staleDays(options.staleDays); const root = getGraphMetaValue(db, "graph_root"); const cutoff = new Date(Date.now() - staleDays * 86_400_000).toISOString().split("T")[0]; const orphans: GraphQueryNode[] = []; const stale: (GraphQueryNode & { updated: string })[] = []; - for (const doc of adjacency.docs.values()) { - const degree = - (adjacency.out.get(doc.id) ?? []).length + (adjacency.in.get(doc.id) ?? []).length; - if (degree === 0) orphans.push(toNode(doc, adjacency, metrics.get(doc.id))); + for (const doc of graph.docs.values()) { + if (degree(graph, doc.id) === 0) orphans.push(toNode(doc, graph, metrics.get(doc.id))); if (doc.updated < cutoff) { - stale.push({ ...toNode(doc, adjacency, metrics.get(doc.id)), updated: doc.updated }); + stale.push({ ...toNode(doc, graph, metrics.get(doc.id)), updated: doc.updated }); } } const unreachable: GraphQueryNode[] = []; if (root) { - const reachable = new Set( - queryOrEmpty<{ id: number }>(db, "SELECT document_id AS id FROM graph_root_distances").map( - (row) => row.id - ) - ); - for (const doc of adjacency.docs.values()) { - if (!reachable.has(doc.id)) unreachable.push(toNode(doc, adjacency, metrics.get(doc.id))); + const reachable = graph.reader.rootDistances(); + for (const doc of graph.docs.values()) { + if (!reachable.has(doc.id)) unreachable.push(toNode(doc, graph, metrics.get(doc.id))); } } - const brokenLinks = db - .prepare( - `SELECT d.path AS sourcePath, l.target AS target - FROM links l JOIN documents d ON d.id = l.source_id - WHERE l.target_id IS NULL - ORDER BY d.path, l.target` - ) - .all() as { sourcePath: string; target: string }[]; + const brokenLinks = graph.reader.brokenLinks(); return { staleDays, root, orphans, unreachable, brokenLinks, stale }; } @@ -412,13 +309,13 @@ export interface GraphStats { /** Everything `brain graph stats` reports, straight out of the derived tables. */ export function getGraphStats(db: Database): GraphStats { - const communities = queryOrEmpty<{ + const reader = cliReader(db); + const communities = reader.derived<{ community: number; size: number; label: string | null; topTerms: string | null; }>( - db, "SELECT community, size, label, top_terms AS topTerms FROM graph_communities ORDER BY size DESC, community ASC" ).map((row) => ({ community: row.community, @@ -427,7 +324,7 @@ export function getGraphStats(db: Database): GraphStats { topTerms: parseJsonArray(row.topTerms), })); - const count = (sql: string): number => queryOrEmpty<{ n: number }>(db, sql)[0]?.n ?? 0; + const count = (sql: string): number => reader.derived<{ n: number }>(sql)[0]?.n ?? 0; const algoRaw = getGraphMetaValue(db, "graph_algo"); let algo: unknown = null; @@ -445,13 +342,7 @@ export function getGraphStats(db: Database): GraphStats { nodes: count("SELECT COUNT(*) AS n FROM graph_metrics"), // Counted the way the graph counts them — deduped, self-links dropped, and // links into binary assets excluded — so this agrees with `graph compute`. - edges: count( - `SELECT COUNT(*) AS n FROM ( - SELECT DISTINCT l.source_id, l.target_id FROM links l - JOIN documents s ON s.id = l.source_id AND s.asset_type = 'markdown' - JOIN documents t ON t.id = l.target_id AND t.asset_type = 'markdown' - WHERE l.source_id <> l.target_id)` - ), + edges: count(`SELECT COUNT(*) AS n FROM (${reader.edgeSql})`), brokenLinks: count("SELECT COUNT(*) AS n FROM links WHERE target_id IS NULL"), components: count("SELECT COUNT(DISTINCT component) AS n FROM graph_metrics"), reachable: count("SELECT COUNT(*) AS n FROM graph_root_distances"), @@ -471,17 +362,6 @@ function parseJsonArray(raw: string | null): string[] { } } -function readRootLinks(db: Database): number[] { - const raw = getGraphMetaValue(db, "graph_root_links"); - if (!raw) return []; - try { - const parsed = JSON.parse(raw); - return Array.isArray(parsed) ? parsed.map(Number).filter(Number.isInteger) : []; - } catch { - return []; - } -} - function getGraphMetaValue(db: Database, key: string): string | null { const row = db.prepare("SELECT value FROM index_metadata WHERE key = ?").get(key) as | { value: string } diff --git a/packages/core/src/lib/graph/reader.ts b/packages/core/src/lib/graph/reader.ts new file mode 100644 index 0000000000..1432f78adf --- /dev/null +++ b/packages/core/src/lib/graph/reader.ts @@ -0,0 +1,360 @@ +/** + * The one reader over the derived graph tables, behind both read surfaces in + * core: the `brain graph` CLI (`./queries.ts`) and the supported `./queries` + * API (`../../queries/graph.ts`), whose graph semantics are the former UI + * server's. Each surface selects a concrete profile below; profiles are not a + * public option and not an extension point (#1354). + * + * The reader owns the mechanics both surfaces share: which documents are + * nodes, the distinct edge list and its adjacency, path lookup, the + * breadth-first walk, depth/staleness defaults and bounds, the precomputed + * root distances, broken links and the scene caps. The adapters own their + * result shapes and error policy, which differ on purpose: + * + * - Node scope. The UI counts a NULL `asset_type` as markdown; the CLI + * requires `'markdown'`, as the precompute does. + * - Edge order. The CLI sorts edges by (source, target); the UI keeps the + * engine's DISTINCT order. + * - Caps. The UI bounds a neighborhood walk and scene at 1,500 nodes and every + * other scene at 5,000 nodes / 20,000 edges, ranked by pagerank, and reports + * `truncated`; it also limits each maintenance list to 5,000. The CLI has no + * cap or walk budget anywhere, so its `truncated` is always false. + * - Isolates. UI clusters exclude isolates unless asked; CLI clusters include + * them unless asked. (The UI judges isolation by precomputed degree, the CLI + * by the live links — that, like node degrees and layout fields, is node + * materialization and stays with each adapter.) + * - Paths and missing nodes. The UI strips a leading `./` or `/` and fails a + * missing center or root with `not_found`; the CLI matches the stored path + * exactly and returns an empty subgraph. + * - Old and uncomputed data. The UI refuses derived modes before v8 or before + * a precompute; the CLI reads whatever exists, degrading a missing derived + * table to no rows. + * - `staleDays`. Both default to 180; the UI clamps to 1..3650, the CLI takes + * the value as given. The UI accepts a caller clock and compares the date + * prefix in SQL; the CLI uses the system clock and the whole string. + * - Root seed list. The UI keeps finite JSON numbers; the CLI coerces entries + * to integers. + * + * Every table read here is governed by docs/integration-contract.md. + */ + +import type { Database } from "bun:sqlite"; + +import type { GraphDirection, GraphEdgeRecord } from "./types.js"; + +/** Depth beyond this stops being a neighbourhood and becomes the whole vault. */ +export const MAX_NEIGHBORHOOD_DEPTH = 3; +/** Discovery rings past this are noise at any realistic corpus size. */ +export const MAX_DISCOVERY_DEPTH = 8; +/** Default staleness horizon, matching the core taxonomy default. */ +export const DEFAULT_STALE_DAYS = 180; +/** The synthesized virtual-root node; no document carries id 0. */ +export const VIRTUAL_ROOT_ID = 0; + +const VIRTUAL_ROOT_PREFIX = "virtual:"; + +export interface GraphProfile { + /** SQL predicate selecting graph nodes from a `documents` alias. */ + nodeScope(alias: string): string; + /** Appended to the distinct edge query. */ + edgeOrder: string; + /** Strip a leading `./` or `/` before looking a path up. */ + normalizePaths: boolean; + /** Cluster isolates when the caller does not say. */ + isolatesByDefault: boolean; + /** Walk budget and scene node cap for a neighborhood. */ + neighborhoodNodes: number; + /** Walk budget and scene node cap for every other scene. */ + sceneNodes: number; + sceneEdges: number; + /** Row limit for each maintenance list; Infinity for none. */ + findingLimit: number; + /** Inclusive staleDays bounds, or null to take the value as given. */ + staleDays: { min: number; max: number } | null; + /** How the precomputed root seed list is read. */ + rootLinks: "finite" | "integer"; + /** Whether a missing derived table reads as no rows instead of failing. */ + degradeDerived: boolean; +} + +/** The supported `./queries` graph: the former UI server's reader. */ +export const UI_GRAPH_PROFILE: GraphProfile = Object.freeze({ + nodeScope: (alias: string) => `COALESCE(${alias}.asset_type, 'markdown') = 'markdown'`, + edgeOrder: "", + normalizePaths: true, + isolatesByDefault: false, + neighborhoodNodes: 1500, + sceneNodes: 5000, + sceneEdges: 20000, + findingLimit: 5000, + staleDays: Object.freeze({ min: 1, max: 3650 }), + rootLinks: "finite", + degradeDerived: false, +}); + +/** `brain graph export` and `brain graph stats`. */ +export const CLI_GRAPH_PROFILE: GraphProfile = Object.freeze({ + nodeScope: (alias: string) => `${alias}.asset_type = 'markdown'`, + edgeOrder: " ORDER BY source, target", + normalizePaths: false, + isolatesByDefault: true, + neighborhoodNodes: Infinity, + sceneNodes: Infinity, + sceneEdges: Infinity, + findingLimit: Infinity, + staleDays: null, + rootLinks: "integer", + degradeDerived: true, +}); + +/** The distinct edge list plus adjacency in both directions, in edge order. */ +export interface LinkStructure { + edges: GraphEdgeRecord[]; + out: Map; + in: Map; +} + +export interface Walk { + /** Hops from the start, in the order nodes were reached. */ + distances: Map; + /** The walk stopped at its node budget. */ + truncated: boolean; +} + +export interface Scene { + nodes: N[]; + edges: GraphEdgeRecord[]; + truncated: boolean; +} + +export interface GraphRootKey { + path: string; + virtual: boolean; +} + +/** Ranking inputs for a capped scene. */ +interface RankedNode { + id: number; + pagerank?: number; + virtual?: boolean; +} + +/** + * One request's read of the graph on a connection the caller owns: the + * supported API's root-bound snapshot or the CLI's resolved database. The + * reader never opens, closes or writes a connection. + */ +export class GraphReader { + private structure: LinkStructure | undefined; + + constructor( + private readonly db: Database, + readonly profile: GraphProfile + ) {} + + /** The node predicate over `documents d`. */ + get scope(): string { + return this.profile.nodeScope("d"); + } + + /** + * One edge per distinct (source, target) document pair — two wiki links that + * resolve to the same note are one edge — with self-links dropped and both + * ends graph nodes. Shared by the adjacency load and the edge counts so + * every count agrees with the edges drawn. + */ + get edgeSql(): string { + return `SELECT DISTINCT l.source_id AS source, l.target_id AS target + FROM links l + JOIN documents d ON d.id = l.source_id AND ${this.profile.nodeScope("d")} + JOIN documents t ON t.id = l.target_id AND ${this.profile.nodeScope("t")} + WHERE l.target_id IS NOT NULL AND l.target_id <> l.source_id${this.profile.edgeOrder}`; + } + + /** Loaded once per reader, straight from `links`: no derived table needed. */ + links(): LinkStructure { + if (this.structure) return this.structure; + const edges = this.db.query(this.edgeSql).all(); + const out = new Map(); + const inbound = new Map(); + for (const edge of edges) { + push(out, edge.source, edge.target); + push(inbound, edge.target, edge.source); + } + this.structure = { edges, out, in: inbound }; + return this.structure; + } + + /** The node id at `path`, or null when no graph node has it. */ + lookup(path: string): number | null { + const key = this.profile.normalizePaths ? path.replace(/^\.?\//, "") : path; + const row = this.db + .query<{ id: number }, [string]>(`SELECT d.id AS id FROM documents d WHERE ${this.scope} AND d.path = ?`) + .get(key); + return row?.id ?? null; + } + + /** Breadth-first, level by level, stopping at `maxDepth` hops or `budget` nodes. */ + walk(start: number, direction: GraphDirection, maxDepth: number, budget: number): Walk { + const structure = this.links(); + const distances = new Map([[start, 0]]); + let frontier = [start]; + let depth = 0; + let truncated = false; + while (frontier.length > 0 && depth < maxDepth && !truncated) { + depth++; + const next: number[] = []; + for (const id of frontier) { + const neighbors: number[] = []; + if (direction !== "in") neighbors.push(...(structure.out.get(id) ?? [])); + if (direction !== "out") neighbors.push(...(structure.in.get(id) ?? [])); + for (const neighbor of neighbors) { + if (distances.has(neighbor)) continue; + if (distances.size >= budget) { + truncated = true; + break; + } + distances.set(neighbor, depth); + next.push(neighbor); + } + if (truncated) break; + } + frontier = next; + } + return { distances, truncated }; + } + + /** The ego walk: depth 1..3 (default 1), both directions by default. */ + neighborhood(center: number, depth?: number, direction?: GraphDirection): Walk { + return this.walk( + center, + direction ?? "both", + clamp(depth ?? 1, 1, MAX_NEIGHBORHOOD_DEPTH), + this.profile.neighborhoodNodes + ); + } + + /** Depth 1..8, default 8. */ + discoveryDepth(maxDepth?: number): number { + return clamp(maxDepth ?? MAX_DISCOVERY_DEPTH, 1, MAX_DISCOVERY_DEPTH); + } + + /** The discovery walk from an explicit root, outbound by default. */ + discovery(root: number, maxDepth: number, direction?: GraphDirection): Walk { + return this.walk(root, direction ?? "out", maxDepth, this.profile.sceneNodes); + } + + includeIsolates(requested?: boolean): boolean { + return requested ?? this.profile.isolatesByDefault; + } + + staleDays(requested?: number): number { + const days = requested ?? DEFAULT_STALE_DAYS; + const bounds = this.profile.staleDays; + return bounds ? clamp(days, bounds.min, bounds.max) : days; + } + + /** + * Precomputed distances from the default root, in table order, optionally + * limited to `maxDepth`. Direction does not apply: the precomputed walk is + * the one that was run. + */ + rootDistances(maxDepth?: number): Map { + const rows = + maxDepth === undefined + ? this.derived<{ id: number; distance: number }>( + "SELECT document_id AS id, distance FROM graph_root_distances" + ) + : this.derived<{ id: number; distance: number }>( + "SELECT document_id AS id, distance FROM graph_root_distances WHERE distance <= ?", + [maxDepth] + ); + return new Map(rows.map((row) => [row.id, row.distance])); + } + + /** The precomputed virtual root's seed ids from `graph_root_links`. */ + rootLinks(raw: string | null | undefined): number[] { + if (!raw) return []; + try { + const parsed = JSON.parse(raw); + if (!Array.isArray(parsed)) return []; + return this.profile.rootLinks === "integer" + ? parsed.map(Number).filter(Number.isInteger) + : parsed.filter((id): id is number => Number.isFinite(id)); + } catch { + return []; + } + } + + /** Unresolved wiki links with their literal text, by source path then text. */ + brokenLinks(): { sourcePath: string; target: string }[] { + const limit = this.profile.findingLimit; + const sql = `SELECT d.path AS sourcePath, l.target AS target + FROM links l JOIN documents d ON d.id = l.source_id + WHERE l.target_id IS NULL + ORDER BY d.path ASC, l.target ASC`; + return Number.isFinite(limit) + ? this.db.query<{ sourcePath: string; target: string }, [number]>(`${sql} LIMIT ?`).all(limit) + : this.db.query<{ sourcePath: string; target: string }, []>(sql).all(); + } + + /** + * Narrows `edges` to the ones between kept nodes, applying the profile's + * caps. Over the node cap the highest-pagerank nodes survive (a virtual root + * always does — dropping the thing the view is rooted on would be + * nonsense); over the edge cap, the edges whose weaker end ranks highest. + */ + scene(nodes: N[], edges: GraphEdgeRecord[], nodeCap: number, walkTruncated = false): Scene { + let truncated = false; + let keptNodes = nodes; + if (nodes.length > nodeCap) { + truncated = true; + keptNodes = [...nodes] + .sort((a, b) => Number(b.virtual ?? false) - Number(a.virtual ?? false) || (b.pagerank ?? 0) - (a.pagerank ?? 0)) + .slice(0, nodeCap); + } + const ids = new Set(keptNodes.map((n) => n.id)); + let keptEdges = edges.filter((e) => ids.has(e.source) && ids.has(e.target)); + if (keptEdges.length > this.profile.sceneEdges) { + truncated = true; + const rank = new Map(keptNodes.map((n) => [n.id, n.pagerank ?? 0])); + keptEdges = keptEdges + .map((edge) => ({ edge, weight: Math.min(rank.get(edge.source) ?? 0, rank.get(edge.target) ?? 0) })) + .sort((a, b) => b.weight - a.weight) + .slice(0, this.profile.sceneEdges) + .map((entry) => entry.edge); + } + return { nodes: keptNodes, edges: keptEdges, truncated: truncated || walkTruncated }; + } + + /** + * A read of a derived (v8) table. A read-only connection never migrates, so + * on an older database the table is absent; a degrading profile reads that + * as no rows. + */ + derived(sql: string, params: (string | number)[] = []): T[] { + if (!this.profile.degradeDerived) return this.db.query(sql).all(...params); + try { + return this.db.prepare(sql).all(...params); + } catch { + return []; + } + } +} + +/** `graph_root` metadata: an indexed path, or `virtual:`. */ +export function parseGraphRootKey(raw: string | null | undefined): GraphRootKey | null { + if (!raw) return null; + if (raw.startsWith(VIRTUAL_ROOT_PREFIX)) return { path: raw.slice(VIRTUAL_ROOT_PREFIX.length), virtual: true }; + return { path: raw, virtual: false }; +} + +function push(map: Map, key: number, value: number): void { + const existing = map.get(key); + if (existing) existing.push(value); + else map.set(key, [value]); +} + +function clamp(value: number, min: number, max: number): number { + return Math.min(max, Math.max(min, value)); +} diff --git a/packages/core/src/lib/hygiene.ts b/packages/core/src/lib/hygiene.ts index 093aa7019a..029520c4db 100644 --- a/packages/core/src/lib/hygiene.ts +++ b/packages/core/src/lib/hygiene.ts @@ -394,21 +394,57 @@ const MS_PER_DAY = 86_400_000; /** Silent edits count once the file is this many days newer than its `updated`. */ const SILENT_EDIT_DAYS = 7; +/** A document whose file changed after its frontmatter `updated`, as the index holds it. */ +export interface SilentEdit { + path: string; + title: string; + /** The file's modification time when it was indexed. */ + file_mtime: string; + /** The frontmatter `updated` value. */ + updated: string; +} + /** - * Silently edited files: the same query `brain briefing` runs, without its - * row limit, kept when the file is more than SILENT_EDIT_DAYS newer than its - * frontmatter `updated`. + * The one silent-edit query: every non-archived document whose file is newer + * than its frontmatter `updated`, unless `brain accept-mtime` baselined that + * mtime. Most recently changed file first; `limit` keeps only the first that + * many. `brain briefing` lists these rows; hygiene keeps the ones that drifted + * far enough (`silentEditCandidates`). */ -export function silentEdits(db: Database): HygieneCandidate[] { - const rows = db - .prepare( - `SELECT file_mtime, updated, path FROM documents +export function silentEdits(db: Database, opts: { limit?: number } = {}): SilentEdit[] { + // A negative LIMIT is no limit in SQLite, so one statement serves both. + return db + .query( + `SELECT file_mtime, updated, path, title FROM documents WHERE file_mtime > updated AND (accepted_mtime IS NULL OR file_mtime > accepted_mtime) AND status != 'archived' - ORDER BY path` + ORDER BY file_mtime DESC LIMIT ?` ) - .all() as { file_mtime: string; updated: string; path: string }[]; + .all(opts.limit ?? -1) as SilentEdit[]; +} + +/** + * Baseline the current file mtimes as non-suspicious, so `silentEdits` stops + * reporting them: one indexed document's, or (no path) every document's. + * Returns how many documents changed. + */ +export function acceptMtimes(db: Database, path?: string): number { + return path === undefined + ? db.run("UPDATE documents SET accepted_mtime = file_mtime WHERE file_mtime IS NOT NULL").changes + : db.run("UPDATE documents SET accepted_mtime = file_mtime WHERE path = ? AND file_mtime IS NOT NULL", [path]).changes; +} + +/** SQLite's BINARY collation: byte order of the UTF-8 encodings. */ +const byUtf8 = (a: string, b: string) => Buffer.compare(Buffer.from(a), Buffer.from(b)); + +/** + * Silently edited files as hygiene candidates, in path order: the + * `silentEdits` rows whose file is more than SILENT_EDIT_DAYS newer than its + * frontmatter `updated`. + */ +export function silentEditCandidates(db: Database): HygieneCandidate[] { + const rows = silentEdits(db).sort((a, b) => byUtf8(a.path, b.path)); const out: HygieneCandidate[] = []; for (const row of rows) { const drift = Math.floor((Date.parse(row.file_mtime) - Date.parse(row.updated)) / MS_PER_DAY); @@ -652,7 +688,7 @@ export async function detectCandidates( } catch { failed.add("validation"); } - const silent = silentEdits(db).filter((c) => !inLog(c.path)).map((c) => withSource(c, { source: "hygiene", name: "silent-edit", severity: null })); + const silent = silentEditCandidates(db).filter((c) => !inLog(c.path)).map((c) => withSource(c, { source: "hygiene", name: "silent-edit", severity: null })); // Media awaiting a decision (#2780): the same inventory `brain sync` counts. let media: MediaInventory | null = null; try { diff --git a/packages/core/src/queries/graph.ts b/packages/core/src/queries/graph.ts index 8167f7ad26..546e773904 100644 --- a/packages/core/src/queries/graph.ts +++ b/packages/core/src/queries/graph.ts @@ -1,14 +1,18 @@ -/** Private UI-profile graph mechanics; core CLI graph defaults remain independent. */ +/** + * The supported `./queries` graph modes: the UI profile of the shared graph + * reader (`GraphReader`, `../lib/graph/reader.ts`). This adapter owns the + * result shapes, node materialization and typed failures; the reader's header + * lists every way this profile differs from the `brain graph` CLI. + */ import type { Database } from "bun:sqlite"; import { basename } from "path"; -import type { Node, Edge, Community, GraphMeta, Subgraph, Maintenance, Direction } from "./types.js"; +import type { Node, Community, GraphMeta, Subgraph, Maintenance, Direction } from "./types.js"; import { QueryFailure } from "./snapshot.js"; -const MAX_NODES = 5000; -const MAX_EDGES = 20000; -const MAX_NEIGHBORHOOD_NODES = 1500; -const MAX_NEIGHBORHOOD_DEPTH = 3; -const MAX_DISCOVERY_DEPTH = 8; -const DEFAULT_STALE_DAYS = 180; +import { GraphReader, UI_GRAPH_PROFILE, VIRTUAL_ROOT_ID, parseGraphRootKey } from "../lib/graph/reader.js"; +/** Every supported graph read selects the UI profile here, and only here. */ +function reader(db: Database): GraphReader { + return new GraphReader(db, UI_GRAPH_PROFILE); +} function requireComputedGraph(meta: Map): void { if (!meta.get("graph_computed_at")) throw new QueryFailure("not_computed"); @@ -27,7 +31,7 @@ interface NodeRow { y: number | null; } /** Only markdown notes are graph nodes; other assets carry no wiki links. */ -const MARKDOWN_ONLY = "COALESCE(d.asset_type, 'markdown') = 'markdown'"; +const MARKDOWN_ONLY = UI_GRAPH_PROFILE.nodeScope("d"); /** * The analytical columns come from tables that do not exist below schema v8, * so the select degrades to literals — that is what keeps the neighborhood @@ -82,119 +86,11 @@ function loadNodesByIds(db: Database, ids: number[], withGraphTables: boolean): } return out; } -function lookupDocumentId(db: Database, path: string): number { - const normalized = path.replace(/^\.?\//, ""); - const row = db - .query<{ - id: number; - }, [ - string - ]>(`SELECT d.id AS id FROM documents d WHERE ${MARKDOWN_ONLY} AND d.path = ?`) - .get(normalized); - if (!row) +function lookupDocumentId(graph: GraphReader, path: string): number { + const id = graph.lookup(path); + if (id === null) throw new QueryFailure("not_found"); - return row.id; -} -// --- link structure -------------------------------------------------------- -interface LinkStructure { - edges: Edge[]; - out: Map; - in: Map; -} -/** - * The one definition of an edge, shared by the adjacency load and the meta - * count so /api/graph/meta agrees with `brain graph stats`: one edge per - * distinct (source, target) DOCUMENT pair — two wiki links that resolve to the - * same note are one edge — self-links dropped, and both ends markdown, since - * non-markdown assets are not graph nodes. - */ -const DISTINCT_EDGES_SQL = `SELECT DISTINCT l.source_id AS source, l.target_id AS target - FROM links l - JOIN documents d ON d.id = l.source_id AND ${MARKDOWN_ONLY} - JOIN documents t ON t.id = l.target_id AND COALESCE(t.asset_type, 'markdown') = 'markdown' - WHERE l.target_id IS NOT NULL AND l.target_id <> l.source_id`; -/** The whole link table as an edge list plus adjacency maps in both directions. */ -function loadLinkStructure(db: Database): LinkStructure { - const edges = db.query(DISTINCT_EDGES_SQL).all(); - const out = new Map(); - const inbound = new Map(); - for (const edge of edges) { - push(out, edge.source, edge.target); - push(inbound, edge.target, edge.source); - } - return { edges, out, in: inbound }; -} -function push(map: Map, key: number, value: number): void { - const existing = map.get(key); - if (existing) - existing.push(value); - else - map.set(key, [value]); -} -interface BfsResult { - distances: Map; - truncated: boolean; -} -/** Breadth-first walk, level by level, stopping at `maxDepth` or `limit` nodes. */ -function bfs(structure: LinkStructure, start: number, direction: Direction, maxDepth: number, limit: number): BfsResult { - const distances = new Map([[start, 0]]); - let frontier = [start]; - let depth = 0; - let truncated = false; - while (frontier.length > 0 && depth < maxDepth && !truncated) { - depth++; - const next: number[] = []; - for (const id of frontier) { - const neighbors: number[] = []; - if (direction !== "in") - neighbors.push(...(structure.out.get(id) ?? [])); - if (direction !== "out") - neighbors.push(...(structure.in.get(id) ?? [])); - for (const neighbor of neighbors) { - if (distances.has(neighbor)) - continue; - if (distances.size >= limit) { - truncated = true; - break; - } - distances.set(neighbor, depth); - next.push(neighbor); - } - if (truncated) - break; - } - frontier = next; - } - return { distances, truncated }; -} -// --- caps ------------------------------------------------------------------ -/** - * Trims a subgraph to the response caps, keeping the highest-pagerank nodes - * (a virtual root always survives — dropping the thing the view is rooted on - * would be nonsense). Edges are then filtered to the surviving node set, which - * is also how a whole-corpus edge list is narrowed to the requested subgraph. - */ -function applyCaps(nodes: Node[], edges: Edge[], maxNodes: number): Subgraph { - let truncated = false; - let keptNodes = nodes; - if (nodes.length > maxNodes) { - truncated = true; - keptNodes = [...nodes] - .sort((a, b) => Number(b.virtual ?? false) - Number(a.virtual ?? false) || (b.pagerank ?? 0) - (a.pagerank ?? 0)) - .slice(0, maxNodes); - } - const ids = new Set(keptNodes.map((n) => n.id)); - let keptEdges = edges.filter((e) => ids.has(e.source) && ids.has(e.target)); - if (keptEdges.length > MAX_EDGES) { - truncated = true; - const rank = new Map(keptNodes.map((n) => [n.id, n.pagerank ?? 0])); - keptEdges = keptEdges - .map((edge) => ({ edge, weight: Math.min(rank.get(edge.source) ?? 0, rank.get(edge.target) ?? 0) })) - .sort((a, b) => b.weight - a.weight) - .slice(0, MAX_EDGES) - .map((entry) => entry.edge); - } - return { nodes: keptNodes, edges: keptEdges, truncated }; + return id; } // --- meta ------------------------------------------------------------------ function countGraph(db: Database): { @@ -203,7 +99,7 @@ function countGraph(db: Database): { } { const edges = db.query<{ c: number; - }, []>(`SELECT COUNT(*) AS c FROM (${DISTINCT_EDGES_SQL})`).get(); + }, []>(`SELECT COUNT(*) AS c FROM (${reader(db).edgeSql})`).get(); return { nodeCount: countMarkdownDocs(db), edgeCount: edges?.c ?? 0 }; } /** @@ -222,29 +118,6 @@ function countMarkdownDocs(db: Database): number { c: number; }, []>(`SELECT COUNT(*) AS c FROM documents d WHERE ${MARKDOWN_ONLY}`).get()?.c ?? 0); } -function parseDefaultRoot(meta: Map): { - path: string; - virtual: boolean; -} | null { - const raw = meta.get("graph_root"); - if (!raw) - return null; - if (raw.startsWith("virtual:")) - return { path: raw.slice("virtual:".length), virtual: true }; - return { path: raw, virtual: false }; -} -function parseRootLinks(meta: Map): number[] { - const raw = meta.get("graph_root_links"); - if (!raw) - return []; - try { - const parsed = JSON.parse(raw); - return Array.isArray(parsed) ? parsed.filter((id): id is number => Number.isFinite(id)) : []; - } - catch { - return []; - } -} function readCommunities(db: Database): Community[] { const rows = db .query<{ @@ -299,7 +172,7 @@ export function graphMeta(db: Database, meta: Map, schemaVersion stale: isStale(db, computedAt), ...counts, communities: readCommunities(db), - defaultRoot: parseDefaultRoot(meta), + defaultRoot: parseGraphRootKey(meta.get("graph_root")), }; if (meta.get("graph_layout_skipped") === "1") response.layoutSkipped = true; @@ -326,19 +199,20 @@ export function graphClusters(db: Database, meta: Map, opts: { includeIsolates?: boolean; }): Subgraph { requireComputedGraph(meta); + const graph = reader(db); const filters: string[] = [MARKDOWN_ONLY]; const params: number[] = []; if (opts.community !== undefined) { filters.push("m.community = ?"); params.push(opts.community); } - if (!opts.includeIsolates) { + if (!graph.includeIsolates(opts.includeIsolates)) { filters.push("(COALESCE(m.in_degree, 0) + COALESCE(m.out_degree, 0)) > 0"); } const rows = db .query(`${nodeSelect(true)} WHERE ${filters.join(" AND ")} ORDER BY m.pagerank DESC, d.id ASC`) .all(...params); - return applyCaps(rows.map((row) => toNode(row)), loadLinkStructure(db).edges, MAX_NODES); + return graph.scene(rows.map((row) => toNode(row)), graph.links().edges, graph.profile.sceneNodes); } /** * Deliberately exempt from the schema gate: an ego graph needs nothing but the @@ -350,64 +224,52 @@ export function graphNeighborhood(db: Database, schemaVersion: number, opts: { depth?: number; direction?: Direction; }): Subgraph { - const depth = clamp(opts.depth ?? 1, 1, MAX_NEIGHBORHOOD_DEPTH); - const direction = opts.direction ?? "both"; - const centerId = lookupDocumentId(db, opts.center); + const graph = reader(db); + const centerId = lookupDocumentId(graph, opts.center); const withGraphTables = schemaVersion >= 8; - const structure = loadLinkStructure(db); - const { distances, truncated } = bfs(structure, centerId, direction, depth, MAX_NEIGHBORHOOD_NODES); + const { distances, truncated } = graph.neighborhood(centerId, opts.depth, opts.direction); const rows = loadNodesByIds(db, [...distances.keys()], withGraphTables); const nodes = rows.map((row) => toNode(row, distances.get(row.id))); - const capped = applyCaps(nodes, structure.edges, MAX_NEIGHBORHOOD_NODES); - return { ...capped, truncated: capped.truncated || truncated }; + return graph.scene(nodes, graph.links().edges, graph.profile.neighborhoodNodes, truncated); } export function graphDiscovery(db: Database, meta: Map, opts: { root?: string; direction?: "out" | "both"; maxDepth?: number; }): Subgraph { - const maxDepth = clamp(opts.maxDepth ?? MAX_DISCOVERY_DEPTH, 1, MAX_DISCOVERY_DEPTH); - const direction = opts.direction ?? "out"; + const graph = reader(db); + const maxDepth = graph.discoveryDepth(opts.maxDepth); requireComputedGraph(meta); - const structure = loadLinkStructure(db); + const structure = graph.links(); const total = countMarkdownDocs(db); if (opts.root) { - const rootId = lookupDocumentId(db, opts.root); - const { distances, truncated } = bfs(structure, rootId, direction, maxDepth, MAX_NODES); + const rootId = lookupDocumentId(graph, opts.root); + const { distances, truncated } = graph.discovery(rootId, maxDepth, opts.direction); const rows = loadNodesByIds(db, [...distances.keys()], true); - const capped = applyCaps(rows.map((row) => toNode(row, distances.get(row.id))), structure.edges, MAX_NODES); + const capped = graph.scene(rows.map((row) => toNode(row, distances.get(row.id))), structure.edges, graph.profile.sceneNodes, truncated); // Reach is a property of the graph, not of the scene, so it is measured // by a second walk with no depth window. A BFS can neither exceed the // node count in levels nor in nodes, so `total` bounds both exactly. - const reachable = bfs(structure, rootId, direction, total, total).distances.size; + const reachable = graph.walk(rootId, opts.direction ?? "out", total, total).distances.size; return { ...capped, - truncated: capped.truncated || truncated, reachableCount: reachable, unreachableCount: Math.max(0, total - reachable), }; } // Default root: the distances were computed at index time, so `direction` // does not apply here — the precomputed walk is the one that was run. - const distanceRows = db - .query<{ - document_id: number; - distance: number; - }, [ - number - ]>("SELECT document_id, distance FROM graph_root_distances WHERE distance <= ?") - .all(maxDepth); - const distances = new Map(distanceRows.map((row) => [row.document_id, row.distance])); + const distances = graph.rootDistances(maxDepth); const rows = loadNodesByIds(db, [...distances.keys()], true); const nodes = rows.map((row) => toNode(row, distances.get(row.id))); - const root = parseDefaultRoot(meta); + const root = parseGraphRootKey(meta.get("graph_root")); const edges = [...structure.edges]; if (root?.virtual) { // The entry file is excluded from indexing, so it has no documents row: // the node standing in for it is synthesized here, at id 0. - const rootLinks = parseRootLinks(meta).filter((id) => distances.has(id)); + const rootLinks = graph.rootLinks(meta.get("graph_root_links")).filter((id) => distances.has(id)); nodes.unshift({ - id: 0, + id: VIRTUAL_ROOT_ID, path: root.path, title: basename(root.path), type: "root", @@ -416,9 +278,9 @@ export function graphDiscovery(db: Database, meta: Map, opts: { distance: 0, virtual: true, }); - edges.unshift(...rootLinks.map((id) => ({ source: 0, target: id }))); + edges.unshift(...rootLinks.map((id) => ({ source: VIRTUAL_ROOT_ID, target: id }))); } - const response = applyCaps(nodes, edges, MAX_NODES); + const response: Subgraph = graph.scene(nodes, edges, graph.profile.sceneNodes); if (hasResolvedRoot(meta)) { // Every distance row is one reached DOCUMENT — a virtual root is none, so // this needs no adjustment for the synthesized node. Counted over the @@ -435,7 +297,9 @@ export function graphMaintenance(db: Database, meta: Map, opts: staleDays?: number; now?: string; }): Maintenance { - const staleDays = clamp(opts.staleDays ?? DEFAULT_STALE_DAYS, 1, 3650); + const graph = reader(db); + const staleDays = graph.staleDays(opts.staleDays); + const limit = graph.profile.findingLimit; requireComputedGraph(meta); const orphans = db .query, opts: ]>(`${nodeSelect(true)} WHERE ${MARKDOWN_ONLY} AND COALESCE(m.in_degree, 0) = 0 AND COALESCE(m.out_degree, 0) = 0 ORDER BY d.updated DESC, d.id ASC LIMIT ?`) - .all(MAX_NODES) + .all(limit) .map((row) => toNode(row)); // Keyed on whether a root was RESOLVED, not on whether any note has a // distance: a named root that reached nothing leaves the distances empty, @@ -458,19 +322,9 @@ export function graphMaintenance(db: Database, meta: Map, opts: LEFT JOIN graph_root_distances rd ON rd.document_id = d.id WHERE ${MARKDOWN_ONLY} AND rd.document_id IS NULL ORDER BY m.pagerank DESC, d.id ASC LIMIT ?`) - .all(MAX_NODES) + .all(limit) .map((row) => toNode(row)); - const brokenLinks = db - .query<{ - sourcePath: string; - target: string; - }, [ - number - ]>(`SELECT d.path AS sourcePath, l.target AS target - FROM links l JOIN documents d ON d.id = l.source_id - WHERE l.target_id IS NULL - ORDER BY d.path ASC, l.target ASC LIMIT ?`) - .all(MAX_NODES); + const brokenLinks = graph.brokenLinks(); // `documents.updated` is a date, `indexed_at` a timestamp — compare on the // date prefix so a mix of both formats still sorts correctly. const cutoff = new Date((opts.now === undefined ? Date.now() : Date.parse(opts.now)) - staleDays * 86400000).toISOString().slice(0, 10); @@ -483,10 +337,7 @@ export function graphMaintenance(db: Database, meta: Map, opts: ]>(`${nodeSelect(true, ", d.updated AS updated")} WHERE ${MARKDOWN_ONLY} AND substr(d.updated, 1, 10) < ? ORDER BY d.updated ASC, d.id ASC LIMIT ?`) - .all(cutoff, MAX_NODES) + .all(cutoff, limit) .map((row) => ({ ...toNode(row), updated: row.updated })); return { orphans, unreachable, brokenLinks, stale, staleDays }; } -function clamp(value: number, min: number, max: number): number { - return Math.min(max, Math.max(min, value)); -} diff --git a/packages/core/tests/briefing.test.ts b/packages/core/tests/briefing.test.ts index b4bb7f92e0..6e454d9155 100644 --- a/packages/core/tests/briefing.test.ts +++ b/packages/core/tests/briefing.test.ts @@ -5,7 +5,7 @@ */ import { afterAll, describe, expect, setSystemTime, test } from "bun:test"; -import { mkdirSync, readFileSync, writeFileSync } from "fs"; +import { mkdirSync, readFileSync, utimesSync, writeFileSync } from "fs"; import { join } from "path"; import { generateBriefing, type BriefingOptions } from "../src/cli/commands/briefing"; @@ -103,6 +103,41 @@ describe("Upkeep", () => { }); }); +describe("Silently Modified", () => { + // Briefing reads the one silent-edit query (`silentEdits`, #1353): the ten + // most recently changed files, archived and baselined ones left out. + test("lists the ten newest silent edits, newest first, without archived or accepted files", async () => { + const doc = (title: string, updated: string, status = "active") => + `---\ntype: note\ntitle: "${title}"\nstatus: ${status}\ncreated: 2026-01-01\nupdated: ${updated}\ntags: [t]\n---\n\nBody.\n`; + const day = (month: number, date: number) => `2026-${String(month).padStart(2, "0")}-${String(date).padStart(2, "0")}`; + // Twelve silent edits, written in an order that is not the answer. + const edits = [7, 2, 11, 5, 12, 1, 9, 4, 10, 3, 8, 6]; + const files: Record = Object.fromEntries(edits.map((n) => [`notes/e${n}.md`, doc(`Edit ${n}`, "2026-01-01")])); + files["notes/archived.md"] = doc("Archived", "2026-01-01", "archived"); + files["notes/accepted.md"] = doc("Accepted", "2026-01-01"); + files["notes/current.md"] = doc("Current", "2026-06-30"); + // Not makeBrain: its accept-mtime would baseline every file at today's mtime. + const root = makeTempBrain({ empty: true }); + brains.push(root); + writeFileSync(join(root, "brain.config.json"), "{}"); + const mtimes: Record = Object.fromEntries(edits.map((n) => [`notes/e${n}.md`, day(2, n)])); + mtimes["notes/archived.md"] = day(6, 1); + mtimes["notes/accepted.md"] = day(5, 1); + mtimes["notes/current.md"] = day(3, 1); + mkdirSync(join(root, "notes"), { recursive: true }); + for (const [rel, text] of Object.entries(files)) { + writeFileSync(join(root, rel), text); + const at = new Date(`${mtimes[rel]}T12:00:00Z`); + utimesSync(join(root, rel), at, at); + } + expect((await runCli(root, ["index", "--json"])).code).toBe(0); + expect((await runCli(root, ["accept-mtime", "notes/accepted.md", "--json"])).code).toBe(0); + expect(section(await brief(root), "Silently Modified")).toEqual( + [12, 11, 10, 9, 8, 7, 6, 5, 4, 3].map((n) => `- file: ${day(2, n)} | frontmatter: 2026-01-01 | notes/e${n}.md | Edit ${n}`) + ); + }); +}); + describe("Overdue Reviews", () => { const reviewed = (n: number) => `---\ntype: note\ntitle: "Review ${n}"\ncreated: 2026-01-01\nupdated: 2026-06-30\nnext_review: ${daysAgo(n)}\ntags: [t]\n---\n\nBody.\n`; diff --git a/packages/core/tests/cli-contract.test.ts b/packages/core/tests/cli-contract.test.ts index 2d5c629cc9..d5d7219644 100644 --- a/packages/core/tests/cli-contract.test.ts +++ b/packages/core/tests/cli-contract.test.ts @@ -106,6 +106,93 @@ describe("search", () => { }); }); +// #1352: flag values go through one typed accessor (cli/flags.ts). A malformed +// one is a usage error (exit 1, message on stderr, nothing on stdout) in both +// output modes, and is refused before any query runs. +describe("malformed flag values", () => { + const whole = (flag: string, got: string) => `--${flag} must be a whole number of 1 or more, got ${got}`; + const invalid: Array<[string, string[], string]> = [ + ["search --limit abc", ["search", "raft", "--limit", "abc"], whole("limit", '"abc"')], + ["search --limit 0", ["search", "raft", "--limit", "0"], whole("limit", '"0"')], + ["search --limit -5", ["search", "raft", "--limit", "-5"], whole("limit", '"-5"')], + ["search --limit 1.5", ["search", "raft", "--limit", "1.5"], whole("limit", '"1.5"')], + ["search --limit 10abc", ["search", "raft", "--limit", "10abc"], whole("limit", '"10abc"')], + ["search --mode bogus", ["search", "raft", "--mode", "bogus"], '--mode must be one of fts, vector, hybrid, got "bogus"'], + ["a bare search --type", ["search", "raft", "--type"], "--type needs a value"], + ["search --tag before another flag", ["search", "raft", "--tag", "--mode", "fts"], "--tag needs a value"], + ["list --tag before another flag", ["list", "--tag", "--status", "active"], "--tag needs a value"], + ["context --max-tokens abc", ["context", "raft", "--max-tokens", "abc"], whole("max-tokens", '"abc"')], + ["briefing --limit abc", ["briefing", "--limit", "abc"], whole("limit", '"abc"')], + // These two were usage errors before #1352 and keep their messages. + ["search --sort bogus", ["search", "raft", "--sort", "bogus"], '--sort must be one of score, updated, deadline, got "bogus"'], + [ + "a malformed search --updated-since", + ["search", "raft", "--updated-since", "yesterday"], + '--updated-since needs a date written YYYY-MM-DD, got "yesterday"', + ], + ]; + for (const mode of ["--json", "--human"]) { + for (const [what, args, message] of invalid) { + test(`${what} is a usage error in ${mode} mode, with no output`, async () => { + const { stdout, stderr, code } = await runCli(root, [...args, mode]); + expect({ code, stdout, stderr: stderr.trim() }).toEqual({ code: 1, stdout: "", stderr: message }); + }); + } + } + + // Without an index, a query fails with "Database not found". A malformed + // flag reports itself instead, so it is refused before any query is tried. + test("a malformed flag is refused before the database is opened", async () => { + const unindexed = makeTempBrain(); + try { + const valid = await runCli(unindexed, ["search", "raft", "--limit", "5", "--json"]); + expect({ code: valid.code, stderr: valid.stderr.trim() }).toEqual({ + code: 1, + stderr: "Database not found. Run `brain index` first.", + }); + for (const [what, args, message] of invalid) { + if (args[0] === "list") continue; + const bad = await runCli(unindexed, [...args, "--json"]); + expect({ what, code: bad.code, stdout: bad.stdout, stderr: bad.stderr.trim() }).toEqual({ + what, + code: 1, + stdout: "", + stderr: message, + }); + } + const add = await runCli(unindexed, ["add", "Penelope weaves by day", "--tags", "--json"]); + expect({ code: add.code, stdout: add.stdout, stderr: add.stderr.trim() }).toEqual({ + code: 1, + stdout: "", + stderr: "--tags needs a value", + }); + expect(existsSync(join(unindexed, "brain.db"))).toBe(false); + } finally { + cleanup(unindexed); + } + }); + + const paths = async (args: string[]) => { + const { stdout, stderr, code } = await runCli(root, ["search", "raft", "--mode", "fts", ...args, "--json"]); + expect({ code, stderr }).toEqual({ code: 0, stderr: "" }); + return (JSON.parse(stdout) as { results: Array<{ path: string }> }).results.map((r) => r.path); + }; + + test("a repeated --limit keeps its last value", async () => { + const seven = await paths(["--limit", "7"]); + expect(seven).toHaveLength(7); + expect(await paths(["--limit", "5", "--limit", "7"])).toEqual(seven); + }); + + test("valid values keep their results: --limit 50 and --mode fts", async () => { + const all = await paths(["--limit", "50"]); + // The corpus has fewer than 20 raft matches, so 50 and the default agree. + expect(all.length).toBeGreaterThan(7); + expect(all.length).toBeLessThan(20); + expect(await paths([])).toEqual(all); + }); +}); + describe("read", () => { test("prints the whole file with no flag", async () => { const { stdout, code } = await runCli(root, ["read", "me/identity.md"]); diff --git a/packages/core/tests/cli-no-sql.test.ts b/packages/core/tests/cli-no-sql.test.ts new file mode 100644 index 0000000000..87a4a7ad56 --- /dev/null +++ b/packages/core/tests/cli-no-sql.test.ts @@ -0,0 +1,111 @@ +/** + * CLI commands hold no SQL (#1353, epic #1341): no file under + * `src/cli/commands/` calls `.prepare(`, `.query(`, `.run(` or `.exec(` on a + * bun:sqlite database or statement. Index reads and writes live in named + * functions under `src/lib/` (or `src/queries/`), which the commands call. + * + * Detection is type-aware (the TypeScript compiler API): a call counts when the + * method it resolves to is declared by bun:sqlite, so a command's own `.run(` + * (`CoreCommand.run`) is not one, and a database reached through an alias or a + * helper's return value still is. A `.prepare(` or `.query(` whose method the + * checker cannot resolve (an `any` handle) counts too. + */ + +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative, resolve, sep } from "path"; +import ts from "typescript"; + +const ROOT = resolve(import.meta.dir, "../../.."); +const COMMANDS = resolve(import.meta.dir, "../src/cli/commands"); +const SQL_METHODS = new Set(["prepare", "query", "run", "exec"]); +const UNTYPED_SQL_METHODS = new Set(["prepare", "query"]); + +function sourceFiles(dir: string): string[] { + return readdirSync(dir, { recursive: true, encoding: "utf-8" }) + .filter((f) => /\.tsx?$/.test(f) && !f.endsWith(".d.ts")) + .map((f) => join(dir, f)) + .sort(); +} + +/** Whether `declaration` is inside bun:sqlite's `declare module "bun:sqlite"`. */ +function fromBunSqlite(declaration: ts.Declaration): boolean { + for (let node: ts.Node | undefined = declaration; node; node = node.parent) { + if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name) && node.name.text === "bun:sqlite") return true; + } + return false; +} + +/** Every `file:line: receiver.method(` call on a bun:sqlite handle in `files`. */ +export function findDatabaseCalls(files: string[]): string[] { + const config = ts.readConfigFile(join(ROOT, "tsconfig.json"), ts.sys.readFile); + const { options } = ts.parseJsonConfigFileContent(config.config, ts.sys, ROOT, undefined, join(ROOT, "tsconfig.json")); + const program = ts.createProgram(files, { ...options, noEmit: true }); + const checker = program.getTypeChecker(); + const found: string[] = []; + for (const file of files) { + const source = program.getSourceFile(file); + if (!source) throw new Error(`not in the program: ${file}`); + const visit = (node: ts.Node): void => { + if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { + const method = node.expression.name.text; + if (SQL_METHODS.has(method)) { + const declarations = checker.getSymbolAtLocation(node.expression.name)?.declarations ?? []; + const sql = declarations.length === 0 ? UNTYPED_SQL_METHODS.has(method) : declarations.some(fromBunSqlite); + if (sql) { + const { line } = source.getLineAndCharacterOfPosition(node.getStart(source)); + found.push(`${relative(ROOT, file).split(sep).join("/")}:${line + 1}: ${node.expression.getText(source).replace(/\s+/g, " ")}(`); + } + } + } + ts.forEachChild(node, visit); + }; + visit(source); + } + return found; +} + +describe("CLI commands hold no SQL", () => { + test("no file under src/cli/commands/ prepares, queries or runs a statement on a database", () => { + const files = sourceFiles(COMMANDS); + expect(files.length).toBeGreaterThan(0); + expect(findDatabaseCalls(files)).toEqual([]); + }); + + test("the detector finds database calls and leaves other .run( calls alone", () => { + const dir = mkdtempSync(join(tmpdir(), "cli-no-sql-")); + try { + const probe = join(dir, "probe.ts"); + writeFileSync( + probe, + [ + 'import { Database } from "bun:sqlite";', + 'const db = new Database(":memory:");', + 'db.prepare("SELECT 1").get();', + 'db.query("SELECT 2").all();', + 'db.run("SELECT 3");', + 'const alias = db;', + 'const statement = alias.prepare("SELECT 4");', + "statement.run();", + "const command = { run(args: string[]) { return args; } };", + 'command.run(["x"]);', + "const loose: any = db;", + 'loose.query("SELECT 5");', + "loose.run();", + "", + ].join("\n") + ); + expect(findDatabaseCalls([probe]).map((hit) => hit.slice(hit.indexOf(":") + 1))).toEqual([ + '3: db.prepare(', + '4: db.query(', + '5: db.run(', + '7: alias.prepare(', + '8: statement.run(', + '12: loose.query(', + ]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/core/tests/cli-onboarding.test.ts b/packages/core/tests/cli-onboarding.test.ts index 48f315ed4b..ce05dff43c 100644 --- a/packages/core/tests/cli-onboarding.test.ts +++ b/packages/core/tests/cli-onboarding.test.ts @@ -326,7 +326,7 @@ test("doctor reports a dead MCP source-file registration", async () => { /** * /brain-init Stage 5 registers the MCP server only when `brain doctor - * --json`'s `mcp` check (`checkMcp`, `packages/core/src/cli/commands/doctor.ts:464-503`) + * --json`'s `mcp` check (`checkMcp`, `packages/core/src/cli/commands/doctor.ts:474-513`) * does not pass. The template's `.mcp.json` already declares the server, so an * unconditional `claude mcp add` gave every new brain a second, local-scope * `brain` server beside the project one (#337). diff --git a/packages/core/tests/graph-profiles.test.ts b/packages/core/tests/graph-profiles.test.ts new file mode 100644 index 0000000000..2dea5c9861 --- /dev/null +++ b/packages/core/tests/graph-profiles.test.ts @@ -0,0 +1,582 @@ +import { afterAll, afterEach, beforeAll, describe, expect, setSystemTime, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { mkdtempSync, rmSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; + +import { openDatabase } from "../src/lib/db"; +import { + getClusterGraph, + getDiscoveryGraph, + getEgoGraph, + getGraphStats, + getMaintenanceFindings, +} from "../src/lib/graph/queries"; +import * as queries from "../src/queries/index"; +import type { QueryCode, QueryResult } from "../src/queries/index"; + +// Profile inventory (#1354). Core reads one set of graph tables for two +// surfaces: the `brain graph` CLI (lib/graph/queries.ts) and the supported +// `./queries` API, whose behaviour is the UI profile (queries/graph.ts). The +// two differ on purpose and the 2026-10-09 ruling preserves every difference. +// Each expected value below was written against, and passed on, the readers as +// they stood before they were consolidated; none is computed by either reader. + +const NOW = "2026-07-12T12:00:00Z"; +const INDEXED_AT = "2026-07-12T08:00:00Z"; +const COMPUTED_AT = "2026-07-12T09:00:00Z"; + +const temporary: string[] = []; +afterAll(() => { + for (const dir of temporary) rmSync(dir, { recursive: true, force: true }); +}); +afterEach(() => setSystemTime()); + +function dbPath(brainPath: string): string { + return join(brainPath, ".brain-index", "brain.db"); +} + +function brain(seed: (db: Database) => void): string { + const dir = mkdtempSync(join(tmpdir(), "brain-graph-profiles-")); + temporary.push(dir); + const db = openDatabase(dbPath(dir)); + try { + db.transaction(() => seed(db))(); + db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + } finally { + db.close(); + } + return dir; +} + +function edit(brainPath: string, sql: string): void { + const db = new Database(dbPath(brainPath)); + try { + db.exec(sql); + db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + } finally { + db.close(true); + } +} + +/** The CLI opens the resolved database read-only and hands it to the reader. */ +function cli(brainPath: string, read: (db: Database) => T): T { + const db = openDatabase(dbPath(brainPath), { readonly: true }); + try { + return read(db); + } finally { + db.close(); + } +} + +function ok(result: QueryResult): T { + expect(result.ok, JSON.stringify(result)).toBe(true); + if (!result.ok) throw new Error("expected a successful query"); + return result.value; +} + +function failed(result: QueryResult, code: QueryCode): void { + expect(result).toEqual({ ok: false, error: { code, retryable: false } }); +} + +const ids = (nodes: { id: number }[]): number[] => nodes.map((node) => node.id); +const sortedEdges = (edges: { source: number; target: number }[]): string[] => + edges.map((edge) => `${edge.source}>${edge.target}`).sort(); + +interface Doc { + id: number; + path: string; + title: string; + type: string; + updated: string; + asset: string | null; +} + +/** + * The voyage: Odysseus links to Ithaca (twice, once through an alias), to + * Penelope, to himself, to a chart PDF and to Thrinacia, which resolves to + * nothing. Penelope links to Telemachus, who links back to Odysseus; Troy + * links to Odysseus. Eurylochus is an isolate. The raft log is a document + * whose asset type is NULL — a node to the UI profile and not to the CLI. + * Precomputed analytics cover only the CLI's node set, as the precompute does. + */ +const VOYAGE: Doc[] = [ + { id: 1, path: "crew/odysseus.md", title: "Odysseus", type: "person", updated: "2026-07-12", asset: "markdown" }, + { id: 2, path: "places/ithaca.md", title: "Ithaca", type: "place", updated: "2026-07-10", asset: "markdown" }, + { id: 3, path: "crew/penelope.md", title: "Penelope", type: "person", updated: "2026-07-11", asset: "markdown" }, + { id: 4, path: "crew/telemachus.md", title: "Telemachus", type: "person", updated: "2026-07-01", asset: "markdown" }, + { id: 5, path: "places/troy.md", title: "Troy", type: "place", updated: "2016-07-12", asset: "markdown" }, + { id: 6, path: "crew/eurylochus.md", title: "Eurylochus", type: "person", updated: "2026-03-01", asset: "markdown" }, + { id: 7, path: "maps/aegean.pdf", title: "Aegean chart", type: "asset", updated: "2026-07-12", asset: "pdf" }, + { id: 8, path: "logs/raft-build.md", title: "Raft build", type: "log", updated: "2026-07-08", asset: null }, +]; + +const LINKS: [number, string, number | null][] = [ + [1, "places/ithaca.md", 2], + [1, "Ithaca Harbour", 2], + [1, "crew/penelope.md", 3], + [1, "crew/odysseus.md", 1], + [1, "maps/aegean.pdf", 7], + [1, "Thrinacia", null], + [3, "crew/telemachus.md", 4], + [4, "crew/odysseus.md", 1], + [5, "crew/odysseus.md", 1], + [2, "logs/raft-build.md", 8], + [8, "Scheria", null], +]; + +// document_id, in, out, pagerank, community +const METRICS: [number, number, number, number, number | null][] = [ + [1, 2, 2, 0.3, 0], + [2, 1, 0, 0.2, 0], + [3, 1, 1, 0.15, 0], + [4, 1, 1, 0.1, 0], + [5, 0, 1, 0.05, 1], + [6, 0, 0, 0.01, null], +]; + +function insertDocs(db: Database, docs: Doc[]): void { + const insert = db.query( + `INSERT INTO documents (id, path, title, type, status, created, updated, content, indexed_at, asset_type) + VALUES (?, ?, ?, ?, 'active', '2026-01-01', ?, 'Ithaca', ?, ?)` + ); + for (const doc of docs) insert.run(doc.id, doc.path, doc.title, doc.type, doc.updated, INDEXED_AT, doc.asset); +} + +function seedVoyage(db: Database): void { + insertDocs(db, VOYAGE); + const link = db.query("INSERT INTO links (source_id, target, target_id) VALUES (?, ?, ?)"); + for (const [source, target, targetId] of LINKS) link.run(source, target, targetId); + const metric = db.query( + "INSERT INTO graph_metrics (document_id, in_degree, out_degree, component, pagerank, community) VALUES (?, ?, ?, 1, ?, ?)" + ); + for (const [id, inDegree, outDegree, pagerank, community] of METRICS) metric.run(id, inDegree, outDegree, pagerank, community); + const layout = db.query("INSERT INTO graph_layouts (mode, document_id, x, y) VALUES ('clusters', ?, ?, ?)"); + for (const [id] of METRICS) layout.run(id, id * 10, -id * 10); + db.run("INSERT INTO graph_communities (community, size, label, top_terms) VALUES (0, 4, 'Ithaca', '[\"ithaca\"]'), (1, 1, 'Troy', '[]')"); + const distance = db.query("INSERT INTO graph_root_distances (document_id, distance, parent_id) VALUES (?, ?, ?)"); + distance.run(1, 1, null); + distance.run(2, 2, 1); + distance.run(3, 2, 1); + distance.run(4, 3, 3); + const meta = db.query("INSERT OR REPLACE INTO index_metadata (key, value) VALUES (?, ?)"); + meta.run("graph_computed_at", COMPUTED_AT); + meta.run("graph_root", "virtual:AGENTS.md"); + meta.run("graph_root_links", "[1]"); +} + +/** Strip the precompute: graph tables empty, no graph metadata. */ +const UNCOMPUTE = `DELETE FROM graph_metrics; DELETE FROM graph_layouts; DELETE FROM graph_communities; + DELETE FROM graph_root_distances; DELETE FROM index_metadata WHERE key LIKE 'graph_%';`; + +/** A supported pre-v8 layout: no graph tables at all. */ +const DOWNGRADE = `DROP TABLE graph_metrics; DROP TABLE graph_layouts; DROP TABLE graph_communities; + DROP TABLE graph_root_distances; DELETE FROM index_metadata WHERE key LIKE 'graph_%'; + UPDATE index_metadata SET value = '7' WHERE key = 'schema_version';`; + +let voyage: string; +beforeAll(() => { + voyage = brain(seedVoyage); +}); + +describe("node and edge scope", () => { + test("UI treats a NULL asset type as markdown and orders edges by the engine; CLI requires 'markdown' and sorts", () => { + const ui = ok(queries.readGraphClusters({ brainPath: voyage, includeIsolates: true })); + const cliGraph = cli(voyage, (db) => getClusterGraph(db)); + expect(ids(ui.nodes)).toEqual([1, 2, 3, 4, 5, 6, 8]); + expect(ids(cliGraph.nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(sortedEdges(ui.edges)).toEqual(["1>2", "1>3", "2>8", "3>4", "4>1", "5>1"]); + expect(cliGraph.edges).toEqual([ + { source: 1, target: 2 }, + { source: 1, target: 3 }, + { source: 3, target: 4 }, + { source: 4, target: 1 }, + { source: 5, target: 1 }, + ]); + }); +}); + +describe("clusters: isolate defaults, ordering and node shape", () => { + test("UI excludes isolates by metrics degree and ranks by pagerank", () => { + const ui = ok(queries.readGraphClusters({ brainPath: voyage })); + expect(ids(ui.nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ui.truncated).toBe(false); + expect(ui.nodes[0]).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 2, + outDegree: 2, + community: 0, + pagerank: 0.3, + x: 10, + y: -10, + }); + expect(sortedEdges(ui.edges)).toEqual(["1>2", "1>3", "3>4", "4>1", "5>1"]); + // NULL pagerank sorts last; a node without metrics carries no analytics. + const all = ok(queries.readGraphClusters({ brainPath: voyage, includeIsolates: true })); + expect(all.nodes.at(-1)).toEqual({ + id: 8, + path: "logs/raft-build.md", + title: "Raft build", + type: "log", + inDegree: 0, + outDegree: 0, + }); + }); + + test("CLI includes isolates by default, keeps document id order and drops isolates by adjacency", () => { + const all = cli(voyage, (db) => getClusterGraph(db)); + expect(ids(all.nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(all.truncated).toBe(false); + expect(all.nodes[5]).toEqual({ + id: 6, + path: "crew/eurylochus.md", + title: "Eurylochus", + type: "person", + inDegree: 0, + outDegree: 0, + pagerank: 0.01, + x: 60, + y: -60, + }); + const linked = cli(voyage, (db) => getClusterGraph(db, { includeIsolates: false })); + expect(ids(linked.nodes)).toEqual([1, 2, 3, 4, 5]); + const community = cli(voyage, (db) => getClusterGraph(db, { community: 1 })); + expect(ids(community.nodes)).toEqual([5]); + expect(community.edges).toEqual([]); + }); +}); + +describe("neighborhood: ordering, missing centers and path handling", () => { + test("UI loads the reached ids in row order with layout; CLI keeps BFS order without layout", () => { + const ui = ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/telemachus.md" })); + expect(ui.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 1], + [3, 1], + [4, 0], + ]); + expect(ui.nodes[0].x).toBe(10); + const cliGraph = cli(voyage, (db) => getEgoGraph(db, { center: "crew/telemachus.md" })); + expect(cliGraph.nodes.map((n) => [n.id, n.distance])).toEqual([ + [4, 0], + [1, 1], + [3, 1], + ]); + expect(cliGraph.nodes[1]).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 2, + outDegree: 2, + community: 0, + pagerank: 0.3, + distance: 1, + }); + expect(cliGraph.edges).toEqual([ + { source: 1, target: 3 }, + { source: 3, target: 4 }, + { source: 4, target: 1 }, + ]); + }); + + test("depth defaults to 1 and clamps to 3 in both; the walk follows each profile's edge scope", () => { + const uiDeep = ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/odysseus.md", depth: 9, direction: "out" })); + expect(uiDeep.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 0], + [2, 1], + [3, 1], + [4, 2], + [8, 2], + ]); + const cliDeep = cli(voyage, (db) => getEgoGraph(db, { center: "crew/odysseus.md", depth: 9, direction: "out" })); + expect(cliDeep.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 0], + [2, 1], + [3, 1], + [4, 2], + ]); + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ids(cli(voyage, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + }); + + test("a missing center is not_found for the UI and an empty subgraph for the CLI", () => { + failed(queries.readGraphNeighborhood({ brainPath: voyage, center: "crew/argos.md" }), "not_found"); + failed(queries.readGraphNeighborhood({ brainPath: voyage, center: "maps/aegean.pdf" }), "not_found"); + const empty = { nodes: [], edges: [], truncated: false }; + expect(cli(voyage, (db) => getEgoGraph(db, { center: "crew/argos.md" }))).toEqual(empty); + expect(cli(voyage, (db) => getEgoGraph(db, { center: "maps/aegean.pdf" }))).toEqual(empty); + // The NULL-asset log is a UI node and no CLI node. + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "logs/raft-build.md" })).nodes)).toEqual([2, 8]); + expect(cli(voyage, (db) => getEgoGraph(db, { center: "logs/raft-build.md" }))).toEqual(empty); + // The UI normalizes a leading "./"; the CLI matches the stored path exactly. + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: voyage, center: "./places/troy.md" })).nodes)).toEqual([1, 5]); + expect(cli(voyage, (db) => getEgoGraph(db, { center: "./places/troy.md" }))).toEqual(empty); + }); +}); + +describe("discovery: virtual root, explicit roots and counts", () => { + test("the default virtual root differs in shape, edge position and reach counts", () => { + const ui = ok(queries.readGraphDiscovery({ brainPath: voyage })); + expect(ui.nodes[0]).toEqual({ + id: 0, + path: "AGENTS.md", + title: "AGENTS.md", + type: "root", + inDegree: 0, + outDegree: 1, + distance: 0, + virtual: true, + }); + expect(ui.nodes.map((n) => [n.id, n.distance])).toEqual([ + [0, 0], + [1, 1], + [2, 2], + [3, 2], + [4, 3], + ]); + expect(ui.edges[0]).toEqual({ source: 0, target: 1 }); + expect(sortedEdges(ui.edges)).toEqual(["0>1", "1>2", "1>3", "3>4", "4>1"]); + expect(ui.reachableCount).toBe(4); + expect(ui.unreachableCount).toBe(3); + expect(ui.truncated).toBe(false); + + const cliGraph = cli(voyage, (db) => getDiscoveryGraph(db)); + expect(cliGraph.nodes[0]).toEqual({ + id: 0, + path: "AGENTS.md", + title: "AGENTS.md", + type: "index", + inDegree: 0, + outDegree: 0, + distance: 0, + virtual: true, + }); + expect(ids(cliGraph.nodes)).toEqual([0, 1, 2, 3, 4]); + expect(cliGraph.edges).toEqual([ + { source: 1, target: 2 }, + { source: 1, target: 3 }, + { source: 3, target: 4 }, + { source: 4, target: 1 }, + { source: 0, target: 1 }, + ]); + expect(cliGraph).not.toHaveProperty("reachableCount"); + expect(cliGraph).not.toHaveProperty("unreachableCount"); + + expect(ids(ok(queries.readGraphDiscovery({ brainPath: voyage, maxDepth: 2 })).nodes)).toEqual([0, 1, 2, 3]); + expect(ids(cli(voyage, (db) => getDiscoveryGraph(db, { maxDepth: 2 })).nodes)).toEqual([0, 1, 2, 3]); + }); + + test("root link ids: the UI keeps finite numbers, the CLI coerces to integers", () => { + const dir = brain(seedVoyage); + edit(dir, `UPDATE index_metadata SET value = '[1, "5", 2.5]' WHERE key = 'graph_root_links'; + INSERT INTO graph_root_distances (document_id, distance, parent_id) VALUES (5, 1, NULL);`); + const ui = ok(queries.readGraphDiscovery({ brainPath: dir })); + expect(ui.edges.filter((e) => e.source === 0)).toEqual([{ source: 0, target: 1 }]); + const cliGraph = cli(dir, (db) => getDiscoveryGraph(db)); + expect(cliGraph.edges.filter((e) => e.source === 0)).toEqual([ + { source: 0, target: 1 }, + { source: 0, target: 5 }, + ]); + }); + + test("an explicit root walks per request; only the UI reports reach", () => { + const ui = ok(queries.readGraphDiscovery({ brainPath: voyage, root: "crew/penelope.md" })); + expect(ui.nodes.map((n) => [n.id, n.distance])).toEqual([ + [1, 2], + [2, 3], + [3, 0], + [4, 1], + [8, 4], + ]); + expect(ui.reachableCount).toBe(5); + expect(ui.unreachableCount).toBe(2); + const cliGraph = cli(voyage, (db) => getDiscoveryGraph(db, { root: "crew/penelope.md" })); + expect(cliGraph.nodes.map((n) => [n.id, n.distance])).toEqual([ + [3, 0], + [4, 1], + [1, 2], + [2, 3], + ]); + expect(cliGraph).not.toHaveProperty("reachableCount"); + // Only the CLI walks inbound from a discovery root. + failed(queries.readGraphDiscovery({ brainPath: voyage, root: "crew/odysseus.md", direction: "in" as "out" }), "invalid_input"); + expect(ids(cli(voyage, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md", direction: "in", maxDepth: 1 })).nodes)).toEqual([1, 4, 5]); + }); + + test("a missing root is not_found for the UI and an empty subgraph for the CLI", () => { + failed(queries.readGraphDiscovery({ brainPath: voyage, root: "crew/argos.md" }), "not_found"); + expect(cli(voyage, (db) => getDiscoveryGraph(db, { root: "crew/argos.md" }))).toEqual({ nodes: [], edges: [], truncated: false }); + }); +}); + +describe("maintenance: findings, ordering and staleDays", () => { + test("defaults: 180 days, UI ordering and caps, CLI id order and root echo", () => { + setSystemTime(new Date(NOW)); + const ui = ok(queries.readGraphMaintenance({ brainPath: voyage })); + expect(ui.staleDays).toBe(180); + expect(ids(ui.orphans)).toEqual([8, 6]); + expect(ids(ui.unreachable)).toEqual([5, 6, 8]); + expect(ids(ui.stale)).toEqual([5]); + expect(ui.stale[0].updated).toBe("2016-07-12"); + expect(ui.brokenLinks).toEqual([ + { sourcePath: "crew/odysseus.md", target: "Thrinacia" }, + { sourcePath: "logs/raft-build.md", target: "Scheria" }, + ]); + expect(ui).not.toHaveProperty("root"); + + const cliFindings = cli(voyage, (db) => getMaintenanceFindings(db)); + expect(cliFindings.staleDays).toBe(180); + expect(cliFindings.root).toBe("virtual:AGENTS.md"); + expect(ids(cliFindings.orphans)).toEqual([6]); + expect(ids(cliFindings.unreachable)).toEqual([5, 6]); + expect(ids(cliFindings.stale)).toEqual([5]); + expect(cliFindings.brokenLinks).toEqual(ui.brokenLinks); + }); + + test("the UI clamps staleDays to 1..3650; the CLI uses the value as given", () => { + setSystemTime(new Date(NOW)); + const stale = (staleDays: number) => { + const ui = ok(queries.readGraphMaintenance({ brainPath: voyage, staleDays, now: NOW })); + const cliFindings = cli(voyage, (db) => getMaintenanceFindings(db, { staleDays })); + return { + ui: [ui.staleDays, ids(ui.stale)], + cli: [cliFindings.staleDays, ids(cliFindings.stale)], + }; + }; + expect(stale(0)).toEqual({ ui: [1, [5, 6, 4, 8, 2]], cli: [0, [2, 3, 4, 5, 6]] }); + expect(stale(-5)).toEqual({ ui: [1, [5, 6, 4, 8, 2]], cli: [-5, [1, 2, 3, 4, 5, 6]] }); + expect(stale(4000)).toEqual({ ui: [3650, [5]], cli: [4000, []] }); + expect(stale(3650)).toEqual({ ui: [3650, [5]], cli: [3650, [5]] }); + }); +}); + +describe("absent, uncomputed and older graph data", () => { + test("uncomputed: the UI refuses derived modes and keeps raw neighborhoods; the CLI degrades every mode", () => { + const dir = brain(seedVoyage); + edit(dir, UNCOMPUTE); + failed(queries.readGraphClusters({ brainPath: dir }), "not_computed"); + failed(queries.readGraphDiscovery({ brainPath: dir }), "not_computed"); + failed(queries.readGraphDiscovery({ brainPath: dir, root: "crew/odysseus.md" }), "not_computed"); + failed(queries.readGraphMaintenance({ brainPath: dir }), "not_computed"); + const hood = ok(queries.readGraphNeighborhood({ brainPath: dir, center: "crew/odysseus.md" })); + // Without metrics the UI reports zero degrees; the CLI counts adjacency. + expect(hood.nodes.find((n) => n.id === 1)).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 0, + outDegree: 0, + distance: 0, + }); + const ego = cli(dir, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })); + expect(ego.nodes[0]).toEqual({ + id: 1, + path: "crew/odysseus.md", + title: "Odysseus", + type: "person", + inDegree: 2, + outDegree: 2, + distance: 0, + }); + const clusters = cli(dir, (db) => getClusterGraph(db)); + expect(ids(clusters.nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(clusters.nodes.every((n) => n.pagerank === undefined && n.x === undefined)).toBe(true); + expect(cli(dir, (db) => getDiscoveryGraph(db))).toEqual({ nodes: [], edges: [], truncated: false }); + expect(ids(cli(dir, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md", maxDepth: 1 })).nodes)).toEqual([1, 2, 3]); + const findings = cli(dir, (db) => getMaintenanceFindings(db)); + expect(findings.root).toBeNull(); + expect(findings.unreachable).toEqual([]); + expect(ids(findings.orphans)).toEqual([6]); + expect(cli(dir, (db) => getGraphStats(db))).toMatchObject({ computedAt: null, root: null, nodes: 0, edges: 5, reachable: 0 }); + }); + + test("older layout: the UI keeps only the neighborhood; the CLI reads links without the derived tables", () => { + const dir = brain(seedVoyage); + edit(dir, DOWNGRADE); + expect(ok(queries.readGraphMeta({ brainPath: dir }))).toMatchObject({ available: false, reason: "schema", schemaVersion: 7 }); + failed(queries.readGraphClusters({ brainPath: dir }), "incompatible_index"); + failed(queries.readGraphDiscovery({ brainPath: dir }), "incompatible_index"); + failed(queries.readGraphMaintenance({ brainPath: dir }), "incompatible_index"); + expect(ids(ok(queries.readGraphNeighborhood({ brainPath: dir, center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ids(cli(dir, (db) => getClusterGraph(db)).nodes)).toEqual([1, 2, 3, 4, 5, 6]); + expect(cli(dir, (db) => getDiscoveryGraph(db))).toEqual({ nodes: [], edges: [], truncated: false }); + expect(ids(cli(dir, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })).nodes)).toEqual([1, 2, 3, 4, 5]); + expect(ids(cli(dir, (db) => getMaintenanceFindings(db)).orphans)).toEqual([6]); + expect(cli(dir, (db) => getGraphStats(db))).toMatchObject({ computedAt: null, nodes: 0, edges: 5, components: 0, communities: [] }); + }); + + test("an absent index is a typed UI failure", () => { + const dir = mkdtempSync(join(tmpdir(), "brain-graph-profiles-absent-")); + temporary.push(dir); + failed(queries.readGraphNeighborhood({ brainPath: dir, center: "crew/odysseus.md" }), "missing_index"); + }); +}); + +describe("caps and truncation on a fleet-sized ledger", () => { + // Odysseus's hub note links to 5,100 ledger entries, all last touched in + // 2015. Every UI cap is exceeded; the CLI has no cap in any mode. + const ENTRIES = 5100; + let fleet: string; + beforeAll(() => { + fleet = brain((db) => { + const entries: Doc[] = []; + for (let i = 0; i < ENTRIES; i++) { + entries.push({ id: 100 + i, path: `ledger/entry-${String(i).padStart(4, "0")}.md`, title: `Ledger ${i}`, type: "note", updated: "2015-07-12", asset: "markdown" }); + } + insertDocs(db, [VOYAGE[0], ...entries]); + const link = db.query("INSERT INTO links (source_id, target, target_id) VALUES (1, ?, ?)"); + for (const entry of entries) link.run(entry.path, entry.id); + const metric = db.query( + "INSERT INTO graph_metrics (document_id, in_degree, out_degree, component, pagerank, community) VALUES (?, ?, ?, 1, ?, 0)" + ); + metric.run(1, 0, ENTRIES, 1); + for (const entry of entries) metric.run(entry.id, 1, 0, entry.id / 1e6); + db.run("INSERT OR REPLACE INTO index_metadata (key, value) VALUES ('graph_computed_at', ?)", [COMPUTED_AT]); + }); + }); + + test("neighborhood: the UI stops at 1,500 nodes; the CLI returns every neighbour", () => { + const ui = ok(queries.readGraphNeighborhood({ brainPath: fleet, center: "crew/odysseus.md" })); + expect(ui.nodes.length).toBe(1500); + expect(ui.truncated).toBe(true); + const cliGraph = cli(fleet, (db) => getEgoGraph(db, { center: "crew/odysseus.md" })); + expect(cliGraph.nodes.length).toBe(ENTRIES + 1); + expect(cliGraph.edges.length).toBe(ENTRIES); + expect(cliGraph.truncated).toBe(false); + }); + + test("explicit-root discovery: the UI caps at 5,000 and reports full reach; the CLI walk has no budget", () => { + const ui = ok(queries.readGraphDiscovery({ brainPath: fleet, root: "crew/odysseus.md" })); + expect(ui.nodes.length).toBe(5000); + expect(ui.truncated).toBe(true); + expect(ui.reachableCount).toBe(ENTRIES + 1); + expect(ui.unreachableCount).toBe(0); + const cliGraph = cli(fleet, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md" })); + expect(cliGraph.nodes.length).toBe(ENTRIES + 1); + expect(cliGraph.truncated).toBe(false); + }); + + test("clusters keep the 5,000 highest-pagerank nodes for the UI and every node for the CLI", () => { + const ui = ok(queries.readGraphClusters({ brainPath: fleet })); + expect(ui.nodes.length).toBe(5000); + expect(ui.truncated).toBe(true); + expect(ui.nodes[0].id).toBe(1); + expect(ui.nodes[1].id).toBe(100 + ENTRIES - 1); + const cliGraph = cli(fleet, (db) => getClusterGraph(db)); + expect(cliGraph.nodes.length).toBe(ENTRIES + 1); + expect(cliGraph.truncated).toBe(false); + }); + + test("maintenance lists stop at 5,000 for the UI and are complete for the CLI", () => { + setSystemTime(new Date(NOW)); + const ui = ok(queries.readGraphMaintenance({ brainPath: fleet, now: NOW })); + expect(ui.stale.length).toBe(5000); + expect(ui.stale[0].id).toBe(100); + const cliFindings = cli(fleet, (db) => getMaintenanceFindings(db)); + expect(cliFindings.stale.length).toBe(ENTRIES); + }); +}); diff --git a/packages/core/tests/hygiene.test.ts b/packages/core/tests/hygiene.test.ts index 8bef8de11d..b318245da6 100644 --- a/packages/core/tests/hygiene.test.ts +++ b/packages/core/tests/hygiene.test.ts @@ -23,6 +23,9 @@ import { reconcile, replaceIfUnchanged, shortPath, + acceptMtimes, + silentEditCandidates, + silentEdits, type HygieneCandidate, } from "../src/lib/hygiene"; import type { LoadedModule } from "../src/lib/module-types"; @@ -62,6 +65,62 @@ const STALE_ID = "staleness-context-current-focus-c515"; const entry = (id: string, ...lines: string[]) => [`### ${id}`, ...lines].join("\n"); +describe("silent edits (#1353)", () => { + // One query serves briefing (newest first, limited) and hygiene (drifted + // more than seven days, in path order). + function index(): Database { + const database = openDatabase(":memory:"); + const insert = database.prepare( + `INSERT INTO documents (path, title, type, status, created, updated, content, indexed_at, file_mtime) + VALUES (?, ?, 'note', ?, '2026-01-01', ?, '', '2026-07-01', ?)` + ); + insert.run("b.md", "B", "active", "2026-01-01", "2026-03-01"); // 59 days of drift + insert.run("a.md", "A", "active", "2026-01-01", "2026-02-01"); // 31 days + insert.run("c.md", "C", "active", "2026-01-01", "2026-01-05"); // 4 days: briefing only + insert.run("archived.md", "Archived", "archived", "2026-01-01", "2026-05-01"); + insert.run("current.md", "Current", "active", "2026-06-01", "2026-05-01"); + insert.run("accepted.md", "Accepted", "active", "2026-01-01", "2026-04-01"); + acceptMtimes(database, "accepted.md"); + return database; + } + + test("silentEdits lists newest first and honours its limit", () => { + const database = index(); + try { + expect(silentEdits(database).map((r) => r.path)).toEqual(["b.md", "a.md", "c.md"]); + expect(silentEdits(database, { limit: 2 })).toEqual([ + { file_mtime: "2026-03-01", updated: "2026-01-01", path: "b.md", title: "B" }, + { file_mtime: "2026-02-01", updated: "2026-01-01", path: "a.md", title: "A" }, + ]); + } finally { + database.close(); + } + }); + + test("silentEditCandidates keeps edits over seven days apart, in path order", () => { + const database = index(); + try { + expect(silentEditCandidates(database)).toEqual([ + { category: "silent-edit", path: "a.md", evidence: "a.md", message: "File changed 2026-02-01, frontmatter updated 2026-01-01 (31 days apart)" }, + { category: "silent-edit", path: "b.md", evidence: "b.md", message: "File changed 2026-03-01, frontmatter updated 2026-01-01 (59 days apart)" }, + ]); + } finally { + database.close(); + } + }); + + test("acceptMtimes baselines one path or every document, and counts them", () => { + const database = index(); + try { + expect(acceptMtimes(database, "missing.md")).toBe(0); + expect(acceptMtimes(database)).toBe(6); + expect(silentEdits(database)).toEqual([]); + } finally { + database.close(); + } + }); +}); + describe("stable IDs", () => { // Each hash4 below was computed from the documented formula with // `printf '%s' '||' | sha1sum | cut -c1-4`.