Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Seven small fixes from outside reports: transcript ingest, search dates, doctor, grep, skill catalogs, Windows sync and the test runner (#9567)
Garry Tanc5a80f17f371
diff --git a/behavior-changes.d/date_only_since_utc_9533.md b/behavior-changes.d/date_only_since_utc_9533.mdnew file mode 100644index 0000000000..6c7aef19f6--- /dev/null+++ b/behavior-changes.d/date_only_since_utc_9533.md@@ -0,0 +1,4 @@+---+kind: fix+---+A date-only since now starts at UTC midnight on search, query and image query, the way a date-only until already ends at UTC midnight. A brain whose database timezone isn't UTC can gain or lose rows dated within that offset of midnight. On a UTC database nothing changes, and a since given as a timestamp or a relative duration is read as before.diff --git a/changelog.d/capy-outside-fix-wave-2.md b/changelog.d/capy-outside-fix-wave-2.mdnew file mode 100644index 0000000000..8667295870--- /dev/null+++ b/changelog.d/capy-outside-fix-wave-2.md@@ -0,0 +1,12 @@+**Seven small fixes from outside reports: Claude Code transcript ingest, date-only search windows, the unit runner's failure log, doctor's Hermes hook check, get_page grep on tables, skill-catalog rebuilds and Windows sync paths.**++### Fixed+- `gbrain transcripts ingest` skips the state files Claude Code 2.1 keeps inside each session directory, instead of failing each with `unknown format` and holding `--since last` back (#9365, reported and first fixed by @Masashi-Ono0611).+- A date-only `since` in search, query and image query starts at UTC midnight, so a one-day window covers that UTC day whatever the database's timezone (#9533, reported and first fixed by @DanCanadian).+- The unit runner's `.context/test-failures.log` keeps each failing test's own error and diff instead of the next test's (#9315, reported and first fixed by @Masashi-Ono0611).+- `gbrain doctor` recognizes a gbrain turn-rule hook added by hand to an existing Hermes `hooks:` section, so `harness_wiring` no longer warns about it (#8846, reported and first fixed by @Masashi-Ono0611).+- `get_page` grep returns the matching table row instead of the whole table (#9104, reported and first fixed by @Masashi-Ono0611).+- `gbrain setup` keeps a skill catalog's `--routing` table when it rebuilds a stale catalog (#9332, reported and first fixed by @Masashi-Ono0611).+- Sync on Windows accepts a page whose stored path uses the other path separator, instead of refusing it with `page_identity_changed` (#9118, reported and first fixed by @yuriysan).++<!-- behavior-change: date_only_since_utc_9533 -->diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 8b1665f85a..727c57fc6f 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1374,7 +1374,7 @@ COVERAGE_DIR=$PWD/.coverage bash scripts/test-shard.sh 1 36 \When `bun run test` finds any failure, the wrapper:-1. Writes failure blocks (each prefixed with `--- shard N: <test name> ---`) to `.context/test-failures.log` (workspace-local, gitignored). On systems without a writable `.context/`, falls back to `/tmp/gbrain-test-failures.log`.+1. Writes one block per failing test (source, error, Expected/Received diff, then `--- shard N: (fail) <test name>`) to the gitignored `.context/test-failures.log`, or to `/tmp/gbrain-test-failures.log` when `.context/` is not writable.2. Prints a loud stderr banner with the absolute log path, plus the last 30 lines of the failure log inlined. Banner survives `| head` / `| tail` / agent-side log truncation.3. Writes a one-line-per-shard summary to `.context/test-summary.txt` (`shard N/M: pass=X fail=Y skip=Z rc=W`).4. Exits non-zero. Empty failure log + non-zero exit = infrastructure problem (wedged shard, killed child); the banner says so.diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex 7e37f87225..df2f02d759 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/by-image.ts` — `searchByImage(engine, input, opts)`. Always runs the image branch (`embedQueryMultimodalImage` + `searchVector(embedding_image)`). Hybrid intersect: when the caller provides an optional `query`, runs a parallel text branch via `embedQueryMultimodal(query)` and merges via `rrfFusionWeighted` with `effectiveRrfK(baseRrfK, weight)` from the resolved mode's refinement weights. Widens to the unified column when `search.unified_multimodal=true` (transparently upgrades retrieval quality post-reindex).-- `src/core/search/date-bounds.ts` — shared public since/until normalization for text and image query paths; hybrid.ts preserves both existing exports. Exact timestamps keep their precision, date-only upper bounds use exclusive next midnight, and invalid calendar dates fail before embedding. Direct legacy afterDate/beforeDate comparisons remain strict by default.+- `src/core/search/date-bounds.ts` — shared public since/until normalization for text and image query paths; hybrid.ts preserves both existing exports. Exact timestamps keep their precision, a date-only public `since` starts at that day's UTC midnight, date-only upper bounds use exclusive next midnight, and invalid calendar dates fail before embedding. Direct legacy afterDate/beforeDate comparisons remain strict by default.- `src/core/search/date-labels.ts` — row-date honesty for `search` / `query`. `effectiveDateLabel(source)` maps `effective_date_source` to a document date (`date`, `published`, `filename`), an event date (`event_date`) or a fallback (`created`, `fallback`: when the page was created or imported); `dateLabelLine(rows)` is the one model-visible `[gbrain dates]` line `src/mcp/dispatch.ts` appends when rows carry dates, naming only the sources present and saying the date is never a contract's effective or validity date. Lean rows (`lean-rows.ts`) keep `effective_date_source` for it. Test: `test/search-date-labels.test.ts`.diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex c7107924b2..c67dddb6fb 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.The page-state concurrency foundation under `src/core/page-state/` and the shared progressive-batch primitive. Dated edition reads (`get_page` `as_of`) are in [Valid time](valid-time.md).-- `src/core/ops/get-page-slice.ts` — get_page `section` / `grep` / `context` (#7180), params `GET_PAGE_SLICE_PARAMS` (full surface only; the get_page description names them on starter, and dispatch accepts them there). `ops/get-page-body.ts` routes a slice here: `parseSliceRequest` makes it a window-mode request carrying `slice`, and `readPartialBody`, after authorization and the quarantine `body_omitted` check, passes its read document's `stream()` (the inline bytes, or `SegmentedDocument.stream()` one segment at a time) with the window's metadata and size. Both scan the read projection line by line, so a segmented page is never held whole (memory: the returned text, one segment, at most `context` paragraphs; a line over 1 MiB is scanned in pieces). `readSection`: the first ATX heading (`HEADING`, outside `FENCE` blocks, as the outline sees them) whose whitespace-folded text equals the request case-insensitively (a leading `##` is ignored), down to the next heading of the same or higher level or the timeline separator; returns `section {heading, level, heading_path, line_start, line_end, text}` and stops reading at the section's end; a miss is `invalid_params` naming up to 20 headings with `detail.total_headings` and an outline fix. `readGrep`: blank-line paragraphs with a line containing the literal term (case-insensitive, no regex), `context` paragraphs either side (default 1, clamped to 5), windows that overlap or touch merged; `grep {term, context, total_matches, returned_matches, omitted_matches, blocks[{line_start, line_end, match_starts, text}]}`. Caps: 50 matching paragraphs and `SLICE_MAX_CHARS` (100,000), fewer when the egress cap is smaller (`sliceCharBudget`); `truncated` says a cap was hit, and a cut section adds `omitted_chars` and a `next` window read. Line numbers are the read view's, the ones `body: 'window'` `lines` reads back. A slice with a selector, include_content, content_only, `view: markdown`, a body other than auto/window, or known_as_of is `invalid_params`. Every get_page shape (whole, content_only, partial, slice) carries `chars`, the characters of page text it holds (`projectGetPage`, `readPartialBody`). Test: `test/get-page-slices.test.ts` (both engines).+- `src/core/ops/get-page-slice.ts` — get_page `section` / `grep` / `context` (#7180), params `GET_PAGE_SLICE_PARAMS` (full surface only; the get_page description names them on starter, and dispatch accepts them there). `ops/get-page-body.ts` routes a slice here: `parseSliceRequest` makes it a window-mode request carrying `slice`, and `readPartialBody`, after authorization and the quarantine `body_omitted` check, passes its read document's `stream()` (the inline bytes, or `SegmentedDocument.stream()` one segment at a time) with the window's metadata and size. Both scan the read projection line by line, so a segmented page is never held whole (memory: the returned text, one segment, at most `context` paragraphs; a line over 1 MiB is scanned in pieces). `readSection`: the first ATX heading (`HEADING`, outside `FENCE` blocks, as the outline sees them) whose whitespace-folded text equals the request case-insensitively (a leading `##` is ignored), down to the next heading of the same or higher level or the timeline separator; returns `section {heading, level, heading_path, line_start, line_end, text}` and stops reading at the section's end; a miss is `invalid_params` naming up to 20 headings with `detail.total_headings` and an outline fix. `readGrep`: blank-line paragraphs or unfenced table rows with a line containing the literal term (case-insensitive, no regex), `context` paragraphs either side (default 1, clamped to 5), windows that overlap or touch merged; `grep {term, context, total_matches, returned_matches, omitted_matches, blocks[{line_start, line_end, match_starts, text}]}`. Caps: 50 matching paragraphs and `SLICE_MAX_CHARS` (100,000), fewer when the egress cap is smaller (`sliceCharBudget`); `truncated` says a cap was hit, and a cut section adds `omitted_chars` and a `next` window read. Line numbers are the read view's, the ones `body: 'window'` `lines` reads back. A slice with a selector, include_content, content_only, `view: markdown`, a body other than auto/window, or known_as_of is `invalid_params`. Every get_page shape (whole, content_only, partial, slice) carries `chars`, the characters of page text it holds (`projectGetPage`, `readPartialBody`). Test: `test/get-page-slices.test.ts` (both engines).- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug, and keeps every move (and any alias it drops) in `slug_rename_history` (v285), which only the folder-rule lineage test reads; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `movePageIdReferences` (#5431) moves the page-id-keyed rows of a stale rename row onto the surviving row (`links` from/to/origin, `timeline_entries` page and event, `page_versions`), dropping stale-side duplicates on the `links` composite key and the timeline dedup indexes (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: no revision is create-only (an existing page refuses `revision_required`, #5385, its own code since the omission is the caller's and not a race), a stale revision or a page another writer created where an internal writer asserted none (`expectedRevision: null`) is `revision_conflict`, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work, but a Markdown or code page at or after the safe-chunk fence with no facts or takes fence, private-key text or quarantine marker keeps its old index in search until rebuilt (`servedTextProjectionFilter`); `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.diff --git a/scripts/run-unit-parallel.sh b/scripts/run-unit-parallel.shindex 115df8a1a4..cadf35c866 100755--- a/scripts/run-unit-parallel.sh+++ b/scripts/run-unit-parallel.sh@@ -376,6 +376,24 @@ strip_ansi() {sed "s/${esc}\[[0-9;]*[a-zA-Z]//g" "$1"}+# extract_failure_blocks PREFIX: reads ANSI-stripped Bun output on stdin and+# prints one block per failing test. Bun prints a failure's source context,+# error and Expected/Received diff ABOVE its `(fail)` / `✗ ` line, so a block+# is every line since the previous pass/skip/fail marker, then the marker+# line prefixed with PREFIX, then a blank line (#9315).+extract_failure_blocks() {+ awk -v prefix="$1" '+ /^(\(fail\) |✗ )/ {+ for (j = 1; j <= n; j++) print buf[j]+ print prefix $0+ print ""+ n = 0; next+ }+ /^(\(pass\)|\(skip\)|✓ |✓$)/ || /__bun_test_summary__/ { n = 0; next }+ { buf[++n] = $0 }+ '+}+# bun_summary_count: parses Bun's summary lines (one per `bun test` invocation# inside a shard). Grouped unit shards emit an authoritative aggregate so child# Bun invocations inside tests cannot inflate the reported totals.@@ -784,16 +802,7 @@ for i in $(seq 1 "$N"); doif [ "$rc" != "0" ]; thenTOTAL_RC=1if [ "$fail_count" -gt 0 ] && [ -f "$SHARD_LOG" ]; then- # Extract each failure block: from the `✗ ` / `(fail) ` line through the- # next pass/skip marker, blank line, or `__bun_test_summary__`. Single awk- # pass over ANSI-stripped text.- strip_ansi "$SHARD_LOG" | awk -v shard="$i" '- /^(\(fail\) |✗ )/ { in_block=1; print "--- shard " shard ": " $0; next }- in_block {- if (/^(\(pass\)|\(skip\)|✓ |✓$)/ || /^[[:space:]]*$/ || /__bun_test_summary__/) { in_block=0; print ""; next }- print $0- }- ' >> "$FAILURES_LOG"+ strip_ansi "$SHARD_LOG" | extract_failure_blocks "--- shard $i: " >> "$FAILURES_LOG"elif [ -f "$SHARD_LOG" ]; then# Non-zero rc but no (fail) line found — extraction couldn't pinpoint.# Dump the full shard log so we never silently lose the failure cause.@@ -848,13 +857,7 @@ if [ "$SERIAL_FILES_COUNT" -gt 0 ]; thens_fail=$(bun_summary_count "fail" "$LOG_DIR/serial.log")TOTAL_FAILURES=$((TOTAL_FAILURES + s_fail))if [ "$s_fail" -gt 0 ]; then- strip_ansi "$LOG_DIR/serial.log" | awk '- /^(\(fail\) |✗ )/ { in_block=1; print "--- shard serial: " $0; next }- in_block {- if (/^(\(pass\)|\(skip\)|✓ |✓$)/ || /^[[:space:]]*$/ || /__bun_test_summary__/) { in_block=0; print ""; next }- print $0- }- ' >> "$FAILURES_LOG"+ strip_ansi "$LOG_DIR/serial.log" | extract_failure_blocks "--- shard serial: " >> "$FAILURES_LOG"else{echo "--- shard serial: rc=$SERIAL_RC, no (fail) markers — full log follows ---"@@ -955,13 +958,7 @@ if [ "$TOTAL_RC" != "0" ] && [ "${RESCUE_COUNT:-0}" -gt 0 ]; thenelse# Real failures confirmed serially (or a non-OOM failure exists anyway).OOM_RESCUE_NOTE=" | oom_rescue_failed=${r_fail}real"- strip_ansi "$RESCUE_LOG" | awk '- /^(\(fail\) |✗ )/ { in_block=1; print "--- oom-rescue (serial, confirmed real): " $0; next }- in_block {- if (/^(\(pass\)|\(skip\)|✓ |✓$)/ || /^[[:space:]]*$/ || /__bun_test_summary__/) { in_block=0; print ""; next }- print $0- }- ' >> "$FAILURES_LOG"+ strip_ansi "$RESCUE_LOG" | extract_failure_blocks "--- oom-rescue (serial, confirmed real): " >> "$FAILURES_LOG"echo "oom-rescue: $RESCUE_COUNT files pass=$r_pass fail=$r_fail rc=$RESCUE_RC (real failures confirmed)" >> "$SUMMARY_FILE"fifidiff --git a/src/core/ops/get-page-slice.ts b/src/core/ops/get-page-slice.tsindex 279a2073ee..60d6a0ea7e 100644--- a/src/core/ops/get-page-slice.ts+++ b/src/core/ops/get-page-slice.ts@@ -277,13 +277,25 @@ export async function readGrep(stream: AsyncIterable<Buffer>, term: string, cont}};let para: Paragraph | null = null;+ let paraIsRow = false;+ let inFence = false;for await (const l of documentLines(stream)) {+ if (!l.continued && /^\s*(```|~~~)/.test(l.text)) inFence = !inFence;if (!l.continued && !l.text.trim()) {if (para) close(para);para = null;continue;}- if (!para) para = { line_start: l.line, line_end: l.line, text: '', match: false };+ // A table has no blank lines, so each row is its own record instead of one paragraph (#9104).+ const row = !l.continued && !inFence && l.text.trimStart().startsWith('|');+ if (para && !l.continued && (row || paraIsRow)) {+ close(para);+ para = null;+ }+ if (!para) {+ para = { line_start: l.line, line_end: l.line, text: '', match: false };+ paraIsRow = row;+ }const sep = para.text && !l.continued ? '\n' : '';if (para.text.length <= budget) para.text += sep + head(l.text, budget + 1 - para.text.length);para.line_end = l.line;diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 83ebbfab18..90f6786a28 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -304,10 +304,15 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wrireturn mutation;}+/** Two source paths name the same file; on Windows either separator spelling matches (#9118). */+export function sameSourcePath(a: string, b: string, separator: string = sep): boolean {+ return separator === '\\' ? a.replaceAll('\\', '/') === b.replaceAll('\\', '/') : a === b;+}+/** The admitted page is still the import's base: its revision, its id and the file it maps to. */function assertImportBaseSnapshot(row: WriteRequest, p: ManagedImportIntent, snapshot: PageSnapshot | null): void {assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)- if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {+ if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && !sameSourcePath(snapshot.page.source_path, p.sourcePath)) {throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',`Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so import request ${row.request_id} published nothing. Read the page before importing the file again.`,{ fix: readFix(`Shows which page holds ${row.slug} in source ${row.source_id} now, with its source path and revision.`,diff --git a/src/core/search/date-bounds.ts b/src/core/search/date-bounds.tsindex 55b1cb784d..68dace4ea2 100644--- a/src/core/search/date-bounds.ts+++ b/src/core/search/date-bounds.ts@@ -30,7 +30,14 @@ export function resolveDateBoundary(raw: string | undefined, boundary: 'since' |}export function resolveSearchDateBounds(opts?: SearchOpts): Pick<SearchOpts, 'afterDate' | 'beforeDate' | 'afterDateInclusive' | 'beforeDateInclusive'> {- const afterDate = resolveDateBoundary(opts?.since ?? opts?.afterDate, 'since');+ let afterDate = resolveDateBoundary(opts?.since ?? opts?.afterDate, 'since');+ const sinceDay = opts?.since?.trim();+ if (sinceDay && /^\d{4}-\d{2}-\d{2}$/.test(sinceDay)) {+ // Match the UTC calendar-day upper bound. A bare date is cast in the+ // database session's timezone, excluding early events or adding prior-day+ // events on non-UTC hosts. Direct legacy afterDate keeps its old behavior.+ afterDate = `${sinceDay}T00:00:00.000Z`;+ }let beforeDate = resolveDateBoundary(opts?.until ?? opts?.beforeDate, 'until');let beforeDateInclusive = opts?.until !== undefined ? true : opts?.beforeDateInclusive;const untilDay = opts?.until?.trim();diff --git a/src/core/setup/hermes-turn-hook.ts b/src/core/setup/hermes-turn-hook.tsindex b59f4705a8..b8c0656314 100644--- a/src/core/setup/hermes-turn-hook.ts+++ b/src/core/setup/hermes-turn-hook.ts@@ -35,6 +35,17 @@ const MARKERS: BlockMarkers = { begin: '# gbrain:turn-rule:begin', end: '# gbraiconst EVENT = 'pre_llm_call';const ALLOWLIST = 'shell-hooks-allowlist.json';+/** Exactly the echo hermesTurnHookCommand writes, for any access: one {context} key holding gbrain's rule text (#8846). */+function isTurnRuleEcho(command: string): boolean {+ const m = /^\/bin\/echo '([^']*)'$/.exec(command);+ if (!m) return false;+ let context: unknown;+ try { context = (JSON.parse(m[1]!) as { context?: unknown }).context; } catch { return false; }+ return typeof context === 'string' && context.startsWith('GBrain: before answering this turn, check GBrain first (')+ && context.includes(') for the people, companies, projects, meetings and decisions it touches.')+ && command === `/bin/echo '${JSON.stringify({ context }).replace(/'/g, '\\u0027')}'`;+}+export interface HermesTurnHookOutcome { action: 'write' | 'keep' | 'print' | 'remove' | 'skip'; path: string; detail: string; snippet?: string }/** `/bin/echo '<json>'`: Hermes splits the command without a shell (and checks the first path, /bin/echo, exists), and a quote in the rule is a JSON escape. */@@ -230,9 +241,11 @@ export function inspectHermesTurnHook(hermesHome: string, access?: BrainFirstAccconst text = existsSync(path) ? readFileSync(path, 'utf8') : '';const probe = probeBlock(MARKERS, text);const printed = access && probe.state === 'absent' ? hermesTurnHookCommand(access) : null;- const pasted = printed ? (loadBoundedYaml(text) as { hooks?: Record<string, unknown> } | null)?.hooks?.[EVENT] : undefined;+ const pasted = probe.state === 'absent' ? (loadBoundedYaml(text) as { hooks?: Record<string, unknown> } | null)?.hooks?.[EVENT] : undefined;+ // With no recorded access, a hand-added entry counts when it is exactly gbrain's rule echo.+ const ours = (c: unknown): c is string => typeof c === 'string' && (printed ? c === printed : isTurnRuleEcho(c));const command = probe.state === 'present' ? commandIn(probe.interior)- : Array.isArray(pasted) && pasted.some((e) => (e as { command?: unknown } | null)?.command === printed) ? printed : null;+ : Array.isArray(pasted) ? pasted.map((e) => (e as { command?: unknown } | null)?.command).find(ours) ?? null : null;if (!command) return { state: 'absent', path };return { state: readAllowlist(join(hermesHome, ALLOWLIST)).approvals.some((e) => approves(e, command)) ? 'approved' : 'unapproved', path, command };} catch {diff --git a/src/core/setup/skill-resolver-setup.ts b/src/core/setup/skill-resolver-setup.tsindex 8f000fef71..66fc21cd3e 100644--- a/src/core/setup/skill-resolver-setup.ts+++ b/src/core/setup/skill-resolver-setup.ts@@ -27,7 +27,7 @@import { existsSync, rmSync } from 'node:fs';import { dirname, join } from 'node:path';import { claudeUserSkillsDir, codexConfigPath } from '../bootstrap/host-specs.ts';-import { buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex } from '../skills/resolver/build.ts';+import { buildSkillIndex, catalogStatus, listCatalogs, removeSkillIndex, routingFromArgv } from '../skills/resolver/build.ts';import { configuredSkillDirs } from '../skills/resolver/config.ts';import { ResolverError } from '../skills/resolver/errors.ts';import { CLAUDE_PLUGINS_CATALOG, logsDir, sessionsDir, skillIndexRoot } from '../skills/resolver/paths.ts';@@ -72,7 +72,7 @@ async function syncPluginCatalog(home: string, dryRun: boolean): Promise<{ skillconst n = readDirSources(roots).skills.length;return n ? { skills: n, step: { step: 'catalog', action: 'write', detail: `${n} plugin skills from ${base} into ${where}` } } : drop();}- const n = (await buildSkillIndex({ catalog: CLAUDE_PLUGINS_CATALOG, claudePlugins: base, harness: 'claude-code' }, { home })).catalog.skill_count;+ const n = (await buildSkillIndex({ catalog: CLAUDE_PLUGINS_CATALOG, claudePlugins: base, harness: 'claude-code', ...routingFromArgv(status?.receipt?.rebuild_argv) }, { home })).catalog.skill_count;if (n < 1) { await removeSkillIndex(CLAUDE_PLUGINS_CATALOG, { home }); return { skills: 0, step: built ? { step: 'catalog', action: 'remove', detail: where } : null }; }return { skills: n, step: { step: 'catalog', action: 'write', detail: `${n} plugin skills from ${base} into ${where}` } };}@@ -114,7 +114,7 @@ export async function syncSkillResolverSetup(opts: { harness: ResolverHarness; gif (skills > 0) out.steps.push({ step: 'catalog', action: fresh ? 'keep' : 'write', detail: `${skills} skills from ${dirs.join(', ')} into ${where}` });} else if (dirs.length && !fresh) {try {- skills = (await buildSkillIndex({ catalog, dirs, harness }, { home })).catalog.skill_count;+ skills = (await buildSkillIndex({ catalog, dirs, harness, ...routingFromArgv(status?.receipt?.rebuild_argv) }, { home })).catalog.skill_count;} catch (e) {return { ...out, error: incomplete(dirs, `the catalog build failed (${e instanceof ResolverError ? e.code : (e as Error).message})`, 'Nothing else was written.') };}diff --git a/src/core/skills/resolver/build.ts b/src/core/skills/resolver/build.tsindex d971bd9906..2a681765d4 100644--- a/src/core/skills/resolver/build.ts+++ b/src/core/skills/resolver/build.ts@@ -107,6 +107,13 @@ export function chooseVariant(skills: readonly SkillRecord[], previous: Variantreturn { variant: share >= T_SHARE_ON || (previous === 'T' && share >= T_SHARE_KEEP) ? 'T' : 'D', share: Math.round(share * 1e4) / 1e4 };}+/** The --routing table a receipt's rebuild argv names, so a rebuild keeps it (#9332). */+export function routingFromArgv(argv: readonly string[] | null | undefined): { routing?: string } {+ const at = argv?.indexOf('--routing') ?? -1;+ const routing = at >= 0 ? argv![at + 1] : undefined;+ return routing ? { routing } : {};+}+/** The argv that rebuilds a catalog from what the receipt recorded (null for a stdin source: the adapter owns it). */export function buildArgs(input: BuildInput): { args: string[]; fix: string[] | null } {const args = ['gbrain', 'skills', 'index', 'build', '--catalog', input.catalog];diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.tsindex d5f03f9588..18262e31a9 100644--- a/src/core/transcripts/claude-code.ts+++ b/src/core/transcripts/claude-code.ts@@ -91,10 +91,22 @@ const CCR_BRIDGE_POINTER = 'bridge-pointer.json';/** True for Claude Code Remote Control state files (never transcripts). */export function isClaudeCodeRemoteControlStateFile(path: string): boolean {- const base = path.split(/[/\\]/).pop() ?? '';- return base.endsWith(CCR_TIP_SUFFIX) || base === CCR_BRIDGE_POINTER;+ const segs = path.split(/[/\\]/);+ const base = segs[segs.length - 1] ?? '';+ if (base.endsWith(CCR_TIP_SUFFIX) || base === CCR_BRIDGE_POINTER) return true;+ // Per-session layout (Claude Code 2.1.x): side files live INSIDE the+ // `<session-uuid>/` directory.+ const isSession = (s: string | undefined) => !!s && SESSION_DIR_RE.test(s);+ const parent = segs[segs.length - 2];+ if ((base === 'ccr-tip.json' || base === 'custom-title.json') && isSession(parent)) return true;+ if (/^agent-[^/\\]+\.meta\.json$/.test(base) && parent === 'subagents' && isSession(segs[segs.length - 3])) {+ return true;+ }+ return /^wf_[^/\\]+\.json$/.test(base) && parent === 'workflows' && isSession(segs[segs.length - 3]);}+const SESSION_DIR_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+/** True for Claude Code's per-project session index (`sessions-index.json`), which lists sessions and holds no turns. */export function isClaudeCodeSessionsIndexFile(path: string): boolean {return (path.split(/[/\\]/).pop() ?? '') === 'sessions-index.json';diff --git a/test/get-page-grep-table-row-9104.test.ts b/test/get-page-grep-table-row-9104.test.tsnew file mode 100644index 0000000000..be5fd229bc--- /dev/null+++ b/test/get-page-grep-table-row-9104.test.ts@@ -0,0 +1,30 @@+/**+ * #9104: a Markdown table has no blank lines, so readGrep read a whole table+ * as one paragraph and a match in one row returned every row. Each row is+ * now its own record; prose paragraphs are unchanged.+ */+import { expect, test } from 'bun:test';+import { readGrep } from '../src/core/ops/get-page-slice.ts';++async function* stream(s: string): AsyncGenerator<Buffer> { yield Buffer.from(s); }++const rows = Array.from({ length: 40 }, (_, i) => `| ${i + 1} | fact number ${i + 1} |`);+const doc = ['# Page', '', '| # | fact |', '|---|---|', ...rows, 'trailing prose line', '', 'tail'].join('\n') + '\n';++test('grep at context 0 on one table row returns only that row', async () => {+ const out = await readGrep(stream(doc), 'fact number 7 ', 0, 100_000, (t) => t) as { grep: { blocks: Array<{ line_start: number; line_end: number; text: string }> } };+ expect(out.grep.blocks).toEqual([expect.objectContaining({ line_start: 11, line_end: 11, text: '| 7 | fact number 7 |' })]);+});++test('pipe lines inside a code fence stay one paragraph', async () => {+ const code = ['# Page', '', '```', '| a', '| needle here', '| c', '```', ''].join('\n');+ const out = await readGrep(stream(code), 'needle', 0, 100_000, (t) => t) as { grep: { blocks: Array<{ line_start: number; line_end: number }> } };+ expect(out.grep.blocks).toEqual([expect.objectContaining({ line_start: 3, line_end: 7 })]);+});++test('context counts neighbouring rows, and prose after a table stays its own paragraph', async () => {+ const near = await readGrep(stream(doc), 'fact number 7 ', 1, 100_000, (t) => t) as { grep: { blocks: Array<{ line_start: number; line_end: number }> } };+ expect(near.grep.blocks).toEqual([expect.objectContaining({ line_start: 10, line_end: 12 })]);+ const prose = await readGrep(stream(doc), 'trailing prose', 0, 100_000, (t) => t) as { grep: { blocks: Array<{ line_start: number; line_end: number; text: string }> } };+ expect(prose.grep.blocks).toEqual([expect.objectContaining({ line_start: 45, line_end: 45, text: 'trailing prose line' })]);+});diff --git a/test/hermes-hand-added-turn-hook.test.ts b/test/hermes-hand-added-turn-hook.test.tsnew file mode 100644index 0000000000..c64c39011f--- /dev/null+++ b/test/hermes-hand-added-turn-hook.test.ts@@ -0,0 +1,41 @@+/**+ * #8846: a gbrain turn-rule hook added by hand to a Hermes config that already+ * has a hooks: section is seen by doctor, so harness_wiring can leave warn.+ * Only the exact echo shape gbrain writes counts; other entries do not.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { hermesTurnHookCommand, inspectHermesTurnHook } from '../src/core/setup/hermes-turn-hook.ts';++const dirs: string[] = [];+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });++function hermesHome(commands: string[], approved: string[]): string {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-hermes-hand-'));+ dirs.push(home);+ writeFileSync(join(home, 'config.yaml'), `hooks:\n pre_llm_call:\n${commands.map((c) => ` - command: ${JSON.stringify(c)}\n timeout: 10\n`).join('')}`);+ writeFileSync(join(home, 'shell-hooks-allowlist.json'), JSON.stringify({ approvals: approved.map((command) => ({ event: 'pre_llm_call', command })) }));+ return home;+}++describe('inspectHermesTurnHook with no recorded access', () => {+ const rule = hermesTurnHookCommand({ kind: 'cli', launcher: 'gbrain' } as never);++ test('a hand-added turn-rule entry beside another hook is found and approved', () => {+ const r = inspectHermesTurnHook(hermesHome(['/usr/local/bin/own-writeback', rule], [rule]));+ expect(r).toMatchObject({ state: 'approved', command: rule });+ });++ test('an unapproved hand-added entry reads as unapproved, not absent', () => {+ expect(inspectHermesTurnHook(hermesHome([rule], [])).state).toBe('unapproved');+ });++ test('an echo that only starts like the rule is not gbrain\'s', () => {+ const lookalike = `/bin/echo '{"context":"GBrain: before answering this turn","x":1}'`;+ const other = `/bin/echo 'GBrain: before answering this turn' && curl example.invalid`;+ const prefixOnly = `/bin/echo '${JSON.stringify({ context: 'GBrain: before answering this turn' })}'`;+ expect(inspectHermesTurnHook(hermesHome([lookalike, other, prefixOnly], [lookalike, other, prefixOnly])).state).toBe('absent');+ });+});diff --git a/test/import-same-source-path-9118.test.ts b/test/import-same-source-path-9118.test.tsnew file mode 100644index 0000000000..be1bca2617--- /dev/null+++ b/test/import-same-source-path-9118.test.ts@@ -0,0 +1,19 @@+/**+ * #9118: on Windows a page's stored source path and an import's path can spell+ * the same file with different separators; the import's identity check must+ * accept either spelling there, and must keep them distinct on POSIX, where a+ * backslash is an ordinary file-name character.+ */+import { expect, test } from 'bun:test';+import { sameSourcePath } from '../src/core/persistence/import-prepare.ts';++test('with the Windows separator, either spelling names the same file', () => {+ expect(sameSourcePath('notes/example.md', 'notes\\example.md', '\\')).toBe(true);+ expect(sameSourcePath('notes\\example.md', 'notes/example.md', '\\')).toBe(true);+ expect(sameSourcePath('notes/example.md', 'notes/other.md', '\\')).toBe(false);+});++test('with the POSIX separator, only the identical path matches', () => {+ expect(sameSourcePath('notes/example.md', 'notes/example.md', '/')).toBe(true);+ expect(sameSourcePath('notes/example.md', 'notes\\example.md', '/')).toBe(false);+});diff --git a/test/query-image-date-readiness.serial.test.ts b/test/query-image-date-readiness.serial.test.tsindex 5ce5000429..d0ced9ff2e 100644--- a/test/query-image-date-readiness.serial.test.ts+++ b/test/query-image-date-readiness.serial.test.ts@@ -41,7 +41,7 @@ describe('image query retains date and readiness contracts outside hybrid searchexpect(decodeDeepResearchId((results as Array<{ id: string }>)[0].id)).toEqual({ sourceId: 'default', slug: 'images/synthetic' });}- expect(options).toMatchObject({ afterDate: '2030-06-15', afterDateInclusive: true,+ expect(options).toMatchObject({ afterDate: '2030-06-15T00:00:00.000Z', afterDateInclusive: true,beforeDate: '2030-06-16T00:00:00.000Z', beforeDateInclusive: false,sourceId: 'default', excludePrivate: true, requireSafeChunks: true });expect(meta.degraded).toContainEqual({ stage: 'vector_candidates_incomplete', reason: 'timeout' });diff --git a/test/scripts/run-unit-parallel-failure-blocks.test.ts b/test/scripts/run-unit-parallel-failure-blocks.test.tsnew file mode 100644index 0000000000..8dc70376b2--- /dev/null+++ b/test/scripts/run-unit-parallel-failure-blocks.test.ts@@ -0,0 +1,56 @@+/**+ * #9315: each block in .context/test-failures.log holds its own failing+ * test's context, error and Expected/Received diff. Bun prints those lines+ * above the test's `(fail)` line, so a block that starts at the marker held+ * the next test's context and the last failure's block was empty.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { spawnSync } from 'child_process';+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';++const REPO_ROOT = resolve(import.meta.dir, '..', '..');+let root = '';+let log = '';++beforeAll(() => {+ root = mkdtempSync(join(tmpdir(), 'gbrain-failure-blocks-'));+ mkdirSync(join(root, 'scripts', 'lib'), { recursive: true });+ mkdirSync(join(root, 'test'), { recursive: true });+ for (const f of ['lib/test-env.sh', 'run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh', 'sharding.ts']) {+ copyFileSync(join(REPO_ROOT, 'scripts', f), join(root, 'scripts', f));+ }+ for (const f of ['run-unit-parallel.sh', 'run-unit-shard.sh', 'run-serial-tests.sh']) chmodSync(join(root, 'scripts', f), 0o755);+ writeFileSync(join(root, 'test', 'order.test.ts'), [+ "import { test, expect } from 'bun:test';",+ "test('first fails', () => { expect('AAA-actual').toBe('AAA-expected'); });",+ "test('second passes', () => { expect(1).toBe(1); });",+ "test('third fails', () => { expect('CCC-actual').toBe('CCC-expected'); });",+ '',+ ].join('\n'));+ spawnSync('bash', [join(root, 'scripts', 'run-unit-parallel.sh'), '--shards', '1'], {+ cwd: root,+ stdio: 'ignore',+ env: { ...process.env, GBRAIN_TEST_NO_MEM_ADAPT: '1', GBRAIN_TEST_NO_OOM_FALLBACK: '1' },+ });+ const path = join(root, '.context', 'test-failures.log');+ log = existsSync(path) ? readFileSync(path, 'utf-8') : '';+}, 120_000);++afterAll(() => {+ if (root) rmSync(root, { recursive: true, force: true });+});++test('each failure block carries its own diff, ending at its own (fail) line', () => {+ const first = log.indexOf('--- shard 1: (fail) first fails');+ const third = log.indexOf('--- shard 1: (fail) third fails');+ expect(first).toBeGreaterThan(-1);+ expect(third).toBeGreaterThan(first);+ const firstBlock = log.slice(0, first);+ const thirdBlock = log.slice(first, third);+ expect(firstBlock).toContain('Expected: "AAA-expected"');+ expect(firstBlock).not.toContain('Expected: "CCC-expected"');+ expect(thirdBlock).toContain('Expected: "CCC-expected"');+ expect(thirdBlock).not.toContain('Expected: "AAA-expected"');+});diff --git a/test/search-date-bounds-timezone.test.ts b/test/search-date-bounds-timezone.test.tsnew file mode 100644index 0000000000..7a9f05f8c6--- /dev/null+++ b/test/search-date-bounds-timezone.test.ts@@ -0,0 +1,59 @@+/**+ * Observable contract: query since=until includes the whole UTC calendar day+ * independently of the database session TimeZone, including UTC midnight.+ * Regression: a bare date lower bound is cast as local midnight, losing early+ * events west of UTC and admitting previous-day events east of UTC.+ * Existing resolver tests compare strings; the normal Bun test runtime is UTC,+ * so they do not exercise the real SQL cast in a non-UTC session.+ * No production seam: real in-memory PGLite and public operation handlers.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';++describe('date-only query bounds are independent of database timezone', () => {+ let engine: PGLiteEngine;+ let ctx: OperationContext;+ const query = operations.find(op => op.name === 'query')!;+ const put = operations.find(op => op.name === 'put_page')!;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ ctx = {+ engine, config: { engine: 'pglite', database_path: ':memory:' },+ logger: { info() {}, warn() {}, error() {}, debug() {} } as never,+ dryRun: false, remote: false, sourceId: 'default',+ };+ for (const [name, date] of [+ ['before', '2024-06-14T23:59:59Z'],+ ['midnight', '2024-06-15T00:00:00Z'],+ ['early', '2024-06-15T00:10:00Z'],+ ['late', '2024-06-15T23:59:59.999Z'],+ ['after', '2024-06-16T00:00:00Z'],+ ]) {+ await put.handler(ctx, {+ slug: `notes/date-window-${name}`,+ content: `---\ntype: note\ntitle: Date window ${name}\nevent_date: ${date}\n---\ndatewindowfixture ${name}\n`,+ });+ }+ }, 60_000);++ afterAll(async () => { await engine.disconnect(); }, 30_000);++ test.each(['America/Toronto', 'UTC', 'Asia/Tokyo'])(+ 'returns exactly the calendar-day pages in %s',+ async zone => {+ await engine.executeRaw("SELECT set_config('TimeZone', $1, false)", [zone]);+ const rows = await query.handler(ctx, {+ query: 'datewindowfixture', since: '2024-06-15', until: '2024-06-15',+ expand: false, autocut: false, adaptive_return: false, use_cache: false,+ limit: 100, mode: 'conservative', relational: false,+ }) as Array<{ slug: string }>;+ expect([...new Set(rows.map(row => row.slug))].sort()).toEqual([+ 'notes/date-window-early', 'notes/date-window-late', 'notes/date-window-midnight',+ ]);+ }, 30_000,+ );+});diff --git a/test/search-date-bounds.test.ts b/test/search-date-bounds.test.tsindex 06e94d33c0..07e9e8ac11 100644--- a/test/search-date-bounds.test.ts+++ b/test/search-date-bounds.test.ts@@ -26,14 +26,23 @@ describe('public search date bounds preserve their comparison contract', () => {test('legacy after/before remain strict and public fields win', () => {const legacy = resolveSearchDateBounds({ afterDate: '2030-06-01', beforeDate: '2030-06-15' });+ expect(legacy.afterDate).toBe('2030-06-01');expect(legacy.afterDateInclusive).not.toBe(true);expect(legacy.beforeDateInclusive).not.toBe(true);expect(legacy.beforeDate).toBe('2030-06-15T23:59:59.999Z');expect(resolveSearchDateBounds({ afterDate: '2030-01-01', since: '2030-06-15' })).toMatchObject({- afterDate: '2030-06-15', afterDateInclusive: true,+ afterDate: '2030-06-15T00:00:00.000Z', afterDateInclusive: true,});});+ test.each(['2030-06-15', ' 2032-02-29 ', '2030-12-31'])(+ 'date-only since %s starts at UTC midnight', since => {+ expect(resolveSearchDateBounds({ since })).toMatchObject({+ afterDate: `${since.trim()}T00:00:00.000Z`, afterDateInclusive: true,+ });+ },+ );+test('invalid calendar dates are rejected instead of shifting into the next month', () => {expect(() => resolveSearchDateBounds({ until: '2030-02-30' })).toThrow('Invalid until');expect(() => resolveSearchDateBounds({ since: '2030-02-29' })).toThrow('Invalid since');diff --git a/test/setup-skill-resolver-routing-9332.test.ts b/test/setup-skill-resolver-routing-9332.test.tsnew file mode 100644index 0000000000..e7cce90582--- /dev/null+++ b/test/setup-skill-resolver-routing-9332.test.ts@@ -0,0 +1,43 @@+/**+ * #9332: when setup rebuilds a stale skill-resolver catalog, the rebuild keeps+ * the --routing table the catalog was built with, so routing rows still match.+ */+import { afterAll, expect, setDefaultTimeout, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { runCli } from './helpers/cli-spawn.ts';++setDefaultTimeout(120_000);+const CLI = join(import.meta.dir, '..', 'src', 'cli.ts');+const root = mkdtempSync(join(tmpdir(), 'gbrain-routing-9332-'));+afterAll(() => rmSync(root, { recursive: true, force: true }));++test('a setup rebuild of a stale catalog keeps its routing table', async () => {+ const home = join(root, 'home');+ const project = join(root, 'project');+ const skills = join(home, '.claude', 'skills');+ const skillFile = join(skills, 'deploy', 'SKILL.md');+ const routing = join(root, 'routing.md');+ const bin = join(root, 'bin', 'gbrain');+ for (const d of [join(root, 'bin'), project, join(skills, 'deploy')]) mkdirSync(d, { recursive: true });+ writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);+ chmodSync(bin, 0o755);+ writeFileSync(skillFile, '---\nname: deploy\ndescription: Ship a service\n---\nSteps.\n');+ writeFileSync(routing, '- **deploy**: roll it out to prod | ship the service now\n');+ const env = {+ HOME: home, GBRAIN_HOME: home, PATH: '/usr/bin:/bin', CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, XDG_CONFIG_HOME: undefined,+ GBRAIN_SKILL_LOADING: undefined, GBRAIN_HOOK_LANE: undefined, GBRAIN_AGENT_INSTRUCTIONS: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ };+ const run = (args: string[]) => runCli(args, { env, cwd: project });++ expect((await run(['skills', 'index', 'build', '--catalog', 'claude-code-user', '--dir', skills, '--harness', 'claude-code', '--routing', routing])).exitCode).toBe(0);+ writeFileSync(skillFile, '---\nname: deploy\ndescription: Ship a service safely\n---\nSteps.\n');+ const setup = await run(['setup', 'claude-code', '--skill-loading', 'resolve', '--yes', '--instructions-only', '--gbrain-bin', bin]);+ expect(setup.exitCode).toBe(0);+ const status = JSON.parse((await run(['skills', 'index', 'status', '--catalog', 'claude-code-user', '--json'])).stdout);+ expect(JSON.stringify(status)).toContain('--routing');+ expect(JSON.stringify(status)).toContain('"fresh":true');+ const hit = await run(['skills', 'resolve', '--catalog', 'claude-code-user', '--text', 'ship the service now', '--json']);+ expect(hit.stdout).toContain('deploy');+});diff --git a/test/transcripts-claude-code-session-side-files-9365.test.ts b/test/transcripts-claude-code-session-side-files-9365.test.tsnew file mode 100644index 0000000000..7fd0fa50e0--- /dev/null+++ b/test/transcripts-claude-code-session-side-files-9365.test.ts@@ -0,0 +1,50 @@+/**+ * #9365: Claude Code 2.1 writes per-session state files inside the+ * `<session-uuid>/` directory. They are never transcripts, so ingest skips+ * them instead of failing each one with `unknown format`.+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { expandPaths } from '../src/commands/transcripts.ts';+import { isClaudeCodeRemoteControlStateFile } from '../src/core/transcripts/claude-code.ts';++const SESSION = '123e4567-e89b-42d3-a456-426614174000';++describe('Claude Code per-session side files', () => {+ test('ingest discovery skips them and keeps every other .json file', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-cc-side-'));+ try {+ const s = join(root, SESSION);+ mkdirSync(join(s, 'subagents'), { recursive: true });+ mkdirSync(join(s, 'workflows'), { recursive: true });+ mkdirSync(join(root, 'notes', 'workflows'), { recursive: true });+ const side = [+ join(s, 'ccr-tip.json'),+ join(s, 'custom-title.json'),+ join(s, 'subagents', 'agent-abc.meta.json'),+ join(s, 'workflows', 'wf_123.json'),+ ];+ const keep = [+ join(root, 'export.json'),+ join(root, 'custom-title.json'),+ join(root, 'notes', 'workflows', 'wf_123.json'),+ ];+ for (const p of [...side, ...keep]) writeFileSync(p, '{}\n');+ const got = new Set(await expandPaths([root]));+ for (const p of side) expect(got.has(p)).toBe(false);+ for (const p of keep) expect(got.has(p)).toBe(true);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test('a side-file name outside a session directory is not a state file', () => {+ expect(isClaudeCodeRemoteControlStateFile(`/p/${SESSION}/custom-title.json`)).toBe(true);+ expect(isClaudeCodeRemoteControlStateFile(`C:\\p\\${SESSION}\\workflows\\wf_1.json`)).toBe(true);+ expect(isClaudeCodeRemoteControlStateFile('/p/not-a-session/custom-title.json')).toBe(false);+ expect(isClaudeCodeRemoteControlStateFile(`/p/${SESSION}/subagents/agent-abc.jsonl`)).toBe(false);+ expect(isClaudeCodeRemoteControlStateFile(`/p/${SESSION}.jsonl`)).toBe(false);+ });+});diff --git a/test/transcripts-claude-code-session-side-files.test.ts b/test/transcripts-claude-code-session-side-files.test.tsnew file mode 100644index 0000000000..5b95233215--- /dev/null+++ b/test/transcripts-claude-code-session-side-files.test.ts@@ -0,0 +1,32 @@+import { describe, test, expect } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { expandPaths } from '../src/commands/transcripts.ts';++const UUID = '123e4567-e89b-42d3-a456-426614174000';++describe('expandPaths Claude Code per-session side files', () => {+ test('excludes in-session state files but keeps other .json files', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gb-ccside-'));+ try {+ const s = join(root, UUID);+ mkdirSync(join(s, 'subagents'), { recursive: true });+ mkdirSync(join(s, 'workflows'), { recursive: true });+ const side = [+ join(s, 'ccr-tip.json'),+ join(s, 'custom-title.json'),+ join(s, 'subagents', 'agent-abc.meta.json'),+ join(s, 'workflows', 'wf_123.json'),+ ];+ const keep = [join(root, 'export.json')];+ for (const p of [...side, ...keep]) writeFileSync(p, '{}\n');+ const got = await expandPaths([root]);+ const real = (p: string) => got.some((g) => g.endsWith(p.slice(root.length)));+ for (const p of side) expect(real(p)).toBe(false);+ expect(real(keep[0]!)).toBe(true);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});