Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(git): hardened Git never runs the checkout's clean or process filters (W4.3)
time-attack168b656bce55
diff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 8ff74a295a..c33ee09b74 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -2,7 +2,7 @@- `src/commands/sync-diagnostics.ts` + `src/core/persistence/{sync-run,verb-errors}.ts` — bounded source/slug/path/reason diagnostics derive from immutable managed-sync receipts, including when the local failure ledger is unavailable. Direct and resident-owner JSON carry the same receipt; human memory errors lead with the specific write reason without widening frozen v1 error codes. Pending requests retain their original UUID, terminal corrections require a new UUID, and neither retry nor line-ending diagnostics bypasses raw-byte or skip guards.-- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts`, `git status --porcelain -z -- <file>` in the source root) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`.+- `src/core/persistence/reconcile*.ts` — trusted-local exact-page reconciliation: loss-preserving semantic preview, explicit JSON Pointer choices, pinned identity/revision/raw-file/policy checks, durable private preimages and same-ID replay through the existing coordinator. Normal overwrite protection stays unchanged. The bounded audit reports source-scoped drift without repair or checkpoint changes; a database-only page (`isDatabaseOnlyPage`, with no file at its slug-derived path) counts as `database_only` with no reconcile suggestion, never as drift, while a legacy row that merely lacks `source_path` is audited as usual. `src/commands/source-reconcile.ts` provides strict CLI parsing, private artifact I/O, brain routing and resident-owner delegation; the operations stay outside public MCP. Operator flow: `docs/guides/concurrent-writes.md`. Tests cover merge choices, both engines, grants, stale previews, read-only audit, and private files. A database-only page (no `source_path`, no `source_uri`; `isDatabaseOnlyPage` in `src/core/persistence/unbound-pages.ts`) is matched to the canonical file at its slug-derived path (`ReconcileState.origin: 'slug_derived'`), and apply records that path as its `source_path` (the #5254 unbound collision; `test/reconcile-unbound-collision.test.ts`). Private fact rows (#6137): `reconcile-prepare.ts` `privateFactViolation` identifies a fact row by (row number, claim), as `restoreHiddenFactRows` does. A stored non-world row carried at its identity must be unchanged; a row at no stored identity may not carry a stored private claim under another visibility, and a world row may not carry (or newly gain) a stored private row's context of 24 or more characters verbatim; sources are not compared. The `permission_denied` refusal names only the row number, with a `gbrain get` read fix. It guards verbatim copies, not reworded text. #6138: an `--auto-additive` preview classified `no_drift` asks Git (`hardened-git.ts` `hardenedPathDirty`: filter-free plumbing, never `git status`, so the checkout's clean/process filters never run; `null` when only repository config could decide) whether the canonical file differs from its last commit and returns `git_dirty`; a dirty file's `next_action` says the content agrees, the difference is only how it is written, reconcile does not commit, and names `git -C <root> diff -- <file>` (committing it is the user's decision; the managed commit path is deferred, D5). The "retry the original write" step is conditional on the preview coming from a refused write. Tests: `test/persistence-reconcile-git-dirty-6138.test.ts`.- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values.diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.mdindex 397965bf47..6c1c033a57 100644--- a/docs/architecture/key-files/persistence-stalls.md+++ b/docs/architecture/key-files/persistence-stalls.md@@ -12,4 +12,4 @@ sync-run, sync-holds, deactivation, source lifecycle) are in- `src/core/persistence/claim-phase.ts` — #6176: the phase a running write request's claim is in. `startClaimPhase`/`enterClaimPhase` keep a per-claim clock in the consumer (single and group routes); `claimPhaseStamp` is the jsonb each claim renewal stores in `persistence_requests.claim_phase` (v217), keyed to the execution token so a later claim never reads an earlier claim's ages. `claimStateOf` reads a row back as `preparing`/`publishing` (live renewal), `publication_transaction` (claim lapsed while running, read on the database clock: a transaction holds the row or the owner is gone; requeued once it ends), `file_publication` (`publication_started`; recovery finishes it) or `unrecorded`, with claim and phase ages, `resumes_on_its_own` and a `why`. `persistence.max_claim_ms` (default 600000, 60000 to 86400000; `validateMaxClaimConfigValue` is `config set`'s `invalid_params` refusal) is doctor `persistence_write_stall`'s threshold. Tests: `test/persistence-write-stall.test.ts`. Consumer and group-publish side (`consumer.ts`, `group-publish.ts`): every renewal of a single or group claim also stores `claim-phase.ts`'s stamp in the request's `claim_phase` column (v217: phase `preparing` or `publishing`, claim start, phase start and the execution token; group members get their own token), so writer status (`diagnostics.ts`, `claim` on each running blocker, never the token) and doctor `persistence_write_stall` can name a stuck phase without an extra statement per write. Tests: `test/persistence-write-stall.test.ts`.- `src/core/persistence/pre-activation-release.ts` — #6122: `preActivationClaims` lists the source bindings of a never-activated brain with their roots; `releasePreActivationClaims` (called by `deactivatePersistence` on a disabled brain once `deactivationBlockers` is empty) takes the local worktree locks, then in one transaction checks the admin state, the admin lock and that the brain is still disabled, re-runs the blockers, retires the claimed worktrees, deletes the source and host bindings and records a committed `writer_deactivate` change with `outcome.pre_activation: true`, so `cleanupRetiredManagedMarkers` clears this host's claim markers. It ensures the CLI writer registration first (a never-activated brain may have none). `sync-authority.ts` `resolveSyncPersistenceMode` refuses such a claimed source with an agent-first `writer_coordinator_required`: both choices in the suggestion, `fix` the state-bound release (`consent: ['destructive']`, so `ask_user`, with the dry run as `preview_argv`). In `deactivation.ts`: on a brain whose managed persistence was never activated, `--dry-run` reports the real `source_bindings` and each claim as `pre_activation_claims` (and `apply_command` when clean), and the state-bound run releases them through `pre-activation-release.ts`; with no claims a rerun still only cleans retired markers. Tests: `test/persistence-preactivation-claim.test.ts`. In `unbound-source.ts`: on a brain whose managed persistence is not activated, the hint offers editing the page's file plus `gbrain sync --source <id>` (and `persistence.unbound_write=database_only` where it applies) instead of the claim, and says a claim alone would block classic sync until activation or `gbrain sources writer deactivate`.- `src/core/persistence/sync-concurrent-write.ts` — #6194 (D4): `concurrentWriteProof` decides whether a managed sync import's `revision_conflict` receipt came from a concurrent database-only write. The proof is revision-linked: the page's live revision differs from the import's frozen `expected_revision`, and `pages.revision_write_request_id` names a committed non-sync request for the same source incarnation and page id (a delete or recreate of that page included; admission order is never used). `concurrentWriteHold` builds the `concurrent_write` hold (competing request id, operation and revision in `meta`; identifiers only). `sync-run.ts` `holdFailedFenceRequest` (the receipt branch) holds such a file exactly as it holds a prepare-time fence refusal; imports only (a held deletion would be re-screened at once), and without proof the failure still blocks. `sync-holds.ts` routes it (`gitHoldFix`: `gbrain sources reconcile <source> <slug> --preview`, then `sources retry-held`; `HoldRepairRoute.concurrent` from the summary's `concurrent` counter, read by `held-reads.ts`, doctor `git_held_files`, `sources retry-held` and the remote host-operator fix). Tests: `test/managed-sync-concurrent-write-hold.test.ts`.-- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`). Tests: `test/persistence-manifest-git-scope.test.ts`.+- `src/core/persistence/worktree-manifest.ts` + `src/core/hardened-git.ts` — #6099 (re-exported by `ownership.ts`): a directory that is the top of its own Git work tree is hashed in `git` scope over `git ls-files -z --cached --stage` (working-tree bytes; a tracked file missing on disk counts as deleted; gitlinks, tracked symlinks and paths resolving through a symlink refuse `writer_manifest_unsafe`; untracked non-ignored files counted as `untracked_count`, never named), so gitignored files are never opened and a clean clone verifies; anything else keeps the `tree` scope (every file but `.git`, `.gbrain-managed` and physical-root metadata, digest unchanged). Stored manifests carry `scope: 'git'` (absent = tree, every older stored manifest), and each verifier recomputes in the stored scope: transfer accept and its dry run, rebind (the new directory in the current checkout's scope; a mismatch names the first differing paths via `manifestDifferences`), clone/reclone (`hashScope` on the recovery record; `topology-recovery.ts` hashes legacy records in tree scope). A tree-scope transfer whose Git successor does not match refuses `writer_manifest_rescope_required` (re-prepare on the owner host) instead of asking for ignored files; transfer prepare reports `untracked_files` with a warning. Migration v218 drops legacy `files` maps from `persistence_worktrees.manifest` and clone recovery records. Git runs through `src/core/hardened-git.ts` (shared with `company-brain/revision.ts`); W4.3: `assertHardenedGitArgs` allows only filter-free plumbing (`rev-parse`, `ls-files`, `ls-tree`, `cat-file` without `--filters`/`--textconv`, `hash-object --no-filters`, `check-attr`, `diff-index --cached`) in both wrappers, and `hardenedPathDirty` is the `git status -- <path>` equivalent (untracked, staged incl. unborn HEAD, worktree vs index; `null` for conversion attributes, CRLF bytes, symlinks/gitlinks and exec-bit-only changes). Tests: `test/persistence-manifest-git-scope.test.ts`, `test/hardened-git-filters.test.ts`.diff --git a/src/core/company-brain/revision.ts b/src/core/company-brain/revision.tsindex 6dbddb8bb6..685ad98846 100644--- a/src/core/company-brain/revision.ts+++ b/src/core/company-brain/revision.ts@@ -4,7 +4,7 @@ import { constants, existsSync, lstatSync, openSync, fstatSync, readSync, closeSimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import type { Action } from '../agent-output.ts';import { opError } from '../ops/contract.ts';-import { HARDENED_GIT_ARGS, hardenedGitEnvironment } from '../hardened-git.ts';+import { HARDENED_GIT_ARGS, assertHardenedGitArgs, hardenedGitEnvironment } from '../hardened-git.ts';import {COMPANY_BRAIN_MAX_ENTRIES, COMPANY_BRAIN_MAX_FILE_BYTES, COMPANY_BRAIN_MAX_METADATA_BYTES,type CommittedEntry, type InspectionLimits, type RevisionIdentity, type UncommittedEntry,@@ -33,6 +33,7 @@ export function safeRepositoryPath(path: string): boolean {}async function gitRead(root: string, args: string[], maxBytes: number, onChunk?: (chunk: Buffer) => void): Promise<Buffer> {+ assertHardenedGitArgs(args);return await new Promise((accept, reject) => {const child = spawn('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],{ env: hardenedGitEnvironment(), stdio: ['ignore', 'pipe', 'pipe'] });diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.tsindex e62a0a3983..2193eedb2b 100644--- a/src/core/hardened-git.ts+++ b/src/core/hardened-git.ts@@ -7,8 +7,17 @@* maintenance. Arguments are an argv array, never a shell string. Callers* bound time and output (`company-brain/revision.ts` streams with its own* caps; `hardenedGitSync` takes a timeout and a byte cap).+ *+ * Git has no switch that turns off `filter.<driver>.clean|process` or+ * `diff.<driver>.textconv` from the repository's config, and porcelain such as+ * `status`, `diff`, `show` or `add` runs them whenever it converts working-tree+ * bytes. So only plumbing that never converts content is allowed+ * (`assertHardenedGitArgs`, wave 12 W4.3), and `hardenedPathDirty` answers+ * "is this file changed from HEAD" without `git status`.*/import { spawnSync } from 'node:child_process';+import { lstatSync } from 'node:fs';+import { join } from 'node:path';export const HARDENED_GIT_ARGS: readonly string[] = ['--no-pager', '--no-optional-locks', '--no-replace-objects','-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=/dev/null', '-c', 'core.untrackedCache=false',@@ -21,16 +30,75 @@ export function hardenedGitEnvironment(): NodeJS.ProcessEnv {GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', LC_ALL: 'C' };}-export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable' };+export type HardenedGitResult = { ok: true; stdout: Buffer } | { ok: false; reason: 'exit' | 'timeout' | 'too_large' | 'unavailable'; status?: number };++const CONVERTING_OPTIONS = new Set(['--filters', '--textconv', '--ext-diff', '-p', '--patch', '-u', '--stat', '--word-diff']);+const ALLOWED_SUBCOMMANDS = new Set(['rev-parse', 'ls-files', 'ls-tree', 'cat-file', 'hash-object', 'check-attr', 'diff-index']);++/**+ * Refuses (throws) any Git invocation that could run a repository-configured+ * clean/process filter or textconv: only the allow-listed plumbing, with+ * `hash-object` only under `--no-filters` and `diff-index` only `--cached`.+ */+export function assertHardenedGitArgs(args: readonly string[]): void {+ const sub = args[0] ?? '';+ const ok = ALLOWED_SUBCOMMANDS.has(sub) && !args.some(arg => CONVERTING_OPTIONS.has(arg) || arg.startsWith('--textconv') || arg.startsWith('--filters'))+ && (sub !== 'hash-object' || args.includes('--no-filters')) && (sub !== 'diff-index' || args.includes('--cached'));+ if (!ok) throw new Error(`hardened git refuses \`git ${args.slice(0, 2).join(' ')}\`: only filter-free plumbing may run in an untrusted checkout (see src/core/hardened-git.ts)`);+}/** Runs `git -C <root> <args>` synchronously under the hardening above, within `timeoutMs` and `maxBytes` of stdout. */export function hardenedGitSync(root: string, args: string[], limits: { timeoutMs: number; maxBytes: number }): HardenedGitResult {+ assertHardenedGitArgs(args);const run = spawnSync('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],{ env: hardenedGitEnvironment(), stdio: ['ignore', 'pipe', 'ignore'], timeout: limits.timeoutMs, maxBuffer: limits.maxBytes, killSignal: 'SIGKILL' });const code = (run.error as NodeJS.ErrnoException | undefined)?.code;if (code === 'ETIMEDOUT') return { ok: false, reason: 'timeout' };if (code === 'ENOBUFS') return { ok: false, reason: 'too_large' };if (run.error) return { ok: false, reason: 'unavailable' };- if (run.status !== 0) return { ok: false, reason: 'exit' };+ if (run.status !== 0) return { ok: false, reason: 'exit', ...(run.status === null ? {} : { status: run.status }) };return { ok: true, stdout: run.stdout };}++const PATH_LIMITS = { timeoutMs: 10_000, maxBytes: 1024 * 1024 };++/**+ * Whether `rel` (repository-relative, `/`-separated) differs from HEAD the+ * way `git status --porcelain -- <rel>` would report it, computed from+ * filter-free plumbing: untracked and not ignored, staged (index differs from+ * HEAD, or unborn HEAD), or working-tree bytes differ from the index blob.+ * `null` when Git cannot say without running repository code or reading+ * config: a conversion attribute (`filter`, `text`, `eol`,+ * `working-tree-encoding`), CRLF working-tree bytes (`core.autocrlf`), a+ * symlink or gitlink, an executable-bit-only difference (`core.filemode`), or+ * any Git failure.+ */+export function hardenedPathDirty(root: string, rel: string): boolean | null {+ const indexed = hardenedGitSync(root, ['ls-files', '-s', '--eol', '-z', '--', rel], PATH_LIMITS);+ if (!indexed.ok) return null;+ const entry = indexed.stdout.toString('utf8').split('\0')[0];+ if (!entry) {+ const untracked = hardenedGitSync(root, ['ls-files', '-z', '--others', '--exclude-standard', '--', rel], PATH_LIMITS);+ return untracked.ok ? untracked.stdout.length > 0 : null;+ }+ const [meta = '', eolInfo = ''] = entry.split('\t');+ const [mode, blob, stage] = meta.split(' ');+ const worktreeEol = eolInfo.trim().split(/\s+/)[1];+ if (!mode || !blob || !stage) return null;+ if (stage !== '0') return true;+ if (mode !== '100644' && mode !== '100755') return null;+ const head = hardenedGitSync(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], PATH_LIMITS);+ if (!head.ok) return head.reason === 'exit' && head.status === 1 ? true : null;+ const staged = hardenedGitSync(root, ['diff-index', '--cached', '--quiet', 'HEAD', '--', rel], PATH_LIMITS);+ if (!staged.ok) return staged.reason === 'exit' && staged.status === 1 ? true : null;+ const hashed = hardenedGitSync(root, ['hash-object', '--no-filters', '--', rel], PATH_LIMITS);+ if (!hashed.ok) return null;+ let executable: boolean;+ try { executable = (lstatSync(join(root, ...rel.split('/'))).mode & 0o111) !== 0; } catch { return null; }+ if (hashed.stdout.toString('utf8').trim() === blob) return executable === (mode === '100755') ? false : null;+ if (worktreeEol === 'w/crlf' || worktreeEol === 'w/mixed') return null;+ const attrs = hardenedGitSync(root, ['check-attr', '-z', 'filter', 'text', 'eol', 'working-tree-encoding', '--', rel], PATH_LIMITS);+ if (!attrs.ok) return null;+ const values = attrs.stdout.toString('utf8').split('\0').filter((_, i) => i % 3 === 2);+ return values.every(value => value === 'unspecified' || value === 'unset') ? true : null;+}diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex a3b24bfdfd..b31afbe7fe 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -1,6 +1,6 @@import { randomUUID } from 'node:crypto';-import { relative } from 'node:path';-import { hardenedGitSync } from '../hardened-git.ts';+import { relative, sep } from 'node:path';+import { hardenedPathDirty } from '../hardened-git.ts';import type { BrainEngine } from '../engine.ts';import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../config.ts';import { OperationError, opError, type OperationContext } from '../ops/contract.ts';@@ -79,10 +79,12 @@ function additiveNextAction(classification: DriftClassification, status: string,return 'Inserted text is structurally additive but can still contradict existing text. Read the inserted lines in the private preview file '+ '(or show them to the user if the page is private or the claims matter), then rerun the preview with --auto-additive --accept-suggested.';}-/** #6138: whether Git reports the canonical file as changed from its last commit; null when Git cannot say (not a Git checkout). */-function canonicalFileGitDirty(root: string, path: string): boolean | null {- const status = hardenedGitSync(root, ['status', '--porcelain', '-z', '--', relative(root, path)], { timeoutMs: 10_000, maxBytes: 1024 * 1024 });- return status.ok ? status.stdout.length > 0 : null;+/**+ * #6138: whether Git reports the canonical file as changed from its last commit; null when Git cannot say (not a Git checkout).+ * W4.3: filter-free plumbing, never `git status` (which runs the checkout's clean/process filters).+ */+export function canonicalFileGitDirty(root: string, path: string): boolean | null {+ return hardenedPathDirty(root, relative(root, path).split(sep).join('/'));}async function config(engine: BrainEngine): Promise<GBrainConfig> {return await loadConfigWithEngine(engine, loadConfig()) ?? { engine: engine.kind } as GBrainConfig;diff --git a/test/hardened-git-filters.test.ts b/test/hardened-git-filters.test.tsnew file mode 100644index 0000000000..e9c1b6304c--- /dev/null+++ b/test/hardened-git-filters.test.ts@@ -0,0 +1,135 @@+/**+ * Wave 12 W4.3: Git run in a checkout gbrain does not trust must never execute+ * the checkout's own `filter.<driver>.clean|process` config. `git status` runs+ * a clean filter whenever it re-hashes a stat-dirty file, so the reconcile+ * preview's "is the canonical file changed in Git" check uses filter-free+ * plumbing (`hardenedPathDirty`), and `hardenedGitSync` refuses everything but+ * allow-listed plumbing.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { assertHardenedGitArgs, hardenedGitSync, hardenedPathDirty } from '../src/core/hardened-git.ts';+import { canonicalFileGitDirty } from '../src/core/persistence/reconcile.ts';++const dirs: string[] = [];+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });++function git(root: string, ...args: string[]): string {+ const run = spawnSync('git', ['-C', root, ...args], { encoding: 'utf8', env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' } });+ if (run.status !== 0) throw new Error(`git ${args.join(' ')}: ${run.stderr}`);+ return run.stdout;+}++/** A committed checkout holding `note.md` (and whatever `extra` writes before the commit). */+function repo(extra?: (root: string) => void): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-hardened-git-'));+ dirs.push(root);+ git(root, 'init', '-q');+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'config', 'user.name', 'Writer Example');+ writeFileSync(join(root, 'note.md'), 'hello\n');+ extra?.(root);+ git(root, 'add', '-A');+ git(root, 'commit', '-qm', 'init');+ return root;+}++/** Make the file stat-dirty without changing its bytes, which is what makes `git status` re-hash it. */+function touch(path: string): void {+ const later = new Date(Date.now() + 5_000);+ utimesSync(path, later, later);+}++describe('W4.3: repository filters never run', () => {+ for (const kind of ['clean', 'process'] as const) {+ test(`a ${kind} filter in the checkout's .git/config is not executed by the reconcile dirty check`, () => {+ const root = repo(r => writeFileSync(join(r, '.gitattributes'), 'note.md filter=evil\n'));+ const marker = join(root, '..', `${root.split('/').pop()}-${kind}-ran`);+ git(root, 'config', `filter.evil.${kind}`, `touch ${marker}; cat`);+ touch(join(root, 'note.md'));+ const verdict = canonicalFileGitDirty(root, join(root, 'note.md'));+ expect(existsSync(marker)).toBe(false);+ expect(verdict).toBe(false);+ rmSync(marker, { force: true });+ });+ }++ test('porcelain and converting options are refused before git runs', () => {+ const root = repo();+ for (const args of [['status', '--porcelain'], ['diff'], ['show', 'HEAD'], ['add', '-A'], ['checkout', '--', '.'],+ ['hash-object', '--', 'note.md'], ['cat-file', '--filters', 'HEAD:note.md'], ['cat-file', '--textconv', 'HEAD:note.md'],+ ['diff-index', 'HEAD'], ['diff-index', '--cached', '-p', 'HEAD']]) {+ expect(() => hardenedGitSync(root, args, { timeoutMs: 5_000, maxBytes: 1024 })).toThrow(/hardened git refuses/);+ }+ expect(() => assertHardenedGitArgs(['hash-object', '--no-filters', '--', 'note.md'])).not.toThrow();+ expect(() => assertHardenedGitArgs(['diff-index', '--cached', '--quiet', 'HEAD'])).not.toThrow();+ expect(() => assertHardenedGitArgs(['ls-tree', '-r', '-z', 'HEAD'])).not.toThrow();+ });+});++describe('W4.3: hardenedPathDirty matches git status without running it', () => {+ test('unchanged, touched-only and modified files', () => {+ const root = repo();+ expect(hardenedPathDirty(root, 'note.md')).toBe(false);+ touch(join(root, 'note.md'));+ expect(hardenedPathDirty(root, 'note.md')).toBe(false);+ writeFileSync(join(root, 'note.md'), 'changed\n');+ expect(hardenedPathDirty(root, 'note.md')).toBe(true);+ });++ test('a staged change whose file equals the index but not HEAD is dirty', () => {+ const root = repo();+ writeFileSync(join(root, 'note.md'), 'staged\n');+ git(root, 'add', 'note.md');+ expect(hardenedPathDirty(root, 'note.md')).toBe(true);+ });++ test('a staged add, a staged delete kept on disk, an untracked file and an ignored file', () => {+ const root = repo(r => writeFileSync(join(r, '.gitignore'), 'ignored.md\n'));+ writeFileSync(join(root, 'added.md'), 'new\n');+ git(root, 'add', 'added.md');+ expect(hardenedPathDirty(root, 'added.md')).toBe(true);+ git(root, 'rm', '-q', '--cached', 'note.md');+ expect(hardenedPathDirty(root, 'note.md')).toBe(true);+ writeFileSync(join(root, 'loose.md'), 'loose\n');+ expect(hardenedPathDirty(root, 'loose.md')).toBe(true);+ writeFileSync(join(root, 'ignored.md'), 'ignored\n');+ expect(hardenedPathDirty(root, 'ignored.md')).toBe(false);+ });++ test('an unborn HEAD makes an indexed file dirty (it is a staged add)', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-hardened-git-unborn-'));+ dirs.push(root);+ git(root, 'init', '-q');+ writeFileSync(join(root, 'note.md'), 'hello\n');+ git(root, 'add', 'note.md');+ expect(hardenedPathDirty(root, 'note.md')).toBe(true);+ });++ test('an executable-bit-only change is unknown (core.filemode is repository config)', () => {+ const root = repo();+ chmodSync(join(root, 'note.md'), 0o755);+ expect(hardenedPathDirty(root, 'note.md')).toBeNull();+ });++ test('CRLF working-tree bytes under core.autocrlf, and a conversion attribute, are unknown rather than dirty', () => {+ const root = repo();+ git(root, 'config', 'core.autocrlf', 'true');+ writeFileSync(join(root, 'note.md'), 'hello\r\n');+ expect(hardenedPathDirty(root, 'note.md')).toBeNull();+ const lfs = repo(r => writeFileSync(join(r, '.gitattributes'), 'note.md filter=lfs diff=lfs merge=lfs -text\n'));+ writeFileSync(join(lfs, 'note.md'), 'real bytes behind a pointer\n');+ expect(hardenedPathDirty(lfs, 'note.md')).toBeNull();+ });++ test('a directory that is not a Git checkout is unknown', () => {+ const plain = mkdtempSync(join(tmpdir(), 'gbrain-hardened-git-plain-'));+ dirs.push(plain);+ mkdirSync(join(plain, 'sub'));+ writeFileSync(join(plain, 'sub', 'note.md'), 'x\n');+ expect(hardenedPathDirty(join(plain, 'sub'), 'note.md')).toBeNull();+ });+});