Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs: fs-durable key-file entry, durable-flush guard, Windows recovery note
garrytanbac07b434397
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex f466558198..6cfd10d0c3 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -1003,7 +1003,7 @@ per-file rules. They do not cache passing results. Candidate scanner failuresfail the guard, and matching files retain the same allowlists and diagnostics.`scripts/guards-manifest.tsv` is THE single registry of `scripts/check-*`-guards (currently 67), each classified `scanner` (greps/parses repo sources —+guards (currently 68), each classified `scanner` (greps/parses repo sources —must eventually carry fixtures), `buildfresh`, or `repostate` (build/freshnessguards are exempt-with-reason, not fixture-tested).`scripts/guard-self-test.sh` (`bun run check:guard-self-test`, wired into@@ -1043,6 +1043,30 @@ and the `Migration` type in `schema-migrations/types.ts`. Fixtures:`test/fixtures/guards/check-layering.ts/`; forms are driven in`test/scripts/layering.test.ts`.+#### Durable-flush guard++`scripts/check-durable-flush.ts` (`bun run check:durable-flush`, in+`bun run verify`) fails on an `fsyncSync(fd)` anywhere in `src/` outside+`src/core/fs-durable.ts` whose `fd` is assigned from a read-only `openSync`+(flags omitted, a flag string without `w`/`a`/`+`, or `O_RDONLY` without+`O_WRONLY`/`O_RDWR`), file or directory, and on one whose flags it cannot+read. Windows refuses fsync on a read-only handle and has no directory flush+(EPERM), which wedged the managed write queue (#5595) and every skill-bundle+publication (#5475). Flushes of descriptors opened for writing pass. Each+failure prints `FAIL [durable_flush_read_handle]: <file>:<line>`, the open it+traced, a `Fix:` line and this anchor. Fix: fsync the descriptor you wrote+through before closing it (set its final mode with `fchmodSync(fd)` first), or+call `flushFile(path)` / `flushDirectory(path, { bestEffort? })` from+`src/core/fs-durable.ts`. A file that cannot migrate yet goes in the guard's+`ALLOWLIST` with a reason (today only `src/core/binary-self-update.ts`, owned+by the self-upgrade wave); an entry whose file no longer needs it fails as+`durable_flush_stale_allowlist`. Fixtures:+`test/fixtures/guards/check-durable-flush.ts/`; forms are driven in+`test/scripts/durable-flush-guard.test.ts`. The helper and the #5595/#5475+regressions run natively on the `windows-latest` row of the test.yml+`security-regressions` job; `test/helpers/win32-flush-semantics.ts` makes them+discriminate on POSIX hosts too.+#### Engine-sql ratchet`scripts/check-engine-sql-ratchet.ts` (`bun run check:engine-sql-ratchet`, indiff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex 16bab898bd..399733b315 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -124,7 +124,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.-- `src/cli.ts` strict flag validation + `src/core/cli-flag-registry.generated.ts` + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — its `src/cli/commands/` module and pipeline branches + imported modules + one level of relative imports + `EXTRA_FLAGS`; deliberately over-inclusive, help-text mentions count, but `//` and `/* */` comments are stripped at every depth before the scan — a helper's doc comment naming `--fresh` must not legalise it for a command that only imports one function from that helper; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. `parseOpArgs` also refuses to let a non-boolean flag swallow a token that is itself a known flag of the same command (op-contract param, a CLI-local, or the `--no-<boolean>` form): `gbrain put x --content --source default` fails with `--content requires a value, but '--source' is a flag; omit --content (or put it last) to read stdin` (exit 1, pre-write) instead of storing the literal `--source` as the page body. A value that merely starts with `--` but names no flag of this command stays a value; the shared `isKnownOpFlag` predicate (`src/core/op-flag-tokens.ts`) sits next to `isBooleanLiteral` so parser and validator cannot disagree. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it. The generator segments `handleCliOnly` into per-command text blocks with `segmentDispatchBlocks`: both `case 'X':` labels and every `if (command === 'X' …)` head — plain, compound (`&& args[0] === 'sub'`: the no-DB `eval <sub>` bypasses such as `eval longmemeval`, the `<cmd> --help` pre-engine branches, `agent register`) and multi-line — are markers, and ownership follows the `command === 'X'` head, never the condition's tail, so a compound block's flags land on its own command's row (the `eval` row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare `command === 'X'` inside a non-`if` expression is deliberately not a marker. Only `import('./commands/*.ts')` inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and `isValueOnlyImport` skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by `test/generate-flag-registry.test.ts` (acceptance AND rejection: `--frobnicate` is still refused) and `test/eval-longmemeval-cli-smoke.test.ts` (the documented `gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only` invocation exits 0 as a subprocess).+- `src/cli.ts` strict flag validation + `src/core/cli-flag-registry.generated.ts` + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — its `src/cli/commands/` module and pipeline branches + imported modules + one level of relative imports + `EXTRA_FLAGS` + `DELEGATED_MODULES`, the modules a command hands its argv to through a nested handler (auth → `persistence-admin.ts` and `grants/cli.ts`), scanned at module depth without their imports so their safety-flag reads count as consumption; deliberately over-inclusive, help-text mentions count, but `//` and `/* */` comments are stripped at every depth before the scan — a helper's doc comment naming `--fresh` must not legalise it for a command that only imports one function from that helper; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. `parseOpArgs` also refuses to let a non-boolean flag swallow a token that is itself a known flag of the same command (op-contract param, a CLI-local, or the `--no-<boolean>` form): `gbrain put x --content --source default` fails with `--content requires a value, but '--source' is a flag; omit --content (or put it last) to read stdin` (exit 1, pre-write) instead of storing the literal `--source` as the page body. A value that merely starts with `--` but names no flag of this command stays a value; the shared `isKnownOpFlag` predicate (`src/core/op-flag-tokens.ts`) sits next to `isBooleanLiteral` so parser and validator cannot disagree. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it. The generator segments `handleCliOnly` into per-command text blocks with `segmentDispatchBlocks`: both `case 'X':` labels and every `if (command === 'X' …)` head — plain, compound (`&& args[0] === 'sub'`: the no-DB `eval <sub>` bypasses such as `eval longmemeval`, the `<cmd> --help` pre-engine branches, `agent register`) and multi-line — are markers, and ownership follows the `command === 'X'` head, never the condition's tail, so a compound block's flags land on its own command's row (the `eval` row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare `command === 'X'` inside a non-`if` expression is deliberately not a marker. Only `import('./commands/*.ts')` inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and `isValueOnlyImport` skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by `test/generate-flag-registry.test.ts` (acceptance AND rejection: `--frobnicate` is still refused) and `test/eval-longmemeval-cli-smoke.test.ts` (the documented `gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only` invocation exits 0 as a subprocess).- `src/schema.sql` — Full Postgres + pgvector DDL: canonical for every table except the TS fragment tables, whose `BEGIN/END GENERATED` regions are rewritten from the fragment modules; `bun run build:schema` derives schema-embedded.generated.ts and the PGLite template from it (`docs/ENGINES.md#canonical-schema-sources`)diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.mdindex 4c9f4b69bc..2240958348 100644--- a/docs/architecture/key-files/schema-mutation.md+++ b/docs/architecture/key-files/schema-mutation.md@@ -7,7 +7,8 @@ stats/sync data plane + CLI verbs + MCP ops + a first-class agent skill.Key files:- `src/core/persistence/staging.ts` — journaled same-directory staging descriptors reserve names, expected sizes and full hashes before any sink. Owner-locked recovery removes only known complete regular files; partial/unexpected bytes keep the root and recovery quota blocked, including committed receipt cleanup. Legacy records acquire durable staging descriptors before any new restoration. Final accounting requires verified absence and parent-directory durability. A regular-file ancestor proves an uncreated staging leaf is absent; recovery flushes the containing directory and settles the storage failure without deleting that ancestor or retaining a false recovery fence. Tests: `atomic-write.test.ts`, `persistence-staging.test.ts`, and eight-boundary process-crash harness.-- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique tmp sibling (`.tmp.<pid>.<rand>`) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → best-effort parent-directory fsync (rename durability). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.+- `src/core/fs-durable.ts` — the shared durable-flush leaf (imports only `node:fs`). `flushFile(path)` fsyncs a file nobody holds open through `'r+'` on win32 (Windows `FlushFileBuffers` needs write access) and `'r'` elsewhere (a 0444 file stays flushable); a read-only file on win32 cannot be opened writable and is left to the OS. `flushDirectory(path, { bestEffort })` is strict by default: every error propagates except the win32 no-directory-flush codes (`EISDIR`/`EPERM`/`EINVAL`/`ENOTSUP`), a non-directory path fails `ENOTDIR`, and `bestEffort` swallows everything. `sameFileMode(actual, expected)` compares every permission bit on POSIX and only the owner write bit on win32, whose stat reports 0444/0666. A writer that still holds its descriptor sets the mode with `fchmodSync(fd)` and fsyncs that descriptor instead (atomic-write, skill-bundle staging). Callers: atomic-write, the persistence coordinator, identity, root registry, physical-root records, reconcile backups, recovery staging, topology checkouts (`flushTopologyDirectory` re-export, `flushTopologyTree`), skill bundles, agent-install state (`syncDirectory` re-export), `sources reconcile` previews and attendance-repair checkpoints. `scripts/check-durable-flush.ts` keeps new read-handle flushes out of `src/` (docs/TESTING.md#durable-flush-guard). Tests: `test/fs-durable.test.ts`, `test/persistence-windows-flush-5595.test.ts`, `test/bundle-files-windows-5475.test.ts`, `test/init-packaged-skills-native.test.ts`, run natively on windows-latest in the test.yml security-regressions job.+- `src/core/atomic-write.ts` — the shared atomic file writer for brain-repo markdown writers: unique tmp sibling (`.tmp.<pid>.<rand>`) → write loop until every byte lands (writeSync may legally short-write under disk pressure; a silent short write could atomically install truncated content) → fsync → close → synchronous staging boundary → optional `verify(onDiskBytes)` callback (throw = abort, tmp removed, target untouched) → atomic rename → parent-directory fsync through `fs-durable.ts` `flushDirectory` (rename durability; strict under `durable`, the journaled-publication flag, best-effort otherwise). The stage is opened with its final mode and `fchmod`-ed on the descriptor past the umask before any byte is written: `AtomicWriteOpts.mode` sets exact bits and reasserts them over an existing target's mode (a legacy 0644 file tightens on its next write); omitted, the target's existing mode is preserved, else 0644 & ~umask. `mkdirPrivate(dir, root = dir)` creates gbrain-private directories: a missing `root` gets default-permission ancestors and is itself made exactly 0700, each missing directory between `root` and `dir` is created 0700 (`O_NOFOLLOW` fchmod), and a directory that already exists, possibly one the user chose, is never chmod-ed; `dir` outside `root` throws. Consumers of the private modes: the Google connector (`google-source.ts`, `sources-ops.ts` Google add) and the persistence coordinator's Google publication. Consumed by `src/commands/backlinks.ts` (which verifies with `parseMarkdown({validate:true})` before the rename). Rename prevents torn writes, NOT lost updates — read-modify-write callers pair it with `withPageLock` (backlinks does). Unifying the per-module copies (skillopt/apply-edits, write-through, lint) is a filed TODO.- `src/core/schema-pack/pack-lock.ts` — Atomic `O_CREAT|O_EXCL` per-pack lock. DELIBERATELY NOT the `existsSync + writeFileSync` TOCTOU shape from `src/core/page-lock.ts`. Default 60s TTL, refresh every 10s while `withPackLock(fn)` runs, `--force` semantics = "steal stale lock" NOT "skip locking." Lock path per-pack so two packs never block each other.- `src/core/schema-pack/write-vocabulary.ts` — write-time pack-vocabulary enforcement shared by the write surfaces (capture op, `add_link` op, `gbrain capture` CLI). `loadActivePackForWriteVocabulary(ctx)` pairs the engine's DB-plane `schema_pack` key with FILE-ONLY config (the `loadActivePackForLocalEngine` posture) while threading `remote` (fail-closed: anything not strictly false is remote) + `sourceId`; NEVER throws — null means "no resolvable pack", which callers MUST treat as "no vocabulary to enforce" (the write proceeds exactly as before). `packDeclaresPageType`/`packDeclaresLinkType` + message/suggestion formatters reject an EXPLICIT undeclared name with the pack's declared vocabulary in the error so agents self-correct without a `gbrain schema explain` round-trip. The DEFAULT `note` path is never checked here — callers validate EXPLICIT names only, so bare `gbrain capture` works under a pack that doesn't declare `note`. `loadActivePackForWriteVocabulary` also swallows a rejecting `getConfig`; `previewNames` bounds the vocabulary preview in the error (the first 12 names + `(N total)`). Pinned by `test/write-vocabulary.test.ts`.- `src/core/schema-pack/mutate-audit.ts` — ISO-week JSONL at `~/.gbrain/audit/schema-mutations-YYYY-Www.jsonl`. Privacy-redacted: type names → sha8, prefixes → first slug segment only, matches `candidate-audit.ts` privacy posture. Logs BOTH success AND failure events so a future `schema_pack_writability` doctor check has signal. `summarizeMutations()` is the cross-surface parity primitive.diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 321370c939..4910616803 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -201,6 +201,14 @@ and do not disable guards or change ownership as part of rollback.| `failed` | The request ended without commitment. || `cancelled` | Cancelled before publication began. |+On Windows, publication flushes each staged file through the handle it was+written with and skips the directory flush Windows does not provide. Older+releases flushed through a read-only handle, which Windows refuses (`EPERM`), so+a restoration could stay `recovering` and hold every later write on that source+behind it. After upgrading, the owner retries it on its own; confirm with+`gbrain doctor --json` (`canonical_content_writes` reports `ok` once recovery+has drained).+Receipts include `request_id`, `state`, and `retry_after_ms`, with optionalrevision, outcome, persistence status, and timestamps. Terminal receipts have`retry_after_ms: null`. Private queued content, credential hashes, and recovery