Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Folders whose names start with two dots are no longer treated as outside the brain (#9606)

Garry Tanea6fdb5fdf8a
diff --git a/behavior-changes.d/dotdot_folder_names_inside.md b/behavior-changes.d/dotdot_folder_names_inside.md
new file mode 100644
index 0000000000..8153318ea4
--- /dev/null
+++ b/behavior-changes.d/dotdot_folder_names_inside.md
@@ -0,0 +1,4 @@
+---
+kind: fix
+---
+Files in a folder whose name starts with two dots, such as ..drafts or ..., are now treated as inside the brain by the path checks this release fixes. Before, gbrain refused or skipped them, or called them outside, at those checks. Remote file uploads into such a folder are still refused; a separate fix covers that check. Three outputs change for such folders. First, gbrain frontmatter now expects the slug ..drafts/note for ..drafts/note.md (the same rule as any other folder) instead of note. Second, an extract-atoms transcript under meetings/..drafts/ gets the meetings label instead of corpus. Third, the LongMemEval call plan records a tracked, unchanged input under a ..inputs/ folder as a pinned INPUT line instead of a PRECONDITION. A gbrain.sourceRoot of ..drafts now scopes git commit-push to that folder instead of the whole checkout. Paths that really leave the brain are still refused.
diff --git a/changelog.d/vorflux-dotdot-folder-names.md b/changelog.d/vorflux-dotdot-folder-names.md
new file mode 100644
index 0000000000..c3812b8204
--- /dev/null
+++ b/changelog.d/vorflux-dotdot-folder-names.md
@@ -0,0 +1,15 @@
+**Files in a folder whose name starts with two dots, such as `..drafts` or `...`, are no longer refused or reported as outside the brain by sync, git commit-push, doctor, frontmatter, skills and the other checks listed below.**
+
+<!-- behavior-change: dotdot_folder_names_inside -->
+
+### Fixed
+- Many path checks asked "does this path start with two dots?" to catch a path that goes up and out of a folder. That question also matched a normal folder named `..drafts`, `..x` or `...`, so a file inside the brain was refused, skipped or called "outside". All of these checks now look at the first folder name exactly, through one shared helper. Remote file uploads into such a folder are still refused; a separate fix covers that check.
+- `gbrain git commit-push -- ..drafts/a.md` commits the file instead of failing with "outside the checkout", and a `gbrain.sourceRoot` of `..drafts` now scopes the commit to that folder instead of being dropped (which scoped it to the whole checkout).
+- Sync markers no longer report a file that was never committed as committed when the source sits in a `..` folder of its repository.
+- Skill packs and the skills catalog (`get_skill`, `list_skills`) read a `SKILL.md` that sits in, or is linked to, an in-pack `..shared` folder.
+- `gbrain frontmatter` expects the slug `..drafts/note` for `..drafts/note.md`, as for any other folder, instead of reporting a false slug mismatch; its backups of two `note.md` files in different `..` folders no longer overwrite each other.
+- Doctor's git-writer and foreign-writer checks, brain-repo hardening (including a `core.hooksPath` of `..hooks`), the first-turn brain rule, extract-benchmark, extract-atoms transcript labels, skillpack update bases, sync applicability, fence-write and reconcile path states, and the LongMemEval call plan treat such folders as inside.
+- Real escapes stay refused with the same messages as before: `../x`, an absolute path elsewhere, a sibling folder that shares the root's name prefix, a symlinked parent that points outside, and another Windows drive.
+
+### Added
+- `bun run verify` runs `check:relative-dotdot`, which refuses a new `.startsWith('..')` containment check in `src/` and points at `relativeEscapesRoot` in `src/core/path-confine.ts`.
diff --git a/package.json b/package.json
index a5f36b08c8..af43ea0da4 100644
--- a/package.json
+++ b/package.json
@@ -149,6 +149,7 @@
"check:pg-url-redaction": "bash scripts/check-pg-url-redaction.sh",
"check:source-scope-onboard": "bash scripts/check-source-scope-onboard.sh",
"check:getpage-scope": "node scripts/check-getpage-scoped-write.mjs",
+ "check:relative-dotdot": "node scripts/check-relative-dotdot.mjs",
"check:origin-assignment": "node scripts/check-origin-assignment.mjs",
"prepublish:clawhub": "bun run build:all",
"publish:clawhub": "clawhub package publish . --family bundle-plugin",
diff --git a/scripts/check-relative-dotdot.mjs b/scripts/check-relative-dotdot.mjs
new file mode 100644
index 0000000000..cc6813941a
--- /dev/null
+++ b/scripts/check-relative-dotdot.mjs
@@ -0,0 +1,81 @@
+#!/usr/bin/env node
+/**
+ * CI guard for the "two-dot folder name" path-containment bug class.
+ *
+ * The trap: `relative(root, p).startsWith('..')` is meant to ask "does p leave
+ * root?", but it also matches a legal first folder whose name starts with two
+ * dots (`..drafts/a`, `..x`, `...`). A file that is inside the root is then
+ * refused, or reported as outside, or (worse) a scope silently widens.
+ *
+ * The fix pattern: `relativeEscapesRoot(rel)` from src/core/path-confine.ts,
+ * which checks the first path component exactly (`..`, `../`, `..` + sep, or an
+ * absolute path), or `resolvedPrefixContained` over resolved paths.
+ *
+ * Heuristic: flag any `.startsWith('..')` call (single, double or backtick
+ * quotes) on a code line of a source file. Comment lines (starting with `//`,
+ * `*` or `/*`) are skipped. `startsWith('../')` and `startsWith(`..${sep}`)`
+ * are component-aware and are not flagged.
+ *
+ * Opt-out: a `gbrain-allow-dotdot-prefix: <reason>` comment on the line or the
+ * line above, for a check that is not about path containment.
+ *
+ * Exit 0 = clean, 1 = violations. Runs under node or bun. The scan root is
+ * argv[2], else GBRAIN_GUARD_ROOT, else `src` (the self-test points it at
+ * test/fixtures/guards/check-relative-dotdot.mjs/{bad,good}).
+ */
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const ROOT = process.argv[2] || process.env.GBRAIN_GUARD_ROOT || 'src';
+const PATTERN = /\.startsWith\(\s*(['"`])\.\.\1\s*\)/;
+const OPT_OUT = 'gbrain-allow-dotdot-prefix';
+
+// Temporary exception, paths relative to the scan root. Remove each entry when
+// its condition holds; a stale entry prints a note so the removal is not missed.
+const TEMPORARY = new Map([
+ ['core/ops/context.ts', 'validateUploadPath; fixed by PR #9570 (garrytan/gbrain), remove this entry when either PR lands second'],
+]);
+
+function walk(dir, out) {
+ for (const name of readdirSync(dir)) {
+ if (name === 'node_modules' || name === '.git') continue;
+ const p = join(dir, name);
+ const st = statSync(p);
+ if (st.isDirectory()) walk(p, out);
+ else if (/\.(ts|tsx|mts|cts|js|mjs|cjs)$/.test(name) && !/\.d\.ts$/.test(name)) out.push(p);
+ }
+ return out;
+}
+
+if (!existsSync(ROOT)) {
+ console.error(`check-relative-dotdot: scan root ${ROOT} does not exist`);
+ process.exit(1);
+}
+
+const violations = [];
+const used = new Set();
+for (const file of walk(ROOT, [])) {
+ const rel = relative(ROOT, file).split('\\').join('/');
+ const lines = readFileSync(file, 'utf8').split('\n');
+ lines.forEach((line, i) => {
+ const t = line.trim();
+ if (t.startsWith('//') || t.startsWith('*') || t.startsWith('/*')) return;
+ if (!PATTERN.test(line)) return;
+ if (line.includes(OPT_OUT) || (i > 0 && lines[i - 1].includes(OPT_OUT))) return;
+ if (TEMPORARY.has(rel)) { used.add(rel); return; }
+ violations.push(`${join(ROOT, rel)}:${i + 1}: ${t}`);
+ });
+}
+
+for (const [rel, why] of TEMPORARY) {
+ if (!used.has(rel) && existsSync(join(ROOT, rel))) console.log(`note: temporary exception ${rel} no longer matches (${why}); delete it from scripts/check-relative-dotdot.mjs`);
+}
+
+if (violations.length) {
+ console.error('ERROR: `.startsWith(\'..\')` also matches a legal folder name such as `..drafts`.');
+ console.error('Use relativeEscapesRoot(rel) from src/core/path-confine.ts (or resolvedPrefixContained).');
+ console.error(`Opt out only for a check that is not about paths: // ${OPT_OUT}: <reason>`);
+ for (const v of violations) console.error(` ${v}`);
+ process.exit(1);
+}
+console.log('OK: no prefix-only `..` containment checks');
diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsv
index 65ebf89247..c69bd82203 100644
--- a/scripts/guards-manifest.tsv
+++ b/scripts/guards-manifest.tsv
@@ -98,6 +98,7 @@ check-opencode-pin.sh repostate exempt pin-stamp drift check (OPENCODE-CLI-PIN.m
check-pin-doc-privacy.sh repostate exempt PIN-doc placeholder discipline (no operator paths/key material/emails in docs/mcp/*-CLI-PIN.md); own bun guard tests in test/check-bootstrap-guards.test.ts
check-origin-assignment.mjs scanner yes #6948: page origin writes (UPDATE pages SET source_path=<non-NULL>, INSERT INTO pages carrying source_path, UPDATE pages SET slug=<rename>) outside src/core/persistence/origin-guard.ts unless marked origin-guard-ok: <reason>; argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS
check-getpage-scoped-write.mjs scanner yes unscoped-getPage + write co-occurrence scanner (source-isolation bug class); argv root override; fixtures under test/fixtures/guards/; also in verify CHECKS
+check-relative-dotdot.mjs scanner yes prefix-only `..` containment checks (`.startsWith('..')` also matches a legal `..drafts` folder); use relativeEscapesRoot from src/core/path-confine.ts; opt-out gbrain-allow-dotdot-prefix: <reason>; one temporary exception for src/core/ops/context.ts until PR #9570 lands; argv/GBRAIN_GUARD_ROOT root override; in verify CHECKS
check-core-guard-coverage.mjs scanner yes core memory write-path guard coverage: PreparedMutation builders route through preparePageMutation or a reasoned EXEMPT entry, wrappers forward exclusiveSources; argv/GBRAIN_GUARD_ROOT root override; in verify CHECKS
check-orphan-modules.mjs scanner yes runtime-reachability walk (static+dynamic relative imports) from cli/mcp/plugin/admin entrypoints + package.json exports; hard-fails untested orphans, requires a reasoned PERMITTED_TEST_ONLY entry per test-only module (stale entries fail); fixture root via argv/GBRAIN_GUARD_ROOT; knip v5 evaluated + rejected (crashes on repo layout — see script header)
check-test-placeholders.mjs scanner yes TypeScript AST (CallExpression) scan of test/**/*.test.ts for no-op expect(true)/expect(1) placeholders; path+test+count allowlist (disabled in fixture mode); fixture root via argv/GBRAIN_GUARD_ROOT; in verify CHECKS
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index edff034ca7..38e8f1e735 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -50,7 +50,7 @@ src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut re
src/commands/config.ts 1546 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +4 GBRA-377 PR B: skills.resolver.* file-plane routing (doc line, the one-line router and its two dispatch lines; logic in core/setup/skill-resolver-config.ts); +8 train C: #8921 #7346 nested credential redaction on top of master's config growth; +1 train C: #9145 config.ts edit on top of #8921 #7346; +7 #8920: plural, acronym and credential secret words with the count-word exception (isSensitiveConfigKey) and URL userinfo masking (redactConfigValue)
src/commands/mcp-expose.ts 1524 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts); +5 GBRA-583: one-click Cursor/Claude link lines in the Next block and verified --status, and install_links in --json (builders live in core/connector-install-links.ts)
src/core/behavior-change-notice.ts 1774 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 E1/F3/F4 rows (since TBD until the merge slot), re-summed at the master merge; +1 GBRA-284 personal_sources_gbra284 row (since TBD until the merge slot) (re-summed at the QM wave merge onto master v0.60.626.0: 1692 + 3); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 GST-1158 v3: the qm_personal_structured_gst1158 row (since TBD until the merge slot); +1 #8477 GST-1158 F2 personal-tools row at the QM wave merge (1695 + 1); +1 GST-1158 F9: the attest_direct_page_writes_deferred_gst1158 row (since TBD until the merge slot); +1 #8483 memory_propose row at the QM wave merge (1696 + 1); +1 GST-1094 gap 4: the qm_admin_http_gst1094 row (since TBD until the merge slot); +1 GST-1158: the member_email_link_gst1158 row (since TBD until the merge slot); +2 #8479 member-email rows at the QM wave merge (1697 + 2); +1 GST-2112: ingest_keeps_readers_gst2112 row (re-summed at the Q7 v0.60.627.0 merge: 1692 + 1); +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-2116 commit_push_skipped_paths_gst2116 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q10 slot on #9009 ee0f4a78: 1694 + 1; +1 GST-2118 pending_ledger_flagged_gst2118 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the Q12 slot on #9016 afb49de5: 1695 + 1; +1 GBRA-431: read_scope_params_gbra431 row (rows are data and cannot move), re-summed at the #9032 stack merge: 1697 measured; +2 GST-2201 sync_restored_file_gst2201 and purge_keeps_committed_file_gst2201 rows (since is the current VERSION until the merge slot; +1 GST-2243 remember_share_gst2243 row (re-summed at the #9098 stack merge: 1699 + 1); +1 GST-2312 #9024 sync_filter_owned_hold_9024 row (re-summed at the #9064 stack merge: 1700 + 1; rows are data and cannot move); +2 access-privacy wave (0.60.649.0): the owner_private_facts_gst2089 and private_labels_write_ahead_gst2092 rows; +1 GBRA-443 private_labels_batch_exit_gbra443 row (rows are data and cannot move), re-summed at the 0.60.650.0 slot on #9038: 1703 + 1; +1 postgres_tls_default row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.651.0 merge: 1704 + 1; +1 GST-2331 sync_reads_fetch_nothing_gst2331 row (rows are data and cannot move), re-summed at the 0.60.654.0 stack on #9045 6ff5540d: 1705 + 1; +7 QM wave (#9037) rows: attest_scope_read_ops_gst1158, attest_direct_page_writes_deferred_gst1158, personal_sources_gbra284, qm_personal_structured_gst1158, memory_propose_held_writes_gst1158, member_email_link_gst1158, qm_admin_http_gst1094 (re-summed at the 0.60.655.0 stack on #9110 f9b2072e: 1706 + 7); +1 GST-2228 recreated_takes_section_keeps_stored_takes_gst2228 row (since TBD; re-summed at the keep-takes-and-link-dates train merge: 1713 + 1); +1 GST-2228 links_rows_keep_own_dates_gst2228 row (since TBD; re-summed at the same train merge: 1714 + 1); +2 the W1 + memory proposals train (#9133): attest_every_page_write_deferred_gst2249 and memory_proposals_owner_http_gst2407 rows (rows are data and cannot move), re-summed at the #9138 v0.60.661.0 stack merge: 1715 + 2 = 1717 measured; +1 #8903 effect_git_secret_gate_gst1923 row (rows are data and cannot move), re-summed at the 0.60.664.0 stack on #9142 3931adb4: 1717 + 1; +1 GST-2407 PR 3: qm_recall_own_page_contract_v4 row (rows are data and cannot move), re-summed at the 0.60.666.0 stack on #9148 69c12917: 1718 + 1; +2 GST-363 PR 1 and PR 3 (#9135): the serves_several_labels_gst363 and stdio_member_per_harness_gst363 rows; +3 #9134 train rows member_forget_names_host_9101, refresh_fence_retry_id_gst2353 and recorded_read_view_args_gst2214 (rows are data and cannot move), re-summed at the #9134 slot merge onto #8829 dfc24954: 1721 + 3; +3 source-checkouts wave rows (autopilot_git_reconcile_gbra386, unknown_drift_history_rescreen, refresh_abandon_members_gst1465), re-summed at the #9137 stack merge: 1724 + 3; persistence train 13 at 0.60.676.0: its five rows on top of 0.60.675.0; +1 GST-2250 reconcile_publish_opt_out_gst2250 row (since TBD until the merge slot; rows are data and cannot move); +1 #8902 unmanaged_push_history_scan_8902 row (re-summed at the 0.60.678.0 stack on 501742d9: 1733 + 1); +1 GST-2246 maintain_safe_free_phases_gst2246 row (since TBD until the merge slot; rows are data and cannot move), re-summed on the doctor/dream/enrich train at the 0.60.679.0 slot merge onto #9170 82932eda: 1734 + 1; +2 GST-2462 privacy_label_ignored_gst2462 and access_page_rules_gst2462 rows (rows are data and cannot move), re-summed at the #9173 slot merge onto 49a922ef: 1735 + 2; +1 GST-2107 follow-up write_capacity_low_not_refusal_gst2107 row (rows are data and cannot move), re-summed at the 0.60.681.0 slot merge onto #9173 c08d0c8b: 1737 + 1; +1 GST-2490: owner_reads_derived_gst2490 row (rows are data and cannot move); +1 GST-2468: the label_only_operator_repairs_gst2468 row (a BEHAVIOR_CHANGES row cannot move); +1 GST-2446 remember_pageless_reply_gst2446, +1 GST-2492 strict_held_facts_gst2492 and +1 GST-2346 D1 owner_facts_shared_gst2346 rows (rows are data and cannot move), re-summed at the 0.60.685.0 train merge onto #9181 405ea4cf: 1740 + 3; +1 GST-2476: the readers_label_setter_gst2476 row (rows are data and cannot move), re-summed at the #9184 slot merge onto the #9179 train 361d57c6: 1743 + 1; +1 GST-2487: the fence_fact_private_in_place_gst2487 row (rows are data and cannot move), at the same slot merge of #9188 0075f09a: 1744 + 1; +1 GST-2515: the sync_status_commits_waiting_gst2515 row (rows are data and cannot move), at the 0.60.688.0 slot merge onto 599b1234: 1745 + 1; +3 GST-2519: commit_push_untrack_gst2519, db_only_labels_kept_gst2519 and git_ignored_label_repair_gst2519 rows (rows are data and cannot move), re-summed at the 0.60.691.0 slot merge onto #9167 ad4f0aef: 1746 + 3; +3 GST-2492 PR 2: the remember_pageless_ask, strict_fact_writers_held and sync_strict_requires_managed rows (rows are data and cannot move), re-summed at the master v0.60.691.0 merge: 1749 + 3; +3 GST-2346 rows owner_forget_private, owner_forget_readers_page and member_save_withdrawn_scope (rows are data and cannot move), re-summed at the 0.60.693.0 slot merge onto #9202 840858e9: 1752 + 3; +2 GST-2518 page_label_widening_held_gst2518 and GST-2521 owner_labels_guarded_gst2521 rows and +1 GST-2511 fence_fact_widening_held_gst2511 row (rows are data and cannot move), re-summed at the 0.60.694.0 slot merge onto master 2c8320d7: 1755 + 3; +3 the GST-2515/GST-2520 notifier_retry_unwatched_gst2515 and strict_skip_mode_refusal_gst2520 rows and the GST-2456 unmanaged_push_every_site_gst2456 row, re-summed at the 0.60.698.0 slot merge onto #9217 887398f0: 1758 + 3; +2 GST-2407: context_pack scope read and attestRead over the owner route; +9 releases per batch: the generated-table import, the releasedIn helper and its comment, the spread of RELEASED_BEHAVIOR_CHANGES; new rows now live in behavior-changes.d/ and stop growing this file (re-summed at the master v0.60.704.0 merge: 1763 + 9 = 1772 measured); +2 #7646 (GBRA-404 salvage): the disclosure lists releases oldest first whatever the table order
-src/core/git/commit-push.ts 1615 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31; +47 #8928 salvage rebuild (GBRA-404) #7752: previewPaths (the dry run asks git against a copied index), admitPaths/flaggedEntries/previewRoots split out of commitPaths and shared with it, settlePending exported (re-summed on master v0.60.699.0: 1658 + 47); +1 GBRA-404 /ship round 2: the dry run stages into its temporary index copy for real (staged-rename partner refusal); GST-2767: the git runner (git-run.ts) and the skipped-path checks with their reasons (skipped-paths.ts) moved out, 1600; +14 GST-2767 staged_for_removal refusal and dry-run skipped-path parity; +1 commit_paths_unmerged: admitPaths calls assertNoUnmergedPaths (skipped-paths.ts)
+src/core/git/commit-push.ts 1616 ratchet GST-2519: --untrack (#7753 port: untrackTargets, untrackPaths; untrackAdmitted, the managed-worktree storage.db_only admission; previewUntrack) and the staged-removal hint in skippedPathsError grow the commit door past the 1500 default (master 1487 + 140); GST-2456 (#9174): crossed the 1500 unlisted cap at the GST-2456 merge of master v0.60.678.0: pushBase (the scan base and lease read live from every push URL, #5138) and the scan budget and progress options; Ctx and publish internals keep it in this file (1487 + 31), re-summed at the master 0c577834 merge into #9198: 1627 + 31; +47 #8928 salvage rebuild (GBRA-404) #7752: previewPaths (the dry run asks git against a copied index), admitPaths/flaggedEntries/previewRoots split out of commitPaths and shared with it, settlePending exported (re-summed on master v0.60.699.0: 1658 + 47); +1 GBRA-404 /ship round 2: the dry run stages into its temporary index copy for real (staged-rename partner refusal); GST-2767: the git runner (git-run.ts) and the skipped-path checks with their reasons (skipped-paths.ts) moved out, 1600; +14 GST-2767 staged_for_removal refusal and dry-run skipped-path parity; +1 commit_paths_unmerged: admitPaths calls assertNoUnmergedPaths (skipped-paths.ts); +1 the relativeEscapesRoot import (path-confine.ts) so a ..drafts folder is not read as outside the checkout
src/commands/auth.ts 1512 ratchet new row: crossed the 1500 unlisted cap at the v0.60.595.0 merge: GST-1113 --attest-sources help lines plus GST-1158 F3 --attest-read help lines (3); CLI help lines cannot move; re-measured at the Train A merge onto master v0.60.708.0: 1503 + 2 (the #8930 shared-token notice) = 1505; re-measured at the Train C merge onto Train B (#9246 onto #9223): 1505 -> 1509, both sides' growth; +3 Wakeshift PR 2 (#8709), one line each: revoke (by name) calls forgetWakePrincipal for every token row its UPDATE returned (RETURNING 1 became RETURNING id, so no line added there), revokeById calls it for the revoked token id, and revokeClient calls it for the revoked OAuth client id; each call ends that principal's open watches and queues its Wakeshift forget (logic in core/wakeshift/forget.ts) after the command's own UPDATE/DELETE; master 1509 + 3 = 1512
src/core/markdown.ts 1501 ratchet new row: crossed the 1500 unlisted cap at the train C merge: #8921 #7052 tag_too_long hold (tagLengthHold import; the limit lives in core/tag-limit.ts) on top of master's 1500
src/mcp/dispatch.ts 1502 ratchet new row: crossed the 1500 unlisted cap with GBRA-504 guest notes (+4): the guest attribution option threaded into dispatch (parsing and checks live in core/guests/admission.ts); next growth should peel the response-cap block into a sibling module
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 78d1f886aa..f978e9a6f8 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -157,6 +157,7 @@ CHECKS=(
"check:fixture-privacy"
"check:source-scope-onboard"
"check:getpage-scope"
+ "check:relative-dotdot"
"check:origin-assignment"
"check:no-double-retry"
"check:batch-audit-site"
diff --git a/src/commands/doctor/checks/foreign-writers.ts b/src/commands/doctor/checks/foreign-writers.ts
index dc398c42c1..86702d0e22 100644
--- a/src/commands/doctor/checks/foreign-writers.ts
+++ b/src/commands/doctor/checks/foreign-writers.ts
@@ -35,6 +35,7 @@ import { doctorVerify, infoCheck } from '../check-fix.ts';
import { SCAN_REPORT_RESERVE_MS } from '../budget.ts';
import { sourceRoots } from './git-convergence.ts';
import type { BrainEngine } from '../../../core/engine.ts';
+import { relativeEscapesRoot } from '../../../core/path-confine.ts';
export const PLUMBING_WINDOW_S = 10 * 60;
export const UNCONFIRMED_WINDOW_MS = 60_000;
@@ -159,7 +160,7 @@ async function repositories(engine: BrainEngine): Promise<{ repos: Repo[]; skipp
const rel = relative(canonical(top), canonical(root)).split(sep).join('/');
const entry = repo.checkouts.get(top) ?? { top, gitDir, source_ids: [], roots: [] };
entry.source_ids.push(...ids.filter(id => !entry.source_ids.includes(id)));
- entry.roots.push(rel.startsWith('..') ? '' : rel);
+ entry.roots.push(relativeEscapesRoot(rel) ? '' : rel);
repo.checkouts.set(top, entry);
repos.set(key, repo);
}
diff --git a/src/commands/doctor/checks/git-writer.ts b/src/commands/doctor/checks/git-writer.ts
index 7d2b394bc5..50a3892281 100644
--- a/src/commands/doctor/checks/git-writer.ts
+++ b/src/commands/doctor/checks/git-writer.ts
@@ -31,6 +31,7 @@ import { configuredSourceRoots, localCommitsOutsideRoots, pendingWriteThroughSti
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { doctorVerify } from '../check-fix.ts';
import { sourceRoots } from './git-convergence.ts';
+import { relativeEscapesRoot } from '../../../core/path-confine.ts';
export const CHECKOUT_LAG_WARN_MS = 60 * 60_000;
export const DIRTY_AGE_WARN_MS = 30 * 60_000;
@@ -57,7 +58,7 @@ async function checkouts(ctx: DoctorContext): Promise<Checkout[]> {
const rel = relative(canonical(top), canonical(root)).split(sep).join('/');
const entry = byTop.get(top) ?? { top, source_ids: [], roots: [] };
entry.source_ids.push(...ids);
- entry.roots.push(rel.startsWith('..') ? '' : rel);
+ entry.roots.push(relativeEscapesRoot(rel) ? '' : rel);
byTop.set(top, entry);
}
return [...byTop.values()];
diff --git a/src/commands/extract-benchmark.ts b/src/commands/extract-benchmark.ts
index 097bc25843..cde44add81 100644
--- a/src/commands/extract-benchmark.ts
+++ b/src/commands/extract-benchmark.ts
@@ -39,6 +39,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { loadActivePackBestEffort } from '../core/schema-pack/best-effort.ts';
import { getExtractableSpec } from '../core/schema-pack/extractable.ts';
import { locateMutablePackFile } from '../core/schema-pack/mutate.ts';
+import { relativeEscapesRoot } from '../core/path-confine.ts';
export interface BenchmarkFixture {
fixture_id: string;
@@ -119,7 +120,7 @@ export function validateFixturePath(
// Resolve() collapses .., but we already rejected those above. Confirm
// the resolved path is within packRoot.
const rel = relative(packRoot, absolute);
- if (rel.startsWith('..') || isAbsolute(rel)) {
+ if (relativeEscapesRoot(rel)) {
throw new Error(
`pack fixture_corpus path resolves OUTSIDE the pack root. ` +
`Pack root: ${packRoot}. Resolved: ${absolute}. ` +
@@ -142,7 +143,7 @@ export function validateFixturePath(
const real = realpathSync(absolute);
const realRoot = realpathSync(packRoot);
const realRel = relative(realRoot, real);
- if (realRel.startsWith('..') || isAbsolute(realRel)) {
+ if (relativeEscapesRoot(realRel)) {
throw new Error(
`pack fixture_corpus realpath resolves outside the pack root ` +
`(an intermediate symlink may be redirecting). ` +
diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.ts
index 9654cf25fe..b4d401a11d 100644
--- a/src/commands/frontmatter.ts
+++ b/src/commands/frontmatter.ts
@@ -45,7 +45,7 @@ import {
import { collectGitVisibleFiles } from '../core/git-visible-files.ts';
import { GIT_PATHSPEC_ENV_VARS, literalPathspecs } from '../core/git-env.ts';
import { isMarkdownFilePath, pruneDir, slugifyPath } from '../core/sync.ts';
-import { isPathContained } from '../core/path-confine.ts';
+import { isPathContained, relativeEscapesRoot } from '../core/path-confine.ts';
/** Test seams: the stream `validate --stdin` reads, and the directory `--staged` runs git in. */
export interface FrontmatterIo {
@@ -459,7 +459,7 @@ async function runValidate(rest: string[], io: FrontmatterIo): Promise<void> {
const rel = relative(brainRoot, file);
// Files above/outside the brain root fall back to basename rather than
// emitting a "../"-prefixed slug for non-brain files.
- const slugPath = rel && !rel.startsWith('..') ? rel : basename(file);
+ const slugPath = rel && !relativeEscapesRoot(rel) ? rel : basename(file);
const check = checkContent(content, slugPath, flags.importable);
const result = toResult(file, check);
const rescuable = flags.includeAmbiguous && check.warnings.some(w => w.code === 'FRONTMATTER_COMMENT_VALUE');
diff --git a/src/core/bootstrap/render-host.ts b/src/core/bootstrap/render-host.ts
index 1e8c6a5097..c11c0ee0fc 100644
--- a/src/core/bootstrap/render-host.ts
+++ b/src/core/bootstrap/render-host.ts
@@ -7,6 +7,7 @@
import { homedir } from 'node:os';
import { join, relative, resolve, sep } from 'node:path';
+import { relativeEscapesRoot } from '../path-confine.ts';
/**
* Whether a workspace belongs to OpenClaw, from OpenClaw's own layout: the
@@ -27,7 +28,7 @@ export function detectOpenClawWorkspace(
const underWorkspaceOf = (stateDir: string): boolean => {
const rel = relative(resolve(stateDir), ws);
const first = rel.split(sep)[0] ?? '';
- return rel !== '' && !rel.startsWith('..') && /^workspace(-.+)?$/.test(first);
+ return rel !== '' && !relativeEscapesRoot(rel) && /^workspace(-.+)?$/.test(first);
};
if (env.OPENCLAW_STATE_DIR && underWorkspaceOf(env.OPENCLAW_STATE_DIR)) return true;
const profile = relative(resolve(home), ws).split(sep)[0] ?? '';
diff --git a/src/core/brain-repo-durability.ts b/src/core/brain-repo-durability.ts
index e276144b37..cbef3d1711 100644
--- a/src/core/brain-repo-durability.ts
+++ b/src/core/brain-repo-durability.ts
@@ -51,6 +51,7 @@ import { readFix } from './ops/op-fix.ts';
import filingRulesDoc from '../../skills/_brain-filing-rules.json';
import { GIT_PATHSPEC_ENV_VARS, gitChildEnv } from './git-env.ts';
import { commitAndPush, commitPathsLocked, readIntegrateConflict, SOURCE_ROOT_CONFIG } from './git/commit-push.ts';
+import { relativeEscapesRoot } from './path-confine.ts';
export { execFileBounded, type BoundedExecOptions } from './bounded-child-exec.ts';
@@ -545,7 +546,7 @@ function gitDirPath(repoPath: string, rel: string): string {
function pathContains(parent: string, child: string): boolean {
const rel = relative(parent, child);
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+ return !relativeEscapesRoot(rel);
}
export function resolveHooksDir(repoPath: string): { dir: string; tracked: boolean } {
@@ -712,7 +713,7 @@ export function commitWriteThroughFile(
): boolean {
try {
const rel = relative(repoPath, absPath);
- if (!rel || rel.startsWith('..') || isAbsolute(rel)) return false;
+ if (!rel || relativeEscapesRoot(rel)) return false;
return commitPathsLocked(repoPath, [absPath], `gbrain: ${action} ${slug}`, { lockWaitMs: WRITE_THROUGH_LOCK_WAIT_MS }) !== null;
} catch {
return false;
@@ -1144,7 +1145,7 @@ function recordSourceRoot(top: string, sourcePath: string): void {
stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: gitChildEnv({ ...GIT_ENV }) }).toString();
try {
const rel = relative(realpathSync(top), realpathSync(sourcePath)).split(sep).join('/');
- if (rel.startsWith('..') || isAbsolute(rel)) return;
+ if (relativeEscapesRoot(rel)) return;
let current: string[] = [];
try { current = run(['--get-all', SOURCE_ROOT_CONFIG]).split('\n').map(v => v.trim()).filter(Boolean); } catch { /* unset */ }
const value = rel || '.';
diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.ts
index bc2535a70b..c8c8552867 100644
--- a/src/core/brain-writer.ts
+++ b/src/core/brain-writer.ts
@@ -20,7 +20,7 @@ import { assertManagedFilesystemWrite } from './persistence/filesystem-guard.ts'
import { createHash } from 'crypto';
import { loadBoundedYaml as yamlLoad } from './data-frontmatter.ts';
import { existsSync, readFileSync, readdirSync, copyFileSync, writeFileSync, mkdirSync, lstatSync } from 'fs';
-import { join, relative, resolve, dirname, basename, isAbsolute } from 'path';
+import { join, relative, resolve, dirname, basename } from 'path';
import type { BrainEngine } from './engine.ts';
import { isConnectorSourceKind } from './persistence/connector-kinds.ts';
import type { ProgressReporter } from './progress.ts';
@@ -37,6 +37,7 @@ import {
} from './markdown.ts';
import { DEFAULT_METAFILE_PAGES_MODE, isMarkdownFilePath, isSyncable, pruneDir, readMetafilePagesMode, slugifyPath, type MetafilePagesMode } from './sync.ts';
import { diskMetafileHeads, metafilePagePredicate } from './sync-metafile-pages.ts';
+import { relativeEscapesRoot } from './path-confine.ts';
export type { ParseValidationCode };
@@ -153,7 +154,7 @@ export function createFrontmatterBackup(filePath: string, opts: FrontmatterBacku
const resolvedFile = resolve(filePath);
const resolvedSource = resolve(opts.sourcePath ?? dirname(resolvedFile));
const rel = relative(resolvedSource, resolvedFile);
- const safeRel = rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : basename(resolvedFile);
+ const safeRel = rel && !relativeEscapesRoot(rel) ? rel : basename(resolvedFile);
const root = opts.backupRoot ?? defaultFrontmatterBackupRoot(opts.runId);
const backupPath = join(root, sourceKey(resolvedSource), safeRel + '.bak');
mkdirSync(dirname(backupPath), { recursive: true });
diff --git a/src/core/cycle/extract-atoms-generation.ts b/src/core/cycle/extract-atoms-generation.ts
index eae0d1bc2b..9f5f01690a 100644
--- a/src/core/cycle/extract-atoms-generation.ts
+++ b/src/core/cycle/extract-atoms-generation.ts
@@ -4,7 +4,7 @@
* path, with the rename map) and slugs. Peeled out of extract-atoms.ts (module-size ratchet).
*/
import { existsSync } from 'node:fs';
-import { isAbsolute, relative, resolve, sep } from 'node:path';
+import { relative, resolve, sep } from 'node:path';
import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import { isAvailable } from '../ai/gateway.ts';
import { ATOM_KIND, atomGenerationAdapter, atomOwnerKey, atomPagePin, TRANSCRIPT_KEY_PREFIX, type AtomGenerationContext } from '../generations/adapters/atoms.ts';
@@ -12,6 +12,7 @@ import { markdownItem } from '../generations/adapters/page.ts';
import type { GenerationKey } from '../generations/contract.ts';
import { publishGeneration } from '../generations/publish.ts';
import type { ExtractAtomsItem } from './extract-atoms-input.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
/**
* GBRA-161: one unmanaged item's atoms, their provenance edges (#3961, #4733), the completion flip (source_hash, #4148)
@@ -54,7 +55,7 @@ export const heldLine = (originLabel: string, key: GenerationKey, reason: string
/** GBRA-161 PR 1b: the corpus root a discovered transcript lies under, with the label its key carries. */
export function transcriptRoot(filePath: string, corpusDir: string, meetingDir: string | undefined): { path: string; label: string } {
- const inside = (dir: string) => { const rel = relative(resolve(dir), resolve(filePath)); return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel); };
+ const inside = (dir: string) => { const rel = relative(resolve(dir), resolve(filePath)); return rel !== '' && !relativeEscapesRoot(rel); };
return meetingDir && inside(meetingDir) && !(inside(corpusDir) && resolve(corpusDir).length > resolve(meetingDir).length)
? { path: meetingDir, label: 'meetings' } : { path: corpusDir, label: 'corpus' };
}
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index e4f700a3c0..b52f04ed4c 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -36,7 +36,7 @@
import { execFileSync } from '../spawn.ts';
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendFileSync, rmSync } from 'node:fs';
-import { dirname, isAbsolute, relative } from 'node:path';
+import { dirname, relative } from 'node:path';
import type { BrainEngine, NewFact, FactVisibility, FactKind, FactAttribution } from '../engine.ts';
import type { ResolutionSource } from '../entities/resolve.ts';
@@ -65,6 +65,7 @@ import { gitChildEnv } from '../git-env.ts';
import { readOnlyCheckout } from '../persistence/mirror-read-only.ts';
import { bodyUnread } from '../page-body/page-shape.ts';
import { bestEffortStoredBodyMirror, fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody } from './file-body-guard.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
/** Resolved source binding for the entity page. */
export interface FenceTarget {
@@ -206,7 +207,7 @@ export type FactFenceGitPathState = 'clean' | 'self_dirty' | 'foreign_dirty' | '
export function gitPathState(repoPath: string, filePath: string): FactFenceGitPathState {
try {
const rel = relative(repoPath, filePath);
- if (!rel || rel.startsWith('..') || isAbsolute(rel)) return 'unknown';
+ if (!rel || relativeEscapesRoot(rel)) return 'unknown';
const status = execFileSync(
'git',
['-C', repoPath, 'status', '--porcelain=v1', '--untracked-files=all', '--', rel],
diff --git a/src/core/git/commit-push.ts b/src/core/git/commit-push.ts
index fbbeb75dd1..a3bc4daec1 100644
--- a/src/core/git/commit-push.ts
+++ b/src/core/git/commit-push.ts
@@ -42,6 +42,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { shellQuote, type Action } from '../agent-output.ts';
import { isSyncable, resolveSlugForPath } from '../sync.ts';
import { isDeclaredDbOnlySlug, storageConfigFromYaml, unresolvedDbOnlyIn, type StorageConfig } from '../storage-config.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
export const COMMIT_LOCK_NAME = 'brain-commit.lock';
/** Taken by pre-#6530 helpers and hooks; held too so they still exclude us during the mixed-version window. */
@@ -301,7 +302,7 @@ export function scopePaths(root: string, paths: string[], cwd: string): string[]
const named = resolve(cwd, p);
const abs = join(canonicalFilesystemPath(dirname(named)), basename(named));
const rel = relative(root, abs);
- if (rel === '' || rel === '.' || rel.startsWith('..') || isAbsolute(rel)) {
+ if (rel === '' || rel === '.' || relativeEscapesRoot(rel)) {
throw opError('commit_paths_invalid', `Path ${p} is ${rel === '' || rel === '.' ? 'the whole checkout' : 'outside the checkout'}.`,
'Pass the explicit file(s) you wrote inside the checkout; a repo-wide commit would sweep up other writers\' files.', { detail: p });
}
@@ -319,7 +320,7 @@ export function configuredSourceRoots(root: string): string[] {
for (const raw of git(root, ['config', '--get-all', SOURCE_ROOT_CONFIG]).stdout.split('\n').map(v => v.trim()).filter(Boolean)) {
const rel = (isAbsolute(raw) ? relative(root, raw) : raw).split('\\').join('/').replace(/^(\.\/)+/, '').replace(/\/+$/, '');
if (rel === '' || rel === '.') return [''];
- if (!rel.startsWith('..')) roots.push(rel);
+ if (!relativeEscapesRoot(rel)) roots.push(rel);
}
return roots.length ? [...new Set(roots)] : [''];
}
@@ -636,7 +637,7 @@ function untrackTargets(root: string, rel: string[]): string[] {
export function untrackAdmitted(root: string, rel: string[], managed: ManagedFilesystemRoot): string[] {
const files = untrackTargets(root, rel);
const base = relative(root, managed.root).split(sep).join('/');
- const prefix = base && !base.startsWith('..') ? `${base}/` : '';
+ const prefix = base && !relativeEscapesRoot(base) ? `${base}/` : '';
const yml = git(root, ['show', `HEAD:${prefix}gbrain.yml`]);
let disk: string | null = null;
try { disk = readFileSync(join(managed.root, 'gbrain.yml'), 'utf8'); } catch { disk = null; }
@@ -860,7 +861,7 @@ export function commitPathsLocked(repo: string, rel: string[], message: string,
assertNoOperationInProgress(root);
const paths = scopePaths(root, rel, root);
const own = relative(realpathSync(root), realpathSync(repo)).split('\\').join('/');
- const roots = [own.startsWith('..') ? '' : own];
+ const roots = [relativeEscapesRoot(own) ? '' : own];
let lock: CommitLock;
try { lock = acquireCommitLock(root, opts.lockWaitMs); } catch (e) {
if (PENDING_NOTED.has((e as { code?: string }).code ?? '')) notePending(root, paths);
diff --git a/src/core/path-confine.ts b/src/core/path-confine.ts
index d9b63ddb51..1c5cdc658e 100644
--- a/src/core/path-confine.ts
+++ b/src/core/path-confine.ts
@@ -65,6 +65,25 @@ export function resolvedPrefixContained(
return resolvedChild === resolvedParent || resolvedChild.startsWith(parentWithSep);
}
+/**
+ * True when a `path.relative(root, x)` result leaves `root`: it is exactly
+ * `..`, starts with a `..` path component (`../` or `..` + the platform
+ * separator), or is absolute (another drive on Windows). A bare
+ * `startsWith('..')` is wrong: it also matches a legal first folder such as
+ * `..drafts`, `..x` or `...`, which sits inside the root.
+ *
+ * Accepts both native and `/`-joined relative paths, because several callers
+ * normalize to `/` before checking. `pathOps` lets tests pass `path.win32` to
+ * check backslash and drive-letter shapes on POSIX CI. The empty string (the
+ * root itself) is NOT an escape; callers keep their own policy for it.
+ */
+export function relativeEscapesRoot(
+ rel: string,
+ pathOps: { sep: string; isAbsolute(p: string): boolean } = { sep, isAbsolute },
+): boolean {
+ return rel === '..' || rel.startsWith('../') || rel.startsWith('..' + pathOps.sep) || pathOps.isAbsolute(rel);
+}
+
/**
* Trust gate for a walk-up routing dotfile, given its `lstatSync` Stats.
*
@@ -214,5 +233,5 @@ export function isWriteTargetContained(target: string, root: string): boolean {
const base = realpathOrResolve(existing);
const finalPath = tail.length ? join(base, ...tail) : base;
const rel = relative(resolvedRoot, finalPath);
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+ return !relativeEscapesRoot(rel);
}
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index ce33fd53ef..1254a47153 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -10,7 +10,7 @@ import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { REVISION_BACKFILL_PENDING, type PageSnapshot } from '../page-state/types.ts';
import { revisionBackfillExhausted, REVISION_BACKFILL_RESUME_COMMAND } from '../page-state/revision-backfill-schema.ts';
-import { isWriteTargetContained } from '../path-confine.ts';
+import { isWriteTargetContained, relativeEscapesRoot } from '../path-confine.ts';
import { recordedPathFromFileUri, scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';
import { absentCanonicalPath, findLiveFileClaimants, recordedReconcilePath, type FileClaimTarget } from './file-claims.ts';
import { wholeBodySnapshot } from './segmented-apply.ts';
@@ -109,7 +109,7 @@ export function canonicalDeletionState(root: string, path: string): 'in_head' |
if (!head.ok) return head.reason === 'exit' && head.status === 1 ? 'gone' : 'unknown';
let repoPath: string;
try { repoPath = relative(realpathSync(top.stdout.toString('utf8').trim()), absentCanonicalPath(path)).split(sep).join('/'); } catch { return 'unknown'; }
- if (!repoPath || repoPath.startsWith('..')) return 'unknown';
+ if (!repoPath || relativeEscapesRoot(repoPath)) return 'unknown';
const listed = hardenedGitSync(root, ['ls-tree', '-z', '--full-tree', 'HEAD', '--', repoPath], limits);
if (!listed.ok) return 'unknown';
return listed.stdout.toString('utf8').split('\0').some(entry => entry.split('\t')[1] === repoPath) ? 'in_head' : 'gone';
diff --git a/src/core/persistence/sync-markers.ts b/src/core/persistence/sync-markers.ts
index 8ba419b2cd..ad1c45d9ac 100644
--- a/src/core/persistence/sync-markers.ts
+++ b/src/core/persistence/sync-markers.ts
@@ -26,6 +26,7 @@ import { readSyncImportProvenance } from './sync-holds.ts';
import { syncOriginPath } from './sync-origin.ts';
import type { SyncDeleteCaps, SyncDeleteTrip } from '../sync-reconcile.ts';
import { SYNC_DELETES_WITHHELD_OP, SYNC_ORIGIN_DELETED_OP, passFingerprint } from './sync-pass-row.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
type Exec = Pick<BrainEngine, 'executeRaw'>;
@@ -66,7 +67,7 @@ function originGitPaths(root: string | null, slugMode: string | null, sourcePath
const gitRoot = toplevel.stdout.toString('utf8').trim();
let scope: string;
try { scope = relative(realpathSync.native(gitRoot), realpathSync.native(root)).split(sep).join('/'); } catch { return null; }
- if (scope.startsWith('..')) return null;
+ if (relativeEscapesRoot(scope)) return null;
const candidates = new Set<string>();
if (slugMode !== 'git-root') candidates.add(scope ? `${scope}/${sourcePath}` : sourcePath);
if (slugMode !== 'source-root' && (!scope || sourcePath.startsWith(`${scope}/`))) candidates.add(sourcePath);
diff --git a/src/core/setup/brain-first.ts b/src/core/setup/brain-first.ts
index af48135092..e734568e8f 100644
--- a/src/core/setup/brain-first.ts
+++ b/src/core/setup/brain-first.ts
@@ -22,7 +22,7 @@
*/
import { existsSync, lstatSync, readFileSync, unlinkSync } from 'node:fs';
import { homedir } from 'node:os';
-import { basename, dirname, isAbsolute, join, relative } from 'node:path';
+import { basename, dirname, join, relative } from 'node:path';
import { parse as parseJsonc, type ParseError } from 'jsonc-parser';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { acquireNativeLockSync } from '../persistence/native-lock.ts';
@@ -31,6 +31,7 @@ import { configDir } from '../config.ts';
import { probeBlock, removeBlock, spliceBlock, type BlockMarkers } from '../managed-block.ts';
import { ensureGitExcluded } from '../context/compiled-core.ts';
import type { McpSurface } from '../../mcp/surface.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
export const BRAIN_FIRST_VERSION = 2;
export const BRAIN_FIRST_BEGIN = '<!-- gbrain:brain-first:begin -->';
@@ -140,7 +141,7 @@ function projectRootOf(harness: string, path: string): string {
function isInside(cwd: string, root: string): boolean {
const rel = relative(root, cwd);
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+ return !relativeEscapesRoot(rel);
}
export const CURSOR_HEAD = '---\ndescription: GBrain memory, managed by gbrain\nalwaysApply: true\n---\n';
diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.ts
index 05d736bb92..43ca40246a 100644
--- a/src/core/skill-catalog.ts
+++ b/src/core/skill-catalog.ts
@@ -48,6 +48,7 @@ import {
type SkillsDirSource,
} from './repo-root.ts';
import { loadOrDeriveManifest, type ManifestEntry } from './skill-manifest.ts';
+import { relativeEscapesRoot } from './path-confine.ts';
import { loadSkillTriggerIndex, FRONTMATTER_SECTION } from './skill-trigger-index.ts';
import { parseSkillFrontmatter } from './skill-frontmatter.ts';
import { oneLineDescription } from './skill-description.ts';
@@ -287,7 +288,7 @@ export function confineManifestPath(skillsDir: string, entry: ManifestEntry): st
throw new OperationError('page_not_found', `Skill file not found: ${entry.name}`, `The skills manifest lists ${entry.name} but its SKILL.md is missing on the brain host. Call list_skills for the skills that are available; the host's operator restores the file or regenerates the manifest.`);
}
const rel = relative(realRoot, realCandidate);
- if (rel.startsWith('..') || resolve(realRoot, rel) !== realCandidate) {
+ if (relativeEscapesRoot(rel) || resolve(realRoot, rel) !== realCandidate) { // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rel comes from relative() of two realpaths; resolve only re-joins it to confirm containment, no file is opened here
throw new OperationError('invalid_params', `Skill path escapes skills dir: ${entry.name}`,
`The manifest entry for ${entry.name} points outside the skills directory, so it is refused. Pick another skill from list_skills; the brain host's operator fixes the manifest.`);
}
diff --git a/src/core/skillpack/brain-resident-locate.ts b/src/core/skillpack/brain-resident-locate.ts
index 877e2ed837..b43958bd35 100644
--- a/src/core/skillpack/brain-resident-locate.ts
+++ b/src/core/skillpack/brain-resident-locate.ts
@@ -27,6 +27,7 @@ import type { BrainEngine } from '../engine.ts';
import { opError, type OperationContext } from '../operations.ts';
import { sourceScopeOpts } from '../operations.ts';
import { hostFix, readFix } from '../ops/op-fix.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
export interface ResidentPackSkill {
/** Skill name, as get_skill takes it. Never `slug`: page slugs and skill
@@ -253,7 +254,7 @@ export async function getResidentSkillDetail(
`Pack ${manifest.name} lists skill ${name}, but its SKILL.md is missing on the brain host. Tell the user the pack is incomplete so its maintainer can add the file.`);
}
const rel = relative(realRoot, realFile);
- if (rel.startsWith('..') || resolve(realRoot, rel) !== realFile) {
+ if (relativeEscapesRoot(rel) || resolve(realRoot, rel) !== realFile) { // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- rel comes from relative() of two realpaths; resolve only re-joins it to confirm containment, no file is opened here
throw opError('storage_error', 'Skill path escaped the pack root.',
`Skill ${name} in source ${sourceId} resolves outside its pack root (a symlink or '..'), so it was refused. Do not retry; tell the user so the pack's maintainer replaces it with a regular file inside the pack.`);
}
diff --git a/src/core/skillpack/safe-update.ts b/src/core/skillpack/safe-update.ts
index ef73c53bb5..9b75b99d89 100644
--- a/src/core/skillpack/safe-update.ts
+++ b/src/core/skillpack/safe-update.ts
@@ -41,6 +41,7 @@ import { loadSkillTriggerIndex } from '../skill-trigger-index.ts';
import { checkResolvable, type ResolvableIssue } from '../check-resolvable.ts';
import { OperationError } from '../ops/contract.ts';
import { confinedSkillChildWrite } from './writer-guard.ts';
+import { relativeEscapesRoot } from '../path-confine.ts';
import {
backupFile, backupsRoot, hashTarget, newJournalId, pendingJournals, planRestore, pruneJournals, readJournal, sha256, undoFile, writeJournal,
type Journal, type JournalFile, type JournalSkill, type RestorePlanFile,
@@ -515,7 +516,7 @@ export async function recordScaffoldBases(skillsRoot: string, files: readonly Sc
for (const f of files) {
if (f.sharedDep || f.pairedSource || (!f.source && f.outcome !== 'wrote_new')) continue;
const rel = relative(root, skillsRootKey(f.target)).split(sep).join('/');
- if (!rel || rel.startsWith('..') || !rel.includes('/')) continue;
+ if (!rel || relativeEscapesRoot(rel) || !rel.includes('/')) continue;
const current = hashTarget(f.target);
const expected = f.source ? sha256(readFileSync(f.source)) : current;
if (current === null || current !== expected) continue;
diff --git a/src/core/sync-applicability.ts b/src/core/sync-applicability.ts
index 82cd0af16c..354a1a892b 100644
--- a/src/core/sync-applicability.ts
+++ b/src/core/sync-applicability.ts
@@ -15,13 +15,13 @@
* whatever directory gbrain runs from.
*/
import { existsSync, realpathSync } from 'node:fs';
-import { isAbsolute, join, relative, resolve } from 'node:path';
+import { join, relative, resolve } from 'node:path';
import type { BrainEngine } from './engine.ts';
import { gbrainPath, loadConfig } from './config.ts';
import { opError, type OperationError } from './ops/contract.ts';
import { readSyncAnchor } from './sync-anchor.ts';
import { contentSetupKey } from './shared-skills/setup.ts';
-import { isForeignAbsolutePath, isHostAbsolutePath } from './path-confine.ts';
+import { isForeignAbsolutePath, isHostAbsolutePath, relativeEscapesRoot } from './path-confine.ts';
/** A source whose sync root is a gbrain-owned content directory with no Git checkout. */
export interface SyncContentDirectory {
@@ -38,7 +38,7 @@ function canonical(path: string): string {
function underGbrainContent(root: string): boolean {
const rel = relative(canonical(gbrainPath('content')), canonical(root));
- return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
+ return rel !== '' && !relativeEscapesRoot(rel);
}
async function ownedByContentReceipt(engine: BrainEngine, sourceId: string, root: string): Promise<boolean> {
diff --git a/src/eval/longmemeval/call-plan.ts b/src/eval/longmemeval/call-plan.ts
index 0d5be3e027..422ad96cf8 100644
--- a/src/eval/longmemeval/call-plan.ts
+++ b/src/eval/longmemeval/call-plan.ts
@@ -27,7 +27,7 @@
import { createHash } from 'node:crypto';
import { execFileSync } from '../../core/spawn.ts';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
-import { basename, isAbsolute, relative, resolve } from 'node:path';
+import { basename, relative, resolve } from 'node:path';
import { haystackToPages } from './adapter.ts';
import { EXTRACTOR_MAX_TOKENS, EXTRACTOR_SYSTEM_PROMPT } from './extract.ts';
import { buildJudgePrompt, JUDGE_MAX_TOKENS } from './judge.ts';
@@ -63,6 +63,7 @@ import { INJECTION_PATTERNS } from '../../core/think/sanitize.ts';
import { formatTrajectoryBlock } from '../../core/trajectory-format.ts';
import type { ThinkLLMClient } from '../../core/think/index.ts';
import type { ChunkInput } from '../../core/types.ts';
+import { relativeEscapesRoot } from '../../core/path-confine.ts';
/** The ONE token rule: no provider tokenizer exists in the repo, so every lane counts `ceil(chars / 3)`. */
export const CALL_PLAN_CHARS_PER_TOKEN = 3;
@@ -165,11 +166,11 @@ function envState(names: string[]): string {
return names.map(n => `${n} ${process.env[n]?.trim() ? 'set' : 'unset'}`).join(', ');
}
-/** An INPUT line for a tracked, unmodified repo file; otherwise a PRECONDITION with its sha256 and basename. */
-function bindInput(root: string, path: string, label: string, plan: CallPlan): void {
+/** An INPUT line for a tracked, unmodified repo file; otherwise a PRECONDITION with its sha256 and basename. Exported for tests. */
+export function bindInput(root: string, path: string, label: string, plan: CallPlan): void {
const abs = resolve(path);
const rel = relative(root, abs);
- if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
+ if (rel && !relativeEscapesRoot(rel)) {
try {
git(root, ['ls-files', '--error-unmatch', '--', rel]);
git(root, ['diff', '--quiet', 'HEAD', '--', rel]);
diff --git a/test/brain-repo-durability-dotdot-folder-names.test.ts b/test/brain-repo-durability-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..906332e91c
--- /dev/null
+++ b/test/brain-repo-durability-dotdot-folder-names.test.ts
@@ -0,0 +1,124 @@
+/**
+ * A folder whose name merely starts with two dots (`..drafts`, `..x`) is a normal folder in a brain checkout. Three checks
+ * in brain-repo-durability used `relative(a, b).startsWith('..')` for "outside", which also matches that folder:
+ * - resolveHooksDir called a `core.hooksPath` of `..hooks` (inside the working tree) "not tracked", so `gbrain sources
+ * harden` installed its hook there without adding it to .git/info/exclude (it then shows up as an untracked file);
+ * - commitWriteThroughFile returned false for a page file under `..drafts/`, so the write was never committed;
+ * - recordSourceRoot skipped a source folder named `..x`, so the checkout kept the whole repo as its source root.
+ * Slug validation lets these through: validateSlug only refuses a whole `..` path component, not `..drafts`.
+ * Protects: such a folder is handled like any other, while a hooks dir outside the checkout, a sibling sharing the checkout's
+ * name prefix, a path that leaves the checkout and a symlinked parent that points outside stay refused or unrecorded.
+ * Authoring gate: (1) where the harden hook is excluded, whether a write-through file is committed and which source root is
+ * recorded; (2) a startsWith('..') check that is not component-aware; (3) the durability tests only use ordinary folder
+ * names; (4) no seam, real temp git repositories through hardenBrainRepo and the exported helpers.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { commitWriteThroughFile, hardenBrainRepo, resolveHooksDir } from '../src/core/brain-repo-durability.ts';
+import { validateSlug } from '../src/core/utils.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const cfgAll = (cwd: string, key: string) => { try { return git(cwd, 'config', '--local', '--get-all', key).split('\n'); } catch { return []; } };
+
+let root: string;
+let work: string;
+let home: string;
+beforeEach(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-dotdot-durable-')));
+ home = join(root, 'home');
+ mkdirSync(home);
+ work = join(root, 'work');
+ execFileSync('git', ['init', '-q', '-b', 'main', work]);
+ git(work, 'config', 'user.name', 'Example Writer'); git(work, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(work, 'README.md'), 'init\n');
+ git(work, 'add', '.'); git(work, 'commit', '-qm', 'init');
+ for (const sibling of ['work2', 'outside']) { mkdirSync(join(root, sibling)); writeFileSync(join(root, sibling, 'a.md'), `${sibling}\n`); }
+});
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+/** Harden without the push-probe: no remote is needed and no scaffolding commit fires the new hook. HOME and GBRAIN_HOME stay under the temp dir. */
+const harden = (repoPath: string) => withEnv({ HOME: home, GBRAIN_HOME: home }, () =>
+ hardenBrainRepo({ repoPath, sourceId: 'wiki', installCron: false, verify: false }));
+const status = (path: string) => git(work, 'status', '--porcelain', '--untracked-files=all', '--', path);
+
+describe('resolveHooksDir and harden treat a hooks dir named ..hooks as inside the checkout', () => {
+ test('core.hooksPath=..hooks is a tracked location, so the hook is excluded and stays out of git status', async () => {
+ git(work, 'config', 'core.hooksPath', '..hooks');
+ expect(resolveHooksDir(work)).toEqual({ dir: join(work, '..hooks'), tracked: true });
+ await harden(work);
+ expect(existsSync(join(work, '..hooks', 'post-commit'))).toBe(true);
+ expect(readFileSync(join(work, '.git', 'info', 'exclude'), 'utf8')).toContain('..hooks/post-commit');
+ expect(status('..hooks/post-commit')).toBe('');
+ });
+
+ test('a hooks dir outside the checkout, a name-prefix sibling, ../hooks and the git dir are not tracked locations', () => {
+ for (const hooksPath of [join(root, 'outside'), join(root, 'work2', 'hooks'), '../outside', '../work2/hooks', '../work2', '.git/hooks']) {
+ git(work, 'config', 'core.hooksPath', hooksPath);
+ expect(`${hooksPath}: ${resolveHooksDir(work).tracked}`).toBe(`${hooksPath}: false`);
+ }
+ });
+});
+
+describe('commitWriteThroughFile commits a page file under a folder named ..drafts', () => {
+ test('the slug passes validation and the file is committed by itself', () => {
+ expect(validateSlug('..drafts/a')).toBe('..drafts/a');
+ mkdirSync(join(work, '..drafts'));
+ writeFileSync(join(work, '..drafts', 'a.md'), 'draft\n');
+ writeFileSync(join(work, 'stray.md'), 'another writer\n');
+ expect(commitWriteThroughFile(work, join(work, '..drafts', 'a.md'), '..drafts/a')).toBe(true);
+ expect(git(work, 'show', '--name-only', '--format=', 'HEAD')).toBe('..drafts/a.md');
+ expect(git(work, 'status', '--porcelain')).toBe('?? stray.md');
+ });
+
+ test('files that are not inside the checkout are refused: ../x, an outside directory, a name-prefix sibling, the checkout itself, a symlinked parent', () => {
+ symlinkSync(join(root, 'outside'), join(work, 'linked'));
+ const head = git(work, 'rev-parse', 'HEAD');
+ for (const path of [join(work, '..', 'outside', 'a.md'), join(root, 'outside', 'a.md'), join(root, 'work2', 'a.md'), work, join(work, 'linked', 'a.md')]) {
+ expect(`${path}: ${commitWriteThroughFile(work, path, 'x')}`).toBe(`${path}: false`);
+ }
+ expect(git(work, 'rev-parse', 'HEAD')).toBe(head);
+ expect(readFileSync(join(root, 'outside', 'a.md'), 'utf8')).toBe('outside\n');
+ });
+});
+
+describe('hardenBrainRepo records a source folder named ..x as the checkout source root', () => {
+ const SOURCE_ROOT = 'gbrain.sourceRoot';
+
+ test('a source path of <checkout>/..x is recorded as gbrain.sourceRoot', async () => {
+ mkdirSync(join(work, '..x'));
+ writeFileSync(join(work, '..x', 'note.md'), '# note\n');
+ git(work, 'add', '.'); git(work, 'commit', '-qm', 'source folder');
+ const report = await harden(join(work, '..x'));
+ expect(report.repo_path).toBe(work);
+ expect(cfgAll(work, SOURCE_ROOT)).toEqual(['..x']);
+ });
+
+ test('an ordinary source folder is recorded and a source at the checkout root records nothing (control)', async () => {
+ mkdirSync(join(work, 'brain'));
+ writeFileSync(join(work, 'brain', 'note.md'), '# note\n');
+ git(work, 'add', '.'); git(work, 'commit', '-qm', 'source folder');
+ await harden(join(work, 'brain'));
+ expect(cfgAll(work, SOURCE_ROOT)).toEqual(['brain']);
+ const other = join(root, 'other');
+ execFileSync('git', ['init', '-q', '-b', 'main', other]);
+ git(other, 'config', 'user.name', 'Example Writer'); git(other, 'config', 'user.email', '[email protected]');
+ writeFileSync(join(other, 'README.md'), 'x\n'); git(other, 'add', '.'); git(other, 'commit', '-qm', 'init');
+ await harden(other);
+ expect(cfgAll(other, SOURCE_ROOT)).toEqual([]);
+ });
+
+ test('a source path that is a symlink out of the checkout hardens the repo it points to and never records a ../ root', async () => {
+ symlinkSync(join(root, 'outside'), join(work, 'linked'));
+ execFileSync('git', ['init', '-q', '-b', 'main', join(root, 'outside')]);
+ git(join(root, 'outside'), 'config', 'user.name', 'Example Writer'); git(join(root, 'outside'), 'config', 'user.email', '[email protected]');
+ git(join(root, 'outside'), 'add', '.'); git(join(root, 'outside'), 'commit', '-qm', 'init');
+ const report = await harden(join(work, 'linked'));
+ expect(report.repo_path).toBe(join(root, 'outside'));
+ expect(cfgAll(work, SOURCE_ROOT)).toEqual([]);
+ expect(cfgAll(join(root, 'outside'), SOURCE_ROOT)).toEqual([]);
+ });
+});
diff --git a/test/brain-writer-backup-dotdot-folder.test.ts b/test/brain-writer-backup-dotdot-folder.test.ts
new file mode 100644
index 0000000000..0c015f86a1
--- /dev/null
+++ b/test/brain-writer-backup-dotdot-folder.test.ts
@@ -0,0 +1,88 @@
+/**
+ * createFrontmatterBackup (src/core/brain-writer.ts) keeps a file's folder
+ * path under the backup root, so two same-named files in different folders
+ * never share one backup, including when the first folder is named `..drafts`.
+ *
+ * Authoring gate:
+ * 1. Protects: backing up `<source>/..drafts/note.md` and
+ * `<source>/..more/note.md` writes two different backup files, each with its
+ * own original bytes (a backup is the undo for `frontmatter validate --fix`);
+ * a file outside the source folder still falls back to its bare file name.
+ * 2. Regression that fails it: the "outside the source" test matching any
+ * relative path that starts with the two characters `..` instead of only a
+ * `..` path component. Both backups then land on `note.md.bak` and the
+ * second silently overwrites the first.
+ * 3. Why existing coverage misses it: brain-writer.test.ts and
+ * frontmatter-fix-slug-5053.test.ts back up files in ordinary folders only.
+ * 4. Production seam: none. createFrontmatterBackup is exported; the backup
+ * root is passed in, so nothing is written under GBRAIN_HOME.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, relative } from 'path';
+
+import { createFrontmatterBackup } from '../src/core/brain-writer.ts';
+
+let scratch: string;
+let source: string;
+let backups: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-backup-dotdot-'));
+ source = join(scratch, 'brain');
+ backups = join(scratch, 'backups');
+ mkdirSync(source, { recursive: true });
+});
+afterEach(() => {
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+function writeNote(dir: string, body: string): string {
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, 'note.md');
+ writeFileSync(file, body);
+ return file;
+}
+
+describe('createFrontmatterBackup with a first folder whose name starts with two dots', () => {
+ test('keeps the folder path under the backup root', () => {
+ const file = writeNote(join(source, '..drafts'), 'draft body\n');
+ const backup = createFrontmatterBackup(file, { sourcePath: source, backupRoot: backups });
+ expect(relative(backups, backup).split('/').slice(1).join('/')).toBe('..drafts/note.md.bak');
+ expect(readFileSync(backup, 'utf8')).toBe('draft body\n');
+ });
+
+ test('two same-named files in different ..folders get two separate backups', () => {
+ const a = writeNote(join(source, '..drafts'), 'draft body\n');
+ const b = writeNote(join(source, '..more'), 'more body\n');
+ const backupA = createFrontmatterBackup(a, { sourcePath: source, backupRoot: backups });
+ const backupB = createFrontmatterBackup(b, { sourcePath: source, backupRoot: backups });
+ expect(backupA).not.toBe(backupB);
+ expect(readFileSync(backupA, 'utf8')).toBe('draft body\n');
+ expect(readFileSync(backupB, 'utf8')).toBe('more body\n');
+ });
+});
+
+describe('createFrontmatterBackup still files an outside file under its bare name', () => {
+ test('a file in a plain folder beside the source folder', () => {
+ const file = writeNote(join(scratch, 'elsewhere'), 'x\n');
+ const backup = createFrontmatterBackup(file, { sourcePath: source, backupRoot: backups });
+ expect(backup.endsWith('/note.md.bak')).toBe(true);
+ expect(relative(backups, backup).split('/')).toHaveLength(2);
+ });
+
+ test('a file in a sibling folder that shares the source folder name prefix', () => {
+ const file = writeNote(join(scratch, 'brain2'), 'x\n');
+ const backup = createFrontmatterBackup(file, { sourcePath: source, backupRoot: backups });
+ expect(relative(backups, backup).split('/')).toHaveLength(2);
+ expect(backup.endsWith('/note.md.bak')).toBe(true);
+ });
+
+ test('a file in a ..outside folder beside the source folder', () => {
+ const file = writeNote(join(scratch, '..outside'), 'x\n');
+ const backup = createFrontmatterBackup(file, { sourcePath: source, backupRoot: backups });
+ expect(relative(backups, backup).split('/')).toHaveLength(2);
+ expect(backup.endsWith('/note.md.bak')).toBe(true);
+ });
+});
diff --git a/test/check-relative-dotdot.test.ts b/test/check-relative-dotdot.test.ts
new file mode 100644
index 0000000000..27835838f8
--- /dev/null
+++ b/test/check-relative-dotdot.test.ts
@@ -0,0 +1,47 @@
+/**
+ * Self-test for scripts/check-relative-dotdot.mjs, the guard against
+ * `.startsWith('..')` containment checks (a legal folder such as `..drafts`
+ * also matches that prefix).
+ *
+ * Runs the scanner against the committed fixtures at
+ * test/fixtures/guards/check-relative-dotdot.mjs/{bad,bad-double-quote,good}/
+ * (the same fixtures guard-self-test.sh exercises) and against the real src/.
+ */
+import { describe, test, expect } from 'bun:test';
+import { join } from 'node:path';
+
+const SCRIPT = join(import.meta.dir, '..', 'scripts', 'check-relative-dotdot.mjs');
+const FIXTURES = join(import.meta.dir, 'fixtures', 'guards', 'check-relative-dotdot.mjs');
+
+function runGuard(dir?: string): { code: number; out: string } {
+ const args = dir ? [process.execPath, SCRIPT, dir] : [process.execPath, SCRIPT];
+ const res = Bun.spawnSync(args, { cwd: join(import.meta.dir, '..') });
+ return { code: res.exitCode, out: res.stderr.toString() + res.stdout.toString() };
+}
+
+describe('check-relative-dotdot guard', () => {
+ test('flags a single-quoted prefix check and names the helper', () => {
+ const { code, out } = runGuard(join(FIXTURES, 'bad'));
+ expect(code).toBe(1);
+ expect(out).toContain('fixture.ts:5');
+ expect(out).toContain('relativeEscapesRoot');
+ });
+
+ test('flags a double-quoted prefix check', () => {
+ const { code, out } = runGuard(join(FIXTURES, 'bad-double-quote'));
+ expect(code).toBe(1);
+ expect(out).toContain('fixture.ts:3');
+ });
+
+ test('passes the helper, component-aware prefixes, comments and an opt-out', () => {
+ const { code, out } = runGuard(join(FIXTURES, 'good'));
+ expect(code).toBe(0);
+ expect(out).toContain('OK');
+ });
+
+ test('the real src/ tree is clean', () => {
+ const { code, out } = runGuard();
+ expect(code).toBe(0);
+ expect(out).toContain('OK');
+ }, 30_000);
+});
diff --git a/test/doctor-foreign-writers-dotdot-folder-names.test.ts b/test/doctor-foreign-writers-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..ef7691f5ed
--- /dev/null
+++ b/test/doctor-foreign-writers-dotdot-folder-names.test.ts
@@ -0,0 +1,58 @@
+/**
+ * Doctor `foreign_writers` scans the dirty page files under each source root. It recorded a source root as the whole
+ * checkout whenever `relative(checkoutTop, sourceRoot)` started with `..`, which also matches a source folder named
+ * `..x`, so for such a source every old dirty file anywhere in the checkout was reported as a page file waiting.
+ * Protects: a source folder named `..x` scopes the scan to that folder (a file in `..xy`, a sibling folder that shares
+ * the name prefix, or at the checkout root is not reported), the same as a folder named `notes`.
+ * Authoring gate: (1) which dirty files doctor reports for a source; (2) a startsWith('..') check that is not
+ * component-aware; (3) doctor-foreign-writers.test.ts only registers a source folder named `notes`; (4) no seam, the
+ * real doctor entry on in-memory PGLite and real git repositories. A source root outside its checkout cannot be
+ * registered here (the checkout is found from the root itself), so that escape case has no test.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { foreignWritersEntry } from '../src/commands/doctor/checks/foreign-writers.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-foreign-dotdot-')));
+const ID = { GIT_AUTHOR_NAME: 'Example Writer', GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Example Writer', GIT_COMMITTER_EMAIL: '[email protected]' };
+const git = (cwd: string, args: string[]) => execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...ID } }).toString().trim();
+const write = (root: string, rel: string, body: string) => { mkdirSync(dirname(join(root, rel)), { recursive: true }); writeFileSync(join(root, rel), body); };
+const OLD = (Date.now() - 2 * 3_600_000) / 1000;
+const age = (root: string, rel: string) => utimesSync(join(root, rel), OLD, OLD);
+let n = 0;
+
+/** A checkout with an upstream and committed seed files in `<folder>`, `<folder>y` (shares the name prefix) and at the root. */
+function checkout(folder: string): string {
+ const bare = join(dir, `origin-${n}.git`), work = join(dir, `work-${n++}`);
+ git(dir, ['init', '-q', '--bare', '-b', 'main', bare]);
+ git(dir, ['clone', '-q', bare, work]);
+ git(work, ['config', 'commit.gpgsign', 'false']);
+ for (const path of [`${folder}/seed.md`, `${folder}y/seed.md`, 'seed.md']) write(work, path, 'seed\n');
+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'seed']); git(work, ['push', '-q', '-u', 'origin', 'main']);
+ return work;
+}
+const run = async (): Promise<Check> => ((await foreignWritersEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext)) as Check[])[0]!;
+const dirtyPaths = (check: Check) => (check.details!.dirty as Array<{ path: string }>).map(d => d.path).sort();
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });
+afterAll(async () => { await engine.disconnect(); rmSync(dir, { recursive: true, force: true }); });
+beforeEach(async () => { await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'"); });
+
+for (const folder of ['..x', 'notes']) {
+ test(`a source folder named ${folder} limits the dirty-file scan to that folder`, async () => {
+ const work = checkout(folder);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source', join(work, folder)]);
+ for (const path of [`${folder}/stray.md`, `${folder}y/stray.md`, 'stray.md']) { write(work, path, 'stray\n'); age(work, path); }
+ const check = await run();
+ expect(check.status).toBe('warn');
+ expect(dirtyPaths(check)).toEqual([`${folder}/stray.md`]);
+ expect(check.details!.dirty_count).toBe(1);
+ }, 60_000);
+}
diff --git a/test/doctor-git-writer-dotdot-folder-names.test.ts b/test/doctor-git-writer-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..4930d495f0
--- /dev/null
+++ b/test/doctor-git-writer-dotdot-folder-names.test.ts
@@ -0,0 +1,64 @@
+/**
+ * Doctor `commits_outside_source_root` compares unpushed commits with the source roots of a checkout. It recorded a
+ * source root as the whole checkout whenever `relative(checkoutTop, sourceRoot)` started with `..`, which also matches a
+ * source folder named `..x`, so a local commit that changed files outside that folder was never reported.
+ * Protects: a source folder named `..x` is the root, so a commit that changed `other.md` or a sibling folder `..xy`
+ * (shares the name prefix) is reported as outside it, while a commit only inside `..x` is not, as with a folder named `notes`.
+ * Authoring gate: (1) which unpushed commits doctor reports as outside the source root; (2) a startsWith('..') check that
+ * is not component-aware; (3) doctor-git-writer-7381.test.ts only registers a source folder named `brain`; (4) no seam,
+ * the real doctor entry on in-memory PGLite and real git repositories with a bare upstream. A source root outside its
+ * checkout cannot be registered here (the checkout is found from the root itself), so that escape case has no test.
+ */
+import { afterAll, beforeAll, beforeEach, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { gitWriterEntry } from '../src/commands/doctor/checks/git-writer.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-git-writer-dotdot-')));
+const git = (cwd: string, args: string[]) => execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
+const write = (root: string, rel: string, body: string) => { mkdirSync(dirname(join(root, rel)), { recursive: true }); writeFileSync(join(root, rel), body); };
+let n = 0;
+
+/** A checkout with an upstream and committed seed files in `<folder>`, `<folder>y` (shares the name prefix) and at the root. */
+function checkout(folder: string): string {
+ const bare = join(dir, `origin-${n}.git`), work = join(dir, `work-${n++}`);
+ git(dir, ['init', '-q', '--bare', '-b', 'main', bare]);
+ git(dir, ['clone', '-q', bare, work]);
+ git(work, ['config', 'user.email', '[email protected]']); git(work, ['config', 'user.name', 'Example Writer']); git(work, ['config', 'commit.gpgsign', 'false']);
+ for (const path of [`${folder}/seed.md`, `${folder}y/seed.md`, 'other.md']) write(work, path, 'seed\n');
+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'seed']); git(work, ['push', '-q', '-u', 'origin', 'main']);
+ return work;
+}
+const outside = async (): Promise<Check> => {
+ const checks = (await gitWriterEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext)) as Check[];
+ return checks.find(c => c.name === 'commits_outside_source_root')!;
+};
+type Found = { roots: string[]; commits: Array<{ paths: string[] }> };
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });
+afterAll(async () => { await engine.disconnect(); rmSync(dir, { recursive: true, force: true }); });
+beforeEach(async () => { await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'"); });
+
+for (const folder of ['..x', 'notes']) {
+ test(`a source folder named ${folder}: an unpushed commit outside it is reported, one inside it is not`, async () => {
+ const work = checkout(folder);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source', join(work, folder)]);
+ write(work, `${folder}/seed.md`, 'edited inside the source root\n');
+ git(work, ['commit', '-q', '-am', 'inside the source root']);
+ expect((await outside()).status).toBe('ok');
+
+ write(work, 'other.md', 'swept\n'); write(work, `${folder}y/seed.md`, 'swept too\n');
+ git(work, ['commit', '-q', '-am', 'cron: swept']);
+ const check = await outside();
+ expect(check.status).toBe('warn');
+ const [found] = (check.details as { checkouts: Found[] }).checkouts;
+ expect(found!.roots).toEqual([folder]);
+ expect(found!.commits.map(c => [...c.paths].sort())).toEqual([[`${folder}y/seed.md`, 'other.md'].sort()]);
+ }, 60_000);
+}
diff --git a/test/eval-longmemeval-call-plan-dotdot-folder.test.ts b/test/eval-longmemeval-call-plan-dotdot-folder.test.ts
new file mode 100644
index 0000000000..38170de3b7
--- /dev/null
+++ b/test/eval-longmemeval-call-plan-dotdot-folder.test.ts
@@ -0,0 +1,84 @@
+/**
+ * `bindInput` (src/eval/longmemeval/call-plan.ts) decides whether a dataset, question-ID or replay file the caller
+ * names is pinned to HEAD as an INPUT line of the call plan, or recorded as a PRECONDITION with its bytes' sha256.
+ * Protects: a tracked, unmodified file in a first folder named `..inputs` binds as an INPUT line with its repo path,
+ * while a modified file there, an untracked file there, a file outside the repository and a file in a sibling folder
+ * that shares the repository's name prefix stay PRECONDITIONs.
+ * Authoring gate: (1) whether a tracked input is pinned to the commit or left as an unpinned precondition; (2) a
+ * startsWith('..') check that is not component-aware treats `..inputs/questions.jsonl` as outside the repository;
+ * (3) eval-longmemeval-call-plan.test.ts binds only test/fixtures/longmemeval-mini.jsonl, whose first folder is
+ * `test`; (4) seam: `bindInput` is exported for this test. The command boundary binds against the gbrain checkout
+ * that runs it, which has no committed `..inputs` folder, so the boundary cannot reach this case; the test drives the
+ * exported function on a real temporary Git repository instead.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { bindInput, type CallPlan } from '../src/eval/longmemeval/call-plan.ts';
+import { gitChildEnv } from '../src/core/git-env.ts';
+
+const env = gitChildEnv();
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env }).trim();
+const dirs: string[] = [];
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+function put(root: string, path: string, body: string): string {
+ const abs = join(root, path);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, body);
+ return abs;
+}
+
+/** `<dir>/repo` with `..inputs/questions.jsonl` and `data/plain.jsonl` committed; `<dir>/repo2` is a name-prefix sibling. */
+function repo(): { dir: string; root: string } {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-lme-dotdot-')));
+ dirs.push(dir);
+ const root = join(dir, 'repo');
+ git(dir, 'init', '-q', '-b', 'main', root);
+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'core.hooksPath', join(dir, 'hooks'));
+ put(root, '..inputs/questions.jsonl', '{"question_id":"q1"}\n');
+ put(root, 'data/plain.jsonl', '{"question_id":"q2"}\n');
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');
+ return { dir, root };
+}
+
+const emptyPlan = (): CallPlan => ({ gate: 'gate', head: 'head', inputs: [], preconditions: [], rows: [] });
+const sha = (body: string) => createHash('sha256').update(body).digest('hex');
+
+describe('call plan input binding with a first folder named ..inputs', () => {
+ test('a tracked, unmodified ..inputs file binds as an INPUT line', () => {
+ const { root } = repo();
+ const plan = emptyPlan();
+ bindInput(root, join(root, '..inputs', 'questions.jsonl'), 'dataset', plan);
+ expect(plan.inputs).toEqual([{ path: '..inputs/questions.jsonl', sha256: sha('{"question_id":"q1"}\n') }]);
+ expect(plan.preconditions).toEqual([]);
+ });
+
+ test('a tracked file in an ordinary folder binds the same way (control)', () => {
+ const { root } = repo();
+ const plan = emptyPlan();
+ bindInput(root, join(root, 'data', 'plain.jsonl'), 'dataset', plan);
+ expect(plan.inputs.map(i => i.path)).toEqual(['data/plain.jsonl']);
+ });
+
+ test('modified, untracked, outside and name-prefix sibling files stay PRECONDITIONs', () => {
+ const { dir, root } = repo();
+ put(root, '..inputs/questions.jsonl', '{"question_id":"changed"}\n');
+ const files = [
+ join(root, '..inputs', 'questions.jsonl'),
+ put(root, '..inputs/untracked.jsonl', 'u\n'),
+ put(dir, 'outside/q.jsonl', 'o\n'),
+ put(dir, 'repo2/q.jsonl', 's\n'),
+ join(root, '..', 'outside', 'q.jsonl'),
+ ];
+ const plan = emptyPlan();
+ for (const f of files) bindInput(root, f, 'dataset', plan);
+ expect(plan.inputs).toEqual([]);
+ expect(plan.preconditions).toHaveLength(files.length);
+ expect(plan.preconditions[0]).toContain(`dataset questions.jsonl sha256=${sha('{"question_id":"changed"}\n')} is not a tracked unmodified file`);
+ });
+});
diff --git a/test/extract-atoms-transcript-root-dotdot-folder.test.ts b/test/extract-atoms-transcript-root-dotdot-folder.test.ts
new file mode 100644
index 0000000000..ad573e9990
--- /dev/null
+++ b/test/extract-atoms-transcript-root-dotdot-folder.test.ts
@@ -0,0 +1,71 @@
+/**
+ * transcriptRoot (src/core/cycle/extract-atoms-generation.ts) says which
+ * corpus root a transcript lies under, and that label becomes part of the
+ * transcript's generation key. A transcript in a `..drafts` folder under the
+ * meetings root must be labelled `meetings`.
+ *
+ * Authoring gate:
+ * 1. Protects: a transcript at `<meetings>/..drafts/t.md` keeps the key
+ * `meetings/..drafts/t.md`; a transcript outside the meetings root (a plain
+ * folder, a `..` path that leaves it, or a sibling folder that shares the
+ * meetings root's name prefix) is still labelled `corpus`.
+ * 2. Regression that fails it: the "inside the meetings root" test matching
+ * any relative path that starts with the two characters `..` instead of only
+ * a `..` path component. The transcript is then keyed `corpus/meetings/...`,
+ * so a run before and after the change would see it as a new, moved page.
+ * 3. Why existing coverage misses it: no test calls transcriptRoot; the
+ * extract-atoms suites use transcripts directly under the roots. Corpus
+ * discovery prunes dot-folders, so production reaches this only through a
+ * transcript named explicitly (synthesize --input).
+ * 4. Production seam: none. transcriptRoot and resolveTranscriptKeys are
+ * already exported; resolveTranscriptKeys gets a stub engine that holds no
+ * live generations.
+ */
+import { describe, expect, test } from 'bun:test';
+import { join } from 'node:path';
+
+import { resolveTranscriptKeys, transcriptRoot } from '../src/core/cycle/extract-atoms-generation.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+
+const CORPUS = '/work/corpus';
+const MEETINGS = join(CORPUS, 'meetings');
+
+describe('transcriptRoot with a transcript in a folder whose name starts with two dots', () => {
+ test('a transcript under meetings/..drafts is labelled meetings', () => {
+ expect(transcriptRoot(join(MEETINGS, '..drafts', 't.md'), CORPUS, MEETINGS)).toEqual({ path: MEETINGS, label: 'meetings' });
+ });
+
+ test('a transcript in a ..drafts folder directly under the corpus root is labelled corpus', () => {
+ expect(transcriptRoot(join(CORPUS, '..drafts', 't.md'), CORPUS, MEETINGS)).toEqual({ path: CORPUS, label: 'corpus' });
+ });
+
+ test('the generation key of a meetings/..drafts transcript keeps the meetings label and its folder', async () => {
+ const file = join(MEETINGS, '..drafts', 't.md');
+ const engine = { executeRaw: async () => [] } as unknown as BrainEngine;
+ const keys = await resolveTranscriptKeys(engine, 'default',
+ [{ filePath: file, contentHash: 'h1', root: transcriptRoot(file, CORPUS, MEETINGS) }], true);
+ expect(keys.get(file)).toBe('meetings/..drafts/t.md');
+ });
+});
+
+describe('transcriptRoot still labels a transcript outside the meetings root as corpus', () => {
+ test('a transcript directly under the meetings root is labelled meetings', () => {
+ expect(transcriptRoot(join(MEETINGS, 't.md'), CORPUS, MEETINGS).label).toBe('meetings');
+ });
+
+ test('a transcript in a plain folder beside the meetings root is labelled corpus', () => {
+ expect(transcriptRoot(join(CORPUS, 'notes', 't.md'), CORPUS, MEETINGS).label).toBe('corpus');
+ });
+
+ test('a transcript in a sibling folder that shares the meetings root name prefix is labelled corpus', () => {
+ expect(transcriptRoot(join(CORPUS, 'meetings2', 't.md'), CORPUS, MEETINGS).label).toBe('corpus');
+ });
+
+ test('a path that climbs out of the meetings root with .. is labelled corpus', () => {
+ expect(transcriptRoot(join(MEETINGS, '..', 't.md'), CORPUS, MEETINGS).label).toBe('corpus');
+ });
+
+ test('with no meetings root every transcript is labelled corpus', () => {
+ expect(transcriptRoot(join(CORPUS, '..drafts', 't.md'), CORPUS, undefined).label).toBe('corpus');
+ });
+});
diff --git a/test/extract/benchmark-dotdot-folder.test.ts b/test/extract/benchmark-dotdot-folder.test.ts
new file mode 100644
index 0000000000..43d3d62366
--- /dev/null
+++ b/test/extract/benchmark-dotdot-folder.test.ts
@@ -0,0 +1,88 @@
+/**
+ * validateFixturePath (src/commands/extract-benchmark.ts) accepts a fixture
+ * under a pack folder named `..drafts`, and still refuses a fixture that
+ * leaves the pack root.
+ *
+ * Authoring gate:
+ * 1. Protects: a pack manifest may point `extractable.fixture_corpus` at a
+ * file inside a folder whose name starts with two dots (directly, or
+ * through an in-pack symlinked folder); a manifest path that leaves the pack
+ * (a `../` segment, a symlinked folder to an outside dir, or to a sibling
+ * folder that shares the pack root's name prefix) is still refused.
+ * 2. Regression that fails it: either of the two containment checks treating
+ * any relative path that starts with the two characters `..` as "outside"
+ * instead of only a `..` path component; or loosening them so an outside
+ * realpath is accepted.
+ * 3. Why existing coverage misses it: test/extract/benchmark.test.ts covers a
+ * `..` segment and a symlinked file, but no folder named like `..drafts`
+ * and no symlinked intermediate folder.
+ * 4. Production seam: none. validateFixturePath is already exported and is
+ * exercised directly, as the sibling test does.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { validateFixturePath } from '../../src/commands/extract-benchmark.ts';
+
+let scratch: string;
+let packRoot: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-fixture-dotdot-'));
+ packRoot = join(scratch, 'pack');
+ mkdirSync(packRoot, { recursive: true });
+});
+afterEach(() => {
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+function writeFixture(dir: string): void {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'claim.jsonl'), '{}\n');
+}
+
+describe('validateFixturePath with a folder whose name starts with two dots', () => {
+ test('accepts a fixture file that does not exist yet under a ..drafts folder', () => {
+ expect(validateFixturePath(packRoot, '..drafts/claim.jsonl')).toBe(join(packRoot, '..drafts', 'claim.jsonl'));
+ });
+
+ test('accepts an existing fixture file under a ..drafts folder', () => {
+ writeFixture(join(packRoot, '..drafts'));
+ expect(validateFixturePath(packRoot, '..drafts/claim.jsonl')).toBe(join(packRoot, '..drafts', 'claim.jsonl'));
+ });
+
+ test('accepts a fixture reached through an in-pack folder symlinked to a ..real folder', () => {
+ writeFixture(join(packRoot, '..real'));
+ symlinkSync('..real', join(packRoot, 'fixtures'), 'dir');
+ expect(validateFixturePath(packRoot, 'fixtures/claim.jsonl')).toBe(join(packRoot, 'fixtures', 'claim.jsonl'));
+ });
+});
+
+describe('validateFixturePath still refuses a fixture that leaves the pack root', () => {
+ test('refuses a ../ segment', () => {
+ expect(() => validateFixturePath(packRoot, '../claim.jsonl')).toThrow(/'\.\.'\s*segment/);
+ expect(() => validateFixturePath(packRoot, '..drafts/../../claim.jsonl')).toThrow(/'\.\.'\s*segment/);
+ });
+
+ test('refuses a folder symlinked to an outside folder with a plain name', () => {
+ const outside = join(scratch, 'outside');
+ writeFixture(outside);
+ symlinkSync(outside, join(packRoot, 'fixtures'), 'dir');
+ expect(() => validateFixturePath(packRoot, 'fixtures/claim.jsonl')).toThrow(/realpath resolves outside the pack root/);
+ });
+
+ test('refuses a folder symlinked to an outside folder whose name starts with two dots', () => {
+ const outside = join(scratch, '..outside');
+ writeFixture(outside);
+ symlinkSync(outside, join(packRoot, 'fixtures'), 'dir');
+ expect(() => validateFixturePath(packRoot, 'fixtures/claim.jsonl')).toThrow(/realpath resolves outside the pack root/);
+ });
+
+ test('refuses a folder symlinked to a sibling folder that shares the pack root name prefix', () => {
+ const sibling = join(scratch, 'pack2');
+ writeFixture(sibling);
+ symlinkSync(sibling, join(packRoot, 'fixtures'), 'dir');
+ expect(() => validateFixturePath(packRoot, 'fixtures/claim.jsonl')).toThrow(/realpath resolves outside the pack root/);
+ });
+});
diff --git a/test/fixtures/guards/check-relative-dotdot.mjs/bad-double-quote/fixture.ts b/test/fixtures/guards/check-relative-dotdot.mjs/bad-double-quote/fixture.ts
new file mode 100644
index 0000000000..1326ac5c37
--- /dev/null
+++ b/test/fixtures/guards/check-relative-dotdot.mjs/bad-double-quote/fixture.ts
@@ -0,0 +1,4 @@
+// BAD: the same prefix-only check, spelled with double quotes.
+export function scope(rel: string): string {
+ return rel.startsWith("..") ? '' : rel;
+}
diff --git a/test/fixtures/guards/check-relative-dotdot.mjs/bad/fixture.ts b/test/fixtures/guards/check-relative-dotdot.mjs/bad/fixture.ts
new file mode 100644
index 0000000000..a681c62be7
--- /dev/null
+++ b/test/fixtures/guards/check-relative-dotdot.mjs/bad/fixture.ts
@@ -0,0 +1,6 @@
+// BAD: a prefix-only check refuses a legal first folder such as `..drafts`.
+import { relative } from 'node:path';
+export function inside(root: string, p: string): boolean {
+ const rel = relative(root, p);
+ return rel !== '' && !rel.startsWith('..');
+}
diff --git a/test/fixtures/guards/check-relative-dotdot.mjs/good/fixture.ts b/test/fixtures/guards/check-relative-dotdot.mjs/good/fixture.ts
new file mode 100644
index 0000000000..86e10db65d
--- /dev/null
+++ b/test/fixtures/guards/check-relative-dotdot.mjs/good/fixture.ts
@@ -0,0 +1,15 @@
+// GOOD: component-aware checks, a comment that names the old pattern, and an opt-out.
+import { relative, sep } from 'node:path';
+declare function relativeEscapesRoot(rel: string): boolean;
+export function inside(root: string, p: string): boolean {
+ // The old check, rel.startsWith('..'), also matched a folder named `..drafts`.
+ const rel = relative(root, p);
+ return rel !== '' && !relativeEscapesRoot(rel);
+}
+export function upward(rel: string): boolean {
+ return rel === '..' || rel.startsWith('../') || rel.startsWith(`..${sep}`);
+}
+export function isRangeToken(token: string): boolean {
+ // gbrain-allow-dotdot-prefix: a `..` range token in a git revision, not a path
+ return token.startsWith('..');
+}
diff --git a/test/frontmatter-dotdot-folder.test.ts b/test/frontmatter-dotdot-folder.test.ts
new file mode 100644
index 0000000000..54a5abf266
--- /dev/null
+++ b/test/frontmatter-dotdot-folder.test.ts
@@ -0,0 +1,109 @@
+/**
+ * `gbrain frontmatter validate` derives a page's expected slug from its path
+ * under the brain root (src/commands/frontmatter.ts). A first folder named
+ * `..drafts` is a legal folder, so its path must be used as written.
+ *
+ * Authoring gate:
+ * 1. Protects: a page at `..drafts/note.md` whose `slug:` matches its path is
+ * reported clean, and a mismatching slug is still reported; a file that is
+ * not under a brain (a loose folder, or a sibling folder that shares the
+ * brain's name prefix) is still judged by its file name alone.
+ * 2. Regression that fails it: the "outside the brain root" test matching any
+ * relative path that starts with the two characters `..` instead of only a
+ * `..` path component. That swaps the slug for the bare file name and
+ * reports a false SLUG_MISMATCH.
+ * 3. Why existing coverage misses it: frontmatter-fix-slug-5053.test.ts and
+ * frontmatter-cli.test.ts only use ordinary folder names.
+ * Bulk scans skip dot-folders by design, so the page is reached by naming
+ * the file (or the folder) explicitly.
+ * 4. Production seam: none. runFrontmatter is driven in-process on real temp
+ * dirs, the same way frontmatter-cli.test.ts does.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { runFrontmatter } from '../src/commands/frontmatter.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const page = (slug: string) => `---\ntype: note\ntitle: A note\nslug: ${slug}\n---\n\nbody\n`;
+
+let scratch: string;
+let brain: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'fm-dotdot-'));
+ brain = join(scratch, 'brain');
+ mkdirSync(join(brain, '.git'), { recursive: true });
+});
+afterEach(() => {
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+interface FileResult { file: string; errors: Array<{ code: string; message: string }> }
+
+/** Run `frontmatter validate <target> --json` in-process; return the per-file results. */
+async function validate(target: string): Promise<FileResult[]> {
+ const logOrig = console.log;
+ const out: string[] = [];
+ const prevExitCode = process.exitCode;
+ _resetCliExitVerdictForTests();
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ try {
+ await withEnv({ GBRAIN_HOME: join(scratch, 'home') }, () => runFrontmatter(['validate', target, '--json']));
+ } finally {
+ console.log = logOrig;
+ _resetCliExitVerdictForTests();
+ process.exitCode = prevExitCode ?? 0;
+ }
+ const doc = JSON.parse(out.join('\n')) as { results?: FileResult[]; files?: FileResult[] };
+ return (doc.results ?? doc.files ?? []) as FileResult[];
+}
+
+const codes = (r: FileResult[]) => r.flatMap(f => f.errors.map(e => e.code));
+
+describe('frontmatter validate with a first folder whose name starts with two dots', () => {
+ test('a slug that matches the ..drafts path is clean', async () => {
+ mkdirSync(join(brain, '..drafts'), { recursive: true });
+ const file = join(brain, '..drafts', 'note.md');
+ writeFileSync(file, page('..drafts/note'));
+ const results = await validate(file);
+ expect(results).toHaveLength(1);
+ expect(codes(results)).toEqual([]);
+ });
+
+ test('a slug that does not match the ..drafts path is still reported', async () => {
+ mkdirSync(join(brain, '..drafts'), { recursive: true });
+ const file = join(brain, '..drafts', 'note.md');
+ writeFileSync(file, page('other/thing'));
+ expect(codes(await validate(file))).toEqual(['SLUG_MISMATCH']);
+ });
+});
+
+describe('frontmatter validate still judges a file outside a brain by its file name', () => {
+ test('a loose file keeps a slug that matches its file name', async () => {
+ const loose = join(scratch, 'loose');
+ mkdirSync(loose);
+ const file = join(loose, 'note.md');
+ writeFileSync(file, page('note'));
+ expect(codes(await validate(file))).toEqual([]);
+ });
+
+ test('a file in a sibling folder that shares the brain name prefix is not read as part of the brain', async () => {
+ const sibling = join(scratch, 'brain2');
+ mkdirSync(sibling);
+ const file = join(sibling, 'note.md');
+ writeFileSync(file, page('note'));
+ expect(codes(await validate(file))).toEqual([]);
+ });
+
+ test('a file in a ..loose folder with no brain above it keeps a slug that matches its file name', async () => {
+ const loose = join(scratch, '..loose');
+ mkdirSync(loose);
+ const file = join(loose, 'note.md');
+ writeFileSync(file, page('note'));
+ expect(codes(await validate(file))).toEqual([]);
+ });
+});
diff --git a/test/git-commit-push-dotdot-folder-names.test.ts b/test/git-commit-push-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..446ad31d84
--- /dev/null
+++ b/test/git-commit-push-dotdot-folder-names.test.ts
@@ -0,0 +1,163 @@
+/**
+ * A folder whose name merely starts with two dots (`..drafts`, `..x`) is a normal folder inside a checkout. The commit-push
+ * path checks used `relative(root, path).startsWith('..')` for "outside the checkout", which also matches that folder, so
+ * `gbrain git commit-push -- ..drafts/a.md` was refused as outside, a `gbrain.sourceRoot` of `..drafts` was dropped (the
+ * whole checkout became the source root), an untrack under a managed root named `..x` read gbrain.yml from the wrong place,
+ * and a write-through into a source root named `..x` lost its root scope and swept in other folders' pending files.
+ * Protects: the folder is accepted and scoped like any other, while `../x`, a real outside directory, a sibling that shares
+ * the checkout's name prefix and a symlinked parent that points outside are still refused or dropped.
+ * Authoring gate: (1) which paths a commit may name and which folder it is confined to; (2) a startsWith('..') check that
+ * is not component-aware; (3) the other commit-push tests only use ordinary folder names; (4) no seam, real temp git
+ * repositories with a bare origin and the exported commit entry points.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { commitAndPush, commitPathsLocked, configuredSourceRoots, notePending, untrackAdmitted } from '../src/core/git/commit-push.ts';
+import { gitChildEnv } from '../src/core/git-env.ts';
+
+const env = gitChildEnv();
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env }).trim();
+const dirs: string[] = [];
+const scratch = (name: string) => { const d = realpathSync(mkdtempSync(join(tmpdir(), `gbrain-dotdot-${name}-`))); dirs.push(d); return d; };
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+function put(root: string, path: string, body: string): void {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), body);
+}
+
+/** A checkout `<dir>/work` on main with `files` committed and pushed to a bare origin; `<dir>/work2` and `<dir>/outside` are siblings. */
+function checkout(files: Record<string, string>): { dir: string; root: string } {
+ const dir = scratch('repo');
+ const root = join(dir, 'work');
+ git(dir, 'init', '-q', '-b', 'main', root);
+ git(root, 'config', 'user.name', 'Example Writer'); git(root, 'config', 'user.email', '[email protected]');
+ git(root, 'config', 'core.hooksPath', join(dir, 'hooks'));
+ for (const [path, body] of Object.entries({ 'seed.md': 'seed\n', ...files })) put(root, path, body);
+ git(root, 'add', '-A'); git(root, 'commit', '-qm', 'seed');
+ git(dir, 'init', '-q', '--bare', '-b', 'main', join(dir, 'origin.git'));
+ git(root, 'remote', 'add', 'origin', join(dir, 'origin.git'));
+ git(root, 'push', '-q', '-u', 'origin', 'main');
+ for (const sibling of ['work2', 'outside']) put(dir, `${sibling}/a.md`, `${sibling}\n`);
+ return { dir, root };
+}
+
+const refusalOf = (fn: () => unknown): { code?: string; message?: string } => {
+ try { fn(); } catch (e) { return e as { code?: string; message?: string }; }
+ throw new Error('expected a refusal');
+};
+const committedFiles = (root: string, rev = 'HEAD') => git(root, 'show', '--name-only', '--format=', rev).split('\n').filter(Boolean).sort();
+const SOURCE_ROOT = 'gbrain.sourceRoot';
+
+describe('commit-push scopes a path inside a folder named ..drafts', () => {
+ test('a file under ..drafts is committed, not refused as outside the checkout', () => {
+ const { root } = checkout({});
+ put(root, '..drafts/a.md', 'draft\n');
+ const result = commitAndPush({ repo: root, cwd: root, paths: ['..drafts/a.md'], message: 'add a draft' });
+ expect(result.outcome).toBe('pushed');
+ expect(result.paths).toEqual(['..drafts/a.md']);
+ expect(committedFiles(root)).toEqual(['..drafts/a.md']);
+ });
+
+ test('the same file named by absolute path and from a cwd inside ..drafts is committed', () => {
+ const { root } = checkout({});
+ put(root, '..drafts/a.md', 'draft\n');
+ put(root, '..drafts/b.md', 'draft b\n');
+ expect(commitAndPush({ repo: root, cwd: root, paths: [join(root, '..drafts', 'a.md')], message: 'abs' }).paths).toEqual(['..drafts/a.md']);
+ expect(commitAndPush({ repo: root, cwd: join(root, '..drafts'), paths: ['b.md'], message: 'from inside' }).paths).toEqual(['..drafts/b.md']);
+ });
+
+ test('paths that really leave the checkout are still refused: ../x, an outside directory, a name-prefix sibling, a symlinked parent', () => {
+ const { dir, root } = checkout({});
+ symlinkSync(join(dir, 'outside'), join(root, 'linked'));
+ const named = ['../outside/a.md', join(dir, 'outside', 'a.md'), join(dir, 'work2', 'a.md'), '../work2/a.md', 'linked/a.md', '..', '../'];
+ for (const path of named) {
+ const e = refusalOf(() => commitAndPush({ repo: root, cwd: root, paths: [path], message: 'escape' }));
+ expect(`${path}: ${e.code}`).toBe(`${path}: commit_paths_invalid`);
+ expect(e.message).toMatch(/outside the checkout|whole checkout/);
+ }
+ });
+});
+
+describe('configuredSourceRoots keeps a source root folder named ..drafts', () => {
+ test('a relative gbrain.sourceRoot of ..drafts stays the root, and a file elsewhere in the checkout is refused', () => {
+ const { root } = checkout({ 'other/b.md': 'other\n' });
+ git(root, 'config', SOURCE_ROOT, '..drafts');
+ put(root, '..drafts/a.md', 'draft\n');
+ expect(configuredSourceRoots(root)).toEqual(['..drafts']);
+ put(root, 'other/b.md', 'changed\n');
+ expect(refusalOf(() => commitAndPush({ repo: root, cwd: root, paths: ['other/b.md'], message: 'm' })).code).toBe('commit_outside_source_root');
+ expect(commitAndPush({ repo: root, cwd: root, paths: ['..drafts/a.md'], message: 'm' }).outcome).toBe('pushed');
+ });
+
+ test('an absolute gbrain.sourceRoot that names the ..drafts folder stays the root', () => {
+ const { root } = checkout({});
+ put(root, '..drafts/a.md', 'draft\n');
+ git(root, 'config', SOURCE_ROOT, join(root, '..drafts'));
+ expect(configuredSourceRoots(root)).toEqual(['..drafts']);
+ });
+
+ test('a source root that is outside the checkout is still dropped (the whole checkout stays the root): ../x, a real outside dir, a name-prefix sibling, ..', () => {
+ const { dir, root } = checkout({});
+ for (const outside of ['../outside', join(dir, 'outside'), join(dir, 'work2'), '../work2', '..', '../']) {
+ git(root, 'config', '--replace-all', SOURCE_ROOT, outside);
+ expect(`${outside}: ${JSON.stringify(configuredSourceRoots(root))}`).toBe(`${outside}: [""]`);
+ }
+ });
+});
+
+describe('untrack under a managed root folder named ..x', () => {
+ const YML = 'storage:\n db_only:\n - arch/\n';
+
+ test('the db_only admission reads gbrain.yml from ..x at HEAD, not from the checkout root', () => {
+ const { root } = checkout({ '..x/gbrain.yml': YML, '..x/arch/a.md': 'a\n' });
+ put(root, '..x/.gitignore', 'arch/\n'); put(root, '.gitignore', 'arch/\n');
+ const managed = { root: join(root, '..x'), evidence: 'test' };
+ expect(untrackAdmitted(root, ['..x/arch/a.md'], managed)).toEqual(['..x/arch/a.md']);
+ });
+
+ test('a file outside the managed root, and a managed root outside the checkout, still refuse untrack_not_db_only', () => {
+ const { dir, root } = checkout({ '..x/gbrain.yml': YML, '..x/arch/a.md': 'a\n', 'arch/b.md': 'b\n' });
+ put(root, '.gitignore', 'arch/\n');
+ const managed = { root: join(root, '..x'), evidence: 'test' };
+ expect(refusalOf(() => untrackAdmitted(root, ['arch/b.md'], managed)).code).toBe('untrack_not_db_only');
+ put(dir, 'outside/gbrain.yml', YML);
+ expect(refusalOf(() => untrackAdmitted(root, ['arch/b.md'], { root: join(dir, 'outside'), evidence: 'test' })).code).toBe('untrack_not_db_only');
+ expect(refusalOf(() => untrackAdmitted(root, ['arch/b.md'], { root: join(dir, 'work2'), evidence: 'test' })).code).toBe('untrack_not_db_only');
+ });
+});
+
+describe('write-through commit into a source root folder named ..x', () => {
+ /** The checkout holds a pending write-through file in `..x` (inside the source root) and one in `other` (outside it). */
+ function pending(rootName: string): { root: string; repo: string } {
+ const { root } = checkout({ [`${rootName}/seed.md`]: 'seed\n', 'other/seed.md': 'seed\n' });
+ put(root, `${rootName}/a.md`, 'new\n'); put(root, `${rootName}/p.md`, 'pending in root\n'); put(root, 'other/p.md', 'pending outside the source root\n');
+ notePending(root, [`${rootName}/p.md`, 'other/p.md']);
+ return { root, repo: join(root, rootName) };
+ }
+
+ test('the commit keeps the ..x source-root scope: a pending file outside it is not swept in', () => {
+ const { root, repo } = pending('..x');
+ commitPathsLocked(repo, ['..x/a.md'], 'write-through', { lockWaitMs: 1000 });
+ expect(committedFiles(root)).toEqual(['..x/a.md', '..x/p.md']);
+ expect(git(root, 'status', '--porcelain', '--', 'other')).toBe('?? other/p.md');
+ });
+
+ test('an ordinary source-root folder behaves the same way (control)', () => {
+ const { root, repo } = pending('notes');
+ commitPathsLocked(repo, ['notes/a.md'], 'write-through', { lockWaitMs: 1000 });
+ expect(committedFiles(root)).toEqual(['notes/a.md', 'notes/p.md']);
+ expect(git(root, 'status', '--porcelain', '--', 'other')).toBe('?? other/p.md');
+ });
+
+ test('a path that leaves the source root checkout is still refused: ../x, an outside directory, a name-prefix sibling', () => {
+ const { root, repo } = pending('..x');
+ const base = dirname(root);
+ for (const path of ['../outside/a.md', join(base, 'outside', 'a.md'), join(base, 'work2', 'a.md')]) {
+ expect(refusalOf(() => commitPathsLocked(repo, [path], 'escape', { lockWaitMs: 1000 })).code).toBe('commit_paths_invalid');
+ }
+ });
+});
diff --git a/test/path-confine-dotdot-folder.test.ts b/test/path-confine-dotdot-folder.test.ts
new file mode 100644
index 0000000000..802bbb24e3
--- /dev/null
+++ b/test/path-confine-dotdot-folder.test.ts
@@ -0,0 +1,133 @@
+/**
+ * isWriteTargetContained (src/core/path-confine.ts) accepts a write target
+ * under a folder named `..drafts` and still refuses one that leaves the root.
+ * It guards the write-through file sinks (takes, API and Google sources).
+ *
+ * Authoring gate:
+ * 1. Protects: a page written to `<root>/..drafts/page.md` (folder present or
+ * not yet created, or reached through an in-root symlink to a `..real`
+ * folder) is allowed; a target outside the root (a `../` path, a sibling
+ * folder that shares the root's name prefix, or a symlinked parent that
+ * points outside) is still refused.
+ * 2. Regression that fails it: the check treating any relative path that starts
+ * with the two characters `..` as "outside" instead of only a `..` path
+ * component, which refuses a legal first folder such as `..drafts`; or
+ * loosening it so an outside target passes.
+ * 3. Why existing coverage misses it: path-confine.test.ts uses ordinary
+ * folder names for both the allowed and the refused cases.
+ * 4. Production seam: none. isWriteTargetContained is exported and used
+ * directly on real temp dirs, as path-confine.test.ts does.
+ *
+ * relativeEscapesRoot is the shared check behind every such site. Its cases run
+ * with both path.posix and path.win32, so backslash and drive-letter shapes
+ * are checked on POSIX CI, where path.relative never produces them.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, posix, win32 } from 'path';
+
+import { isWriteTargetContained, relativeEscapesRoot } from '../src/core/path-confine.ts';
+
+let scratch: string;
+let root: string;
+
+beforeEach(() => {
+ scratch = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-confine-dotdot-')));
+ root = join(scratch, 'brain');
+ mkdirSync(root, { recursive: true });
+});
+afterEach(() => {
+ rmSync(scratch, { recursive: true, force: true });
+});
+
+describe('isWriteTargetContained with a first folder whose name starts with two dots', () => {
+ test('allows a new file in a ..drafts folder that does not exist yet', () => {
+ expect(isWriteTargetContained(join(root, '..drafts', 'page.md'), root)).toBe(true);
+ expect(isWriteTargetContained(join(root, '..drafts', 'deep', 'page.md'), root)).toBe(true);
+ });
+
+ test('allows a new file in an existing ..drafts folder', () => {
+ mkdirSync(join(root, '..drafts'));
+ expect(isWriteTargetContained(join(root, '..drafts', 'page.md'), root)).toBe(true);
+ });
+
+ test('allows the ..drafts folder itself and a folder named three dots', () => {
+ mkdirSync(join(root, '..drafts'));
+ expect(isWriteTargetContained(join(root, '..drafts'), root)).toBe(true);
+ expect(isWriteTargetContained(join(root, '...', 'page.md'), root)).toBe(true);
+ });
+
+ test('allows a write through an in-root symlink to a ..real folder', () => {
+ mkdirSync(join(root, '..real'));
+ symlinkSync('..real', join(root, 'people'), 'dir');
+ expect(isWriteTargetContained(join(root, 'people', 'page.md'), root)).toBe(true);
+ });
+
+ test('allows a root that itself sits under a ..drafts folder', () => {
+ const nested = join(scratch, '..drafts', 'brain');
+ mkdirSync(nested, { recursive: true });
+ expect(isWriteTargetContained(join(nested, 'page.md'), nested)).toBe(true);
+ });
+});
+
+describe('isWriteTargetContained still refuses a target that leaves the root', () => {
+ test('refuses a ../ path above the root', () => {
+ expect(isWriteTargetContained(join(root, '..', 'page.md'), root)).toBe(false);
+ expect(isWriteTargetContained(join(root, '..drafts', '..', '..', 'page.md'), root)).toBe(false);
+ });
+
+ test('refuses a file in a folder next to the root', () => {
+ mkdirSync(join(scratch, 'outside'));
+ expect(isWriteTargetContained(join(scratch, 'outside', 'page.md'), root)).toBe(false);
+ });
+
+ test('refuses a file in a ..outside folder next to the root', () => {
+ mkdirSync(join(scratch, '..outside'));
+ expect(isWriteTargetContained(join(scratch, '..outside', 'page.md'), root)).toBe(false);
+ });
+
+ test('refuses a file in a sibling folder that shares the root name prefix', () => {
+ mkdirSync(join(scratch, 'brain2'));
+ expect(isWriteTargetContained(join(scratch, 'brain2', 'page.md'), root)).toBe(false);
+ expect(isWriteTargetContained(join(scratch, 'brain-backup', 'page.md'), root)).toBe(false);
+ });
+
+ test('refuses a write through an in-root symlink that points outside', () => {
+ const outside = join(scratch, 'outside');
+ mkdirSync(outside);
+ symlinkSync(outside, join(root, 'people'), 'dir');
+ expect(isWriteTargetContained(join(root, 'people', 'page.md'), root)).toBe(false);
+ });
+
+ test('refuses a write through an in-root symlink that points at a ..outside folder', () => {
+ const outside = join(scratch, '..outside');
+ mkdirSync(outside);
+ symlinkSync(outside, join(root, 'people'), 'dir');
+ writeFileSync(join(outside, 'existing.md'), 'x');
+ expect(isWriteTargetContained(join(root, 'people', 'page.md'), root)).toBe(false);
+ expect(isWriteTargetContained(join(root, 'people', 'existing.md'), root)).toBe(false);
+ });
+});
+
+describe('relativeEscapesRoot', () => {
+ const inside = ['', 'a', 'a/b', '..drafts', '..drafts/a', '..x/y', '...', '.../a', '.hidden/a', 'a/../b', 'a/..'];
+ const outside = ['..', '../', '../x', '../..drafts', '../../x'];
+
+ test('posix: only a leading `..` component or an absolute path escapes', () => {
+ for (const rel of inside) expect(`${rel}: ${relativeEscapesRoot(rel, posix)}`).toBe(`${rel}: false`);
+ for (const rel of [...outside, '/etc/x', '/']) expect(`${rel}: ${relativeEscapesRoot(rel, posix)}`).toBe(`${rel}: true`);
+ });
+
+ test('win32: backslash, forward-slash and drive-letter shapes', () => {
+ for (const rel of [...inside, '..drafts\\a', '...\\a', 'a\\b']) expect(`${rel}: ${relativeEscapesRoot(rel, win32)}`).toBe(`${rel}: false`);
+ for (const rel of [...outside, '..\\', '..\\x', '..\\..drafts', 'D:\\x', 'D:/x', '\\\\server\\share\\x', '\\x']) {
+ expect(`${rel}: ${relativeEscapesRoot(rel, win32)}`).toBe(`${rel}: true`);
+ }
+ });
+
+ test('defaults to the host path module', () => {
+ expect(relativeEscapesRoot('..drafts/a')).toBe(false);
+ expect(relativeEscapesRoot('../a')).toBe(true);
+ });
+});
diff --git a/test/path-state-dotdot-folder-names.test.ts b/test/path-state-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..5bc79f8a7a
--- /dev/null
+++ b/test/path-state-dotdot-folder-names.test.ts
@@ -0,0 +1,73 @@
+/**
+ * Two Git path-state probes judged a file "outside the checkout" when `relative(checkout, file)` started with `..`, which
+ * also matches a legal first folder named `..drafts`:
+ * - `gitPathState` (fact fence write-through) answered 'unknown', so the fence commit was skipped and audited as
+ * `git_durability_prewrite_state_unknown`;
+ * - `canonicalDeletionState` (file-drift repair) answered 'unknown', so a page whose file was deleted from such a
+ * folder could not be told apart from one that was never committed.
+ * Protects: files under `..drafts` get the same answers as files under `notes` (clean / self_dirty / foreign_dirty;
+ * in_head / gone), and paths that really leave the checkout (outside, a sibling that shares the checkout's name prefix,
+ * `../x`, a symlinked folder that points out) are still 'unknown'.
+ * Authoring gate: (1) the answers of the two exported probes; (2) a startsWith('..') check that is not component-aware;
+ * (3) no existing test calls either probe with such a folder; (4) no seam, real git repositories in a temp directory.
+ */
+import { afterAll, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { appendFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { gitPathState } from '../src/core/facts/fence-write.ts';
+import { canonicalDeletionState } from '../src/core/persistence/reconcile-state.ts';
+
+const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-path-state-dotdot-')));
+afterAll(() => { rmSync(dir, { recursive: true, force: true }); });
+const git = (cwd: string, args: string[]) => execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
+const write = (root: string, rel: string, body: string) => { mkdirSync(dirname(join(root, rel)), { recursive: true }); writeFileSync(join(root, rel), body); };
+let n = 0;
+
+/** A checkout `work` (committed `<folder>/a.md`, `<folder>/b.md`), a sibling `work2` that shares its name prefix, and `outside`. */
+function fixture(folder: string) {
+ const base = join(dir, `case-${n++}`), work = join(base, 'work'), work2 = join(base, 'work2'), outside = join(base, 'outside');
+ for (const d of [work, work2, outside]) mkdirSync(d, { recursive: true });
+ git(work, ['init', '-q', '-b', 'main']);
+ git(work, ['config', 'user.email', '[email protected]']); git(work, ['config', 'user.name', 'Example Writer']); git(work, ['config', 'commit.gpgsign', 'false']);
+ write(work, `${folder}/a.md`, 'a\n'); write(work, `${folder}/b.md`, 'b\n');
+ git(work, ['add', '-A']); git(work, ['commit', '-q', '-m', 'seed']);
+ write(work2, 'a.md', 'sibling\n'); write(outside, 'a.md', 'outside\n');
+ symlinkSync(outside, join(work, 'linked'));
+ return { work, work2, outside };
+}
+
+for (const folder of ['..drafts', 'notes']) {
+ test(`gitPathState: a file under ${folder} is clean, then self_dirty once edited`, () => {
+ const { work } = fixture(folder);
+ const a = join(work, folder, 'a.md');
+ expect(gitPathState(work, a)).toBe('clean');
+ appendFileSync(a, 'edited\n');
+ expect(gitPathState(work, a)).toBe('self_dirty');
+ appendFileSync(join(work, folder, 'b.md'), 'edited\n');
+ write(work, `${folder}/c.md`, 'new\n');
+ expect(gitPathState(work, a)).toBe('self_dirty');
+ // The probe is limited to the target path, so a sibling's dirt does not change the answer for another file.
+ expect(gitPathState(work, join(work, folder, 'b.md'))).toBe('self_dirty');
+ });
+
+ test(`canonicalDeletionState: a file deleted from ${folder} is in_head when committed and gone when never committed`, () => {
+ const { work } = fixture(folder);
+ rmSync(join(work, folder, 'a.md'));
+ expect(canonicalDeletionState(work, join(work, folder, 'a.md'))).toBe('in_head');
+ expect(canonicalDeletionState(work, join(work, folder, 'never.md'))).toBe('gone');
+ });
+}
+
+test('both probes still answer unknown for a path that leaves the checkout (and the symlink case for the deletion probe)', () => {
+ const { work, work2, outside } = fixture('..drafts');
+ const leaving = [join(outside, 'a.md'), join(work2, 'a.md'), join(work, '..', 'outside', 'a.md'), join(work, '..', 'work2', 'a.md'), join(work, '..')];
+ for (const path of leaving) {
+ expect(`${path}: ${gitPathState(work, path)}`).toBe(`${path}: unknown`);
+ expect(`${path}: ${canonicalDeletionState(work, path)}`).toBe(`${path}: unknown`);
+ }
+ // A symlinked folder that points out: canonicalDeletionState resolves it and refuses. (gitPathState does not resolve
+ // symlinks and answers from git alone; that is separate from this bug and is not asserted here.)
+ expect(canonicalDeletionState(work, join(work, 'linked', 'a.md'))).toBe('unknown');
+});
diff --git a/test/setup-brain-first-dotdot-folder.test.ts b/test/setup-brain-first-dotdot-folder.test.ts
new file mode 100644
index 0000000000..58118f96c2
--- /dev/null
+++ b/test/setup-brain-first-dotdot-folder.test.ts
@@ -0,0 +1,79 @@
+/**
+ * The per-turn brain-first rule for a project-scope install (a Claude Code
+ * CLAUDE.local.md) applies only to sessions started inside that project
+ * (src/core/setup/brain-first.ts, brainFirstTurnRule).
+ *
+ * Authoring gate:
+ * 1. Protects: a session started in `<project>/..drafts/work` still gets the
+ * rule, because that folder is inside the project; a session in the parent
+ * folder, in a sibling folder that shares the project's name prefix, or in
+ * another project still does not.
+ * 2. Regression that fails it: the "is the cwd inside the project" test
+ * matching any relative path that starts with the two characters `..`
+ * instead of only a `..` path component. A legal folder named `..drafts`
+ * then silently turns the rule off.
+ * 3. Why existing coverage misses it: brain-first-turn-rule.test.ts only
+ * asserts user-scope installs; no test starts a session from a project
+ * subfolder or from outside the project.
+ * 4. Production seam: none. brainFirstTurnRule is exported; the ledger is a
+ * real file under a private GBRAIN_HOME set with withEnv.
+ */
+import { afterAll, 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 { withEnv } from './helpers/with-env.ts';
+import { brainFirstTurnRule, renderBrainFirstTurnRule } from '../src/core/setup/brain-first.ts';
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+const RULE = renderBrainFirstTurnRule({ kind: 'mcp', server: 'gbrain' });
+
+/** A GBRAIN_HOME whose ledger records one installed project-scope block, plus the project folder it names. */
+function projectInstall(): { home: string; project: string; scratch: string } {
+ const scratch = mkdtempSync(join(tmpdir(), 'gbrain-first-dotdot-'));
+ roots.push(scratch);
+ const home = join(scratch, 'home');
+ const project = join(scratch, 'project');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ mkdirSync(project, { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'agent-instructions.json'), JSON.stringify({ version: 1, entries: [{
+ harness: 'claude-code', status: 'installed', path: join(project, 'CLAUDE.local.md'), block_version: 2,
+ access: { kind: 'mcp', server: 'gbrain' }, writer: 'test', created_file: true, updated_at: new Date(Date.UTC(2026, 9, 25)).toISOString(),
+ }] }));
+ return { home, project, scratch };
+}
+
+const ruleFor = (home: string, cwd: string) =>
+ withEnv({ GBRAIN_HOME: home, GBRAIN_AGENT_INSTRUCTIONS: undefined }, async () => brainFirstTurnRule('claude-code', cwd));
+
+describe('brain-first turn rule: a project-scope install and the session folder', () => {
+ test('a session in the project folder gets the rule', async () => {
+ const { home, project } = projectInstall();
+ expect(await ruleFor(home, project)).toBe(RULE);
+ });
+
+ test('a session in a subfolder named ..drafts gets the rule', async () => {
+ const { home, project } = projectInstall();
+ expect(await ruleFor(home, join(project, '..drafts'))).toBe(RULE);
+ expect(await ruleFor(home, join(project, '..drafts', 'work'))).toBe(RULE);
+ });
+
+ test('a session in the parent folder does not get the rule', async () => {
+ const { home, project, scratch } = projectInstall();
+ expect(await ruleFor(home, scratch)).toBeNull();
+ expect(await ruleFor(home, join(project, '..'))).toBeNull();
+ });
+
+ test('a session in a sibling folder that shares the project name prefix does not get the rule', async () => {
+ const { home, scratch } = projectInstall();
+ expect(await ruleFor(home, join(scratch, 'project2'))).toBeNull();
+ });
+
+ test('a session in another project, or in a ..other folder next to the project, does not get the rule', async () => {
+ const { home, scratch } = projectInstall();
+ expect(await ruleFor(home, join(scratch, 'elsewhere', 'app'))).toBeNull();
+ expect(await ruleFor(home, join(scratch, '..other'))).toBeNull();
+ });
+});
diff --git a/test/skill-catalog-dotdot-folder.test.ts b/test/skill-catalog-dotdot-folder.test.ts
new file mode 100644
index 0000000000..081f730642
--- /dev/null
+++ b/test/skill-catalog-dotdot-folder.test.ts
@@ -0,0 +1,70 @@
+/**
+ * `confineManifestPath` (src/core/skill-catalog.ts) confines a skills-manifest entry to the skills directory before
+ * `get_skill` and `list_skills` read it.
+ * Protects: an entry whose SKILL.md sits in a first folder named `..shared` (or `...`), or is reached through an
+ * in-directory symlink to such a folder, resolves to its real path; an entry that leaves the directory (`../`), points
+ * into a sibling folder that shares the directory's name prefix, or goes through a symlink that points outside, is still
+ * refused with invalid_params.
+ * Authoring gate: (1) whether a legal skill in the skills directory can be read through get_skill and list_skills;
+ * (2) a startsWith('..') check that is not component-aware refuses `..shared/alpha/SKILL.md` as "escapes skills dir";
+ * (3) skill-catalog.test.ts only uses ordinary folder names; (4) no seam: the exported function on real temp dirs.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { confineManifestPath } from '../src/core/skill-catalog.ts';
+
+const dirs: string[] = [];
+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });
+
+/** `<dir>/skills` (the skills directory) plus `<dir>/skills2` and `<dir>/outside` siblings. */
+function layout(): { dir: string; skills: string } {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-skill-catalog-dotdot-')));
+ dirs.push(dir);
+ const skills = join(dir, 'skills');
+ mkdirSync(skills, { recursive: true });
+ return { dir, skills };
+}
+
+function skillAt(root: string, rel: string): string {
+ const abs = join(root, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, '---\nname: alpha\n---\n# alpha\n');
+ return abs;
+}
+
+describe('confineManifestPath with a first folder whose name starts with two dots', () => {
+ test('a SKILL.md under ..shared or ... resolves to its real path', () => {
+ const { skills } = layout();
+ const shared = skillAt(skills, '..shared/alpha/SKILL.md');
+ const dots = skillAt(skills, '.../beta/SKILL.md');
+ expect(confineManifestPath(skills, { name: 'alpha', path: '..shared/alpha/SKILL.md' })).toBe(shared);
+ expect(confineManifestPath(skills, { name: 'beta', path: '.../beta/SKILL.md' })).toBe(dots);
+ });
+
+ test('an in-directory symlink to a ..real folder resolves', () => {
+ const { skills } = layout();
+ const real = skillAt(skills, '..real/gamma/SKILL.md');
+ symlinkSync('..real/gamma', join(skills, 'gamma'), 'dir');
+ expect(confineManifestPath(skills, { name: 'gamma', path: 'gamma/SKILL.md' })).toBe(real);
+ });
+
+ test('an ordinary folder resolves the same way (control)', () => {
+ const { skills } = layout();
+ const plain = skillAt(skills, 'alpha/SKILL.md');
+ expect(confineManifestPath(skills, { name: 'alpha', path: 'alpha/SKILL.md' })).toBe(plain);
+ });
+
+ test('entries that leave the directory stay refused: ../, name-prefix sibling, symlink out', () => {
+ const { dir, skills } = layout();
+ skillAt(dir, 'outside/alpha/SKILL.md');
+ skillAt(dir, 'skills2/alpha/SKILL.md');
+ symlinkSync(join(dir, 'outside', 'alpha'), join(skills, 'linked'), 'dir');
+ for (const path of ['../outside/alpha/SKILL.md', '../skills2/alpha/SKILL.md', 'linked/SKILL.md']) {
+ let code = 'none';
+ try { confineManifestPath(skills, { name: 'alpha', path }); } catch (e) { code = (e as { code?: string }).code ?? String(e); }
+ expect(`${path}: ${code}`).toBe(`${path}: invalid_params`);
+ }
+ });
+});
diff --git a/test/skillpack-brain-resident-locate-dotdot-folder.test.ts b/test/skillpack-brain-resident-locate-dotdot-folder.test.ts
new file mode 100644
index 0000000000..ea293d2e02
--- /dev/null
+++ b/test/skillpack-brain-resident-locate-dotdot-folder.test.ts
@@ -0,0 +1,151 @@
+/**
+ * A brain-resident pack whose real folder name begins with two dots
+ * (`..shared`, `..skills`) must still serve its skills; a symlink that leaves
+ * the pack must still be refused (src/core/skillpack/brain-resident-locate.ts,
+ * getResidentSkillDetail).
+ *
+ * Authoring gate:
+ * 1. Protects: get_skill with a source_id serves a SKILL.md that lives in a
+ * folder named `..shared` inside the pack (reached through an in-pack
+ * symlink, which is allowed by design) and still refuses anything that
+ * resolves outside the pack root.
+ * 2. Regression that fails it: the containment check treating any relative
+ * path that starts with the two characters `..` as "outside", instead of
+ * only a `..` path component. Or, the other way round, loosening the check
+ * so a sibling folder or an outside symlink is served.
+ * 3. Why existing coverage misses it: skillpack-brain-resident-locate.test.ts
+ * only has the escape case (a symlink to an unrelated outside dir); no test
+ * uses an in-pack folder whose name starts with `..`, or a sibling folder
+ * that shares the pack root's name prefix.
+ * 4. Production seam: none. Everything goes through the exported
+ * getResidentSkillDetail with a fake engine, as the sibling test does.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { runInitBrainPack } from '../src/core/skillpack/init-brain-pack.ts';
+import { getResidentSkillDetail } from '../src/core/skillpack/brain-resident-locate.ts';
+import { OperationError, type OperationContext } from '../src/core/operations.ts';
+
+let root: string;
+let packDir: string;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-brl-dotdot-'));
+ packDir = join(root, 'pack-source');
+ runInitBrainPack({ targetDir: packDir, name: 'deal-brain', firstSkillSlug: 'diligence', schemaPack: 'gbrain-base' });
+});
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+function engineFor(localPath: string): OperationContext['engine'] {
+ return {
+ executeRaw: async () => [{
+ id: 'default', name: 'default', local_path: localPath, last_commit: null, last_sync_at: null,
+ config: {}, created_at: new Date(), archived: false,
+ }],
+ getConfig: async () => null,
+ } as unknown as OperationContext['engine'];
+}
+
+function ctxFor(localPath: string): OperationContext {
+ return {
+ engine: engineFor(localPath),
+ config: {} as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {}, debug() {} } as unknown as OperationContext['logger'],
+ dryRun: false,
+ remote: false,
+ } as OperationContext;
+}
+
+function skillMd(title: string): string {
+ return `---\nname: diligence\ndescription: ${title}\n---\n\n# diligence\n\n${title}\n`;
+}
+
+async function expectEscape(p: Promise<unknown>): Promise<void> {
+ try {
+ await p;
+ } catch (e) {
+ expect(e).toBeInstanceOf(OperationError);
+ expect((e as OperationError).code).toBe('storage_error');
+ expect((e as OperationError).message).toContain('escaped');
+ return;
+ }
+ throw new Error('expected the skill path to be refused as escaped, but the call resolved');
+}
+
+describe('getResidentSkillDetail with a folder whose name starts with two dots', () => {
+ test('serves a skill reached through a symlink into an in-pack ..shared folder', async () => {
+ const real = join(packDir, '..shared', 'diligence');
+ mkdirSync(real, { recursive: true });
+ writeFileSync(join(real, 'SKILL.md'), skillMd('lives in the dotdot folder'));
+ rmSync(join(packDir, 'skills', 'diligence'), { recursive: true, force: true });
+ symlinkSync(join('..', '..shared', 'diligence'), join(packDir, 'skills', 'diligence'), 'dir');
+
+ const detail = await getResidentSkillDetail(ctxFor(packDir), 'default', 'diligence');
+ expect(detail.body).toContain('lives in the dotdot folder');
+ });
+
+ test('serves a skill when the whole skills folder is a symlink to an in-pack ..skills folder', async () => {
+ renameSync(join(packDir, 'skills'), join(packDir, '..skills'));
+ symlinkSync('..skills', join(packDir, 'skills'), 'dir');
+
+ const detail = await getResidentSkillDetail(ctxFor(packDir), 'default', 'diligence');
+ expect(detail.name).toBe('diligence');
+ expect(detail.body).toContain('# diligence');
+ });
+
+ test('serves a skill when the pack root itself sits under a ..drafts folder', async () => {
+ const nested = join(root, '..drafts', 'pack');
+ mkdirSync(join(root, '..drafts'), { recursive: true });
+ runInitBrainPack({ targetDir: nested, name: 'deal-brain', firstSkillSlug: 'diligence', schemaPack: 'gbrain-base' });
+
+ const detail = await getResidentSkillDetail(ctxFor(nested), 'default', 'diligence');
+ expect(detail.body).toContain('# diligence');
+ });
+});
+
+describe('getResidentSkillDetail still refuses a skill that leaves the pack', () => {
+ test('refuses a skill symlinked to an outside folder with a plain name', async () => {
+ const outside = join(root, 'outside-skill');
+ mkdirSync(outside, { recursive: true });
+ writeFileSync(join(outside, 'SKILL.md'), skillMd('TOP SECRET OUTSIDE PACK'));
+ rmSync(join(packDir, 'skills', 'diligence'), { recursive: true, force: true });
+ symlinkSync(outside, join(packDir, 'skills', 'diligence'), 'dir');
+
+ await expectEscape(getResidentSkillDetail(ctxFor(packDir), 'default', 'diligence'));
+ });
+
+ test('refuses a skill symlinked to an outside folder whose name starts with two dots', async () => {
+ const outside = join(root, '..outside', 'diligence');
+ mkdirSync(outside, { recursive: true });
+ writeFileSync(join(outside, 'SKILL.md'), skillMd('TOP SECRET OUTSIDE PACK'));
+ rmSync(join(packDir, 'skills', 'diligence'), { recursive: true, force: true });
+ symlinkSync(outside, join(packDir, 'skills', 'diligence'), 'dir');
+
+ await expectEscape(getResidentSkillDetail(ctxFor(packDir), 'default', 'diligence'));
+ });
+
+ test('refuses a skill symlinked into a sibling folder that shares the pack root name prefix', async () => {
+ const sibling = join(root, 'pack-source2', 'diligence');
+ mkdirSync(sibling, { recursive: true });
+ writeFileSync(join(sibling, 'SKILL.md'), skillMd('TOP SECRET SIBLING PACK'));
+ rmSync(join(packDir, 'skills', 'diligence'), { recursive: true, force: true });
+ symlinkSync(sibling, join(packDir, 'skills', 'diligence'), 'dir');
+
+ await expectEscape(getResidentSkillDetail(ctxFor(packDir), 'default', 'diligence'));
+ });
+
+ test('refuses a skills folder that is a symlink to an outside folder', async () => {
+ const outside = join(root, 'outside-skills');
+ mkdirSync(join(outside, 'diligence'), { recursive: true });
+ writeFileSync(join(outside, 'diligence', 'SKILL.md'), skillMd('TOP SECRET OUTSIDE SKILLS'));
+ rmSync(join(packDir, 'skills'), { recursive: true, force: true });
+ symlinkSync(outside, join(packDir, 'skills'), 'dir');
+
+ await expectEscape(getResidentSkillDetail(ctxFor(packDir), 'default', 'diligence'));
+ });
+});
diff --git a/test/skillpack-safe-update-dotdot-folder.test.ts b/test/skillpack-safe-update-dotdot-folder.test.ts
new file mode 100644
index 0000000000..dd7762bcd9
--- /dev/null
+++ b/test/skillpack-safe-update-dotdot-folder.test.ts
@@ -0,0 +1,133 @@
+/**
+ * recordScaffoldBases (src/core/skillpack/safe-update.ts) records an install
+ * base for a skill folder named `..drafts`, and still skips a file that sits
+ * outside the skills root.
+ *
+ * Authoring gate:
+ * 1. Protects: a scaffolded skill whose folder name starts with two dots gets
+ * its install base recorded, so a later `--update-untouched` can update it;
+ * a file outside the skills root (a `../` path, a sibling folder sharing the
+ * root's name prefix, or a symlinked parent pointing outside) is never
+ * recorded as a skill of this root.
+ * 2. Regression that fails it: the "outside the root" test matching any
+ * relative path that starts with the two characters `..` rather than a `..`
+ * path component; or loosening it so outside files get recorded.
+ * 3. Why existing coverage misses it: skillpack-safe-update.test.ts records
+ * bases only for ordinary slugs (`demo`, `other`) and has no outside-root
+ * case for recordScaffoldBases.
+ * 4. Production seam: none. The exported recordScaffoldBases and loadState are
+ * used with a private state file, as the sibling test does.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+import { recordScaffoldBases, skillsRootKey } from '../src/core/skillpack/safe-update.ts';
+import { sha256 } from '../src/core/skillpack/update-journal.ts';
+import { loadState } from '../src/core/skillpack/state.ts';
+
+const created: string[] = [];
+afterEach(() => {
+ while (created.length) rmSync(created.pop()!, { recursive: true, force: true });
+});
+
+interface Env { dir: string; skillsRoot: string; statePath: string }
+
+function setup(): Env {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-bases-dotdot-'));
+ created.push(dir);
+ const skillsRoot = join(dir, 'skills');
+ mkdirSync(skillsRoot, { recursive: true });
+ return { dir, skillsRoot, statePath: join(dir, 'state', 'skillpack-state.json') };
+}
+
+function writeSkill(path: string, body: string): string {
+ mkdirSync(join(path, '..'), { recursive: true });
+ writeFileSync(path, body);
+ return path;
+}
+
+/** The recorded slugs of the skills root, or [] when nothing was recorded. */
+function recordedSlugs(env: Env): string[] {
+ const roots = loadState({ statePath: env.statePath }).roots ?? {};
+ return Object.keys(roots[skillsRootKey(env.skillsRoot)] ?? {});
+}
+
+/**
+ * Record `target` together with an ordinary in-root skill (`demo`). The control
+ * proves recording works at all, so an empty result for `target` is the skip.
+ */
+async function recordWithControl(env: Env, target: string): Promise<void> {
+ const control = writeSkill(join(env.skillsRoot, 'demo', 'SKILL.md'), '# demo\n');
+ await recordScaffoldBases(env.skillsRoot, [
+ { target, outcome: 'wrote_new', sharedDep: false },
+ { target: control, outcome: 'wrote_new', sharedDep: false },
+ ], { statePath: env.statePath });
+}
+
+describe('recordScaffoldBases with a skill folder whose name starts with two dots', () => {
+ test('records the base of a skill written under a ..drafts folder', async () => {
+ const env = setup();
+ const target = writeSkill(join(env.skillsRoot, '..drafts', 'SKILL.md'), '# drafts\n');
+
+ await recordScaffoldBases(env.skillsRoot, [{ target, outcome: 'wrote_new', sharedDep: false }], { statePath: env.statePath });
+
+ const roots = loadState({ statePath: env.statePath }).roots ?? {};
+ const record = roots[skillsRootKey(env.skillsRoot)]?.['..drafts'];
+ expect(record?.files['..drafts/SKILL.md']).toBe(sha256('# drafts\n'));
+ });
+
+ test('records an ordinary skill next to a ..drafts one', async () => {
+ const env = setup();
+ const dotted = writeSkill(join(env.skillsRoot, '..x', 'SKILL.md'), '# x\n');
+ const plain = writeSkill(join(env.skillsRoot, 'demo', 'SKILL.md'), '# demo\n');
+
+ await recordScaffoldBases(env.skillsRoot, [
+ { target: dotted, outcome: 'wrote_new', sharedDep: false },
+ { target: plain, outcome: 'wrote_new', sharedDep: false },
+ ], { statePath: env.statePath });
+
+ expect(recordedSlugs(env).sort()).toEqual(['..x', 'demo']);
+ });
+});
+
+describe('recordScaffoldBases still skips a file outside the skills root', () => {
+ test('skips a file in a plain folder above the skills root', async () => {
+ const env = setup();
+ const target = writeSkill(join(env.dir, 'elsewhere', 'SKILL.md'), '# elsewhere\n');
+
+ await recordWithControl(env, target);
+
+ expect(recordedSlugs(env)).toEqual(['demo']);
+ });
+
+ test('skips a file in a sibling folder that shares the skills root name prefix', async () => {
+ const env = setup();
+ const target = writeSkill(join(env.dir, 'skills2', 'demo', 'SKILL.md'), '# sibling\n');
+
+ await recordWithControl(env, target);
+
+ expect(recordedSlugs(env)).toEqual(['demo']);
+ });
+
+ test('skips a file in a ..outside folder next to the skills root', async () => {
+ const env = setup();
+ const target = writeSkill(join(env.dir, '..outside', 'demo', 'SKILL.md'), '# outside\n');
+
+ await recordWithControl(env, target);
+
+ expect(recordedSlugs(env)).toEqual(['demo']);
+ });
+
+ test('skips a file whose skill folder is a symlink pointing outside the skills root', async () => {
+ const env = setup();
+ const outside = join(env.dir, 'outside-skill');
+ writeSkill(join(outside, 'SKILL.md'), '# outside\n');
+ symlinkSync(outside, join(env.skillsRoot, 'linked'), 'dir');
+
+ await recordWithControl(env, join(env.skillsRoot, 'linked', 'SKILL.md'));
+
+ expect(recordedSlugs(env)).toEqual(['demo']);
+ });
+});
diff --git a/test/sync-applicability-dotdot-folder-names.test.ts b/test/sync-applicability-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..7b86f4fd50
--- /dev/null
+++ b/test/sync-applicability-dotdot-folder-names.test.ts
@@ -0,0 +1,55 @@
+/**
+ * `syncContentDirectory` decides that sync does not apply to a gbrain-owned content directory
+ * (`<GBRAIN_HOME>/.gbrain/content/<brain>/<source>`). It treated any path whose `relative()` from the content directory
+ * starts with `..` as outside it, which also matches a brain folder named `..x`, so such a directory was not recognised
+ * as gbrain-owned and sync went on to treat it as a Git source.
+ * Protects: a source directory under `content/..x/` is recognised (owned by the content root), while a directory outside
+ * the content directory, a sibling that shares its name prefix (`content2`), `../content` spelled out, the content
+ * directory itself and a symlink under it that points outside are not.
+ * Authoring gate: (1) whether sync is refused as not applicable for a gbrain-owned directory; (2) a startsWith('..')
+ * check that is not component-aware; (3) sync-applicability.test.ts only uses a brain folder named `brain-example`; (4) no
+ * seam, the exported function on in-memory PGLite with GBRAIN_HOME set through withEnv, as that test does.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { syncContentDirectory } from '../src/core/sync-applicability.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let home: string;
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-sync-dotdot-'))); });
+
+const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home }, fn);
+const dirAt = (...parts: string[]) => { const dir = join(home, ...parts); mkdirSync(dir, { recursive: true }); return dir; };
+
+describe('syncContentDirectory and a brain folder named ..x', () => {
+ test('a source directory under content/..x is a gbrain-owned content directory', () => inHome(async () => {
+ const root = dirAt('.gbrain', 'content', '..x', 'default');
+ expect(await syncContentDirectory(engine, { repoPath: root })).toMatchObject({ sourceId: 'default', root, ownedBy: 'content_root' });
+ const second = dirAt('.gbrain', 'content', '..drafts', 'notes');
+ expect(await syncContentDirectory(engine, { repoPath: second })).toMatchObject({ root: second, ownedBy: 'content_root' });
+ }));
+
+ test('an ordinary brain folder is recognised the same way (control)', () => inHome(async () => {
+ const root = dirAt('.gbrain', 'content', 'brain-example', 'default');
+ expect(await syncContentDirectory(engine, { repoPath: root })).toMatchObject({ root, ownedBy: 'content_root' });
+ }));
+
+ test('directories that are not under the content directory are not owned: outside, name-prefix sibling, ../content, the content directory itself, a symlink out', () => inHome(async () => {
+ dirAt('.gbrain', 'content');
+ const outside = dirAt('elsewhere', 'default');
+ const symlinked = join(dirAt('.gbrain', 'content', 'brain-example'), 'linked');
+ symlinkSync(outside, symlinked);
+ for (const root of [outside, dirAt('.gbrain', 'content2', 'default'), join(dirAt('.gbrain', 'content', 'brain-example'), '..', '..', 'content2'),
+ join(home, '.gbrain', 'content'), symlinked]) {
+ expect(`${root}: ${JSON.stringify(await syncContentDirectory(engine, { repoPath: root }))}`).toBe(`${root}: null`);
+ }
+ }));
+});
diff --git a/test/sync-markers-dotdot-folder-names.test.ts b/test/sync-markers-dotdot-folder-names.test.ts
new file mode 100644
index 0000000000..3cb59f7e0b
--- /dev/null
+++ b/test/sync-markers-dotdot-folder-names.test.ts
@@ -0,0 +1,67 @@
+/**
+ * A source whose folder inside its Git checkout is named with two leading dots (`<repo>/..x`) is a normal source root.
+ * `originGitPaths` (sync-markers) computed the folder's scope as `relative(gitRoot, root)` and treated any scope starting
+ * with `..` as "the checkout cannot be read", so `originCommitted` answered "committed" for every origin of that source,
+ * even a file that was never in Git: a retention purge kept it and a deletion marker was written for it needlessly.
+ * Protects: for such a source `originCommitted` answers from the real tree (committed file true, never-committed file
+ * false), as it does for a folder named `notes`; a binding that points outside its checkout still answers true (fail closed).
+ * Authoring gate: (1) whether a purged page's origin is still committed; (2) a startsWith('..') check that is not
+ * component-aware; (3) the other sync-marker tests only use a source at the checkout root or a folder named `notes`;
+ * (4) no seam, the exported originCommitted on a real PGLite brain with a real claimed worktree.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { originCommitted } from '../src/core/persistence/sync-markers.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (cwd: string, ...args: string[]) => execFileSync('git', ['-C', cwd, '-c', 'user.name=Example', '-c', '[email protected]', '-c', 'commit.gpgsign=false', ...args], { stdio: 'ignore' });
+
+/** A managed brain whose default source is the folder `folder` inside a Git checkout, with `kept.md` committed there and `draft.md` never committed. */
+async function withSourceFolder(folder: string, run: (engine: Awaited<ReturnType<typeof isolatedSharedSkillsEngine>>['engine'], repo: string) => Promise<void>): Promise<void> {
+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-dotdot-origin-')));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine();
+ try {
+ const repo = join(home, 'repo');
+ const root = join(repo, folder);
+ mkdirSync(root, { recursive: true });
+ git(repo, 'init', '-q', '-b', 'main');
+ writeFileSync(join(repo, 'README.md'), 'readme\n');
+ writeFileSync(join(root, 'kept.md'), '---\ntitle: Kept\n---\n\nKept.\n');
+ git(repo, 'add', '-A'); git(repo, 'commit', '-qm', 'seed');
+ writeFileSync(join(root, 'draft.md'), '---\ntitle: Draft\n---\n\nNever committed.\n');
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await claimWorktree(engine, 'default', root);
+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
+ await run(engine, repo);
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+}
+
+describe('originCommitted for a source folder inside its checkout', () => {
+ for (const folder of ['..x', '..drafts', 'notes']) {
+ test(`${folder}: a committed origin is committed and a never-committed origin is not`, () => withSourceFolder(folder, async engine => {
+ expect(await originCommitted(engine, 'default', 'kept.md')).toBe(true);
+ expect(await originCommitted(engine, 'default', 'draft.md')).toBe(false);
+ }), 120_000);
+ }
+
+ test('a binding whose folder leaves the checkout answers committed (fail closed): ../outside, and a sibling that shares the checkout name prefix', () => withSourceFolder('notes', async (engine, repo) => {
+ for (const relative of ['../outside', '../repo2']) {
+ mkdirSync(join(repo, relative), { recursive: true });
+ await engine.executeRaw("UPDATE persistence_source_bindings SET relative_path=$1 WHERE source_id='default'", [relative]);
+ expect(`${relative}: ${await originCommitted(engine, 'default', 'draft.md')}`).toBe(`${relative}: true`);
+ }
+ rmSync(join(repo, '..', 'outside'), { recursive: true, force: true });
+ rmSync(join(repo, '..', 'repo2'), { recursive: true, force: true });
+ }), 120_000);
+});