Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/fix-wave-10-c

time-attack59012042a16f
diff --cc docs/architecture/key-files/commands-4.md
index 72cff6c4bc,f7fd79313a..14f15c7ad8
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@@ -20,7 -20,7 +20,7 @@@ Current behavior and load-bearing invar
- `src/commands/jobs.ts:refreshGatewayForJob` + `src/core/ai/gateway.ts:refreshGatewayEnvFromFilePlane` — long-lived-worker staleness boundary, three tiers: (1) DB-plane model config re-resolves per gateway-refresh job (`reconfigureGatewayWithEngine`); (2) FILE-plane config (`~/.gbrain/config.json`, incl. provider API keys) re-folds per job via the env-ONLY `refreshGatewayEnvFromFilePlane` — never a full `configureGateway(buildGatewayConfig(loadConfig()))`, which would clobber DB-plane-merged fields (base_urls, chat options) with file-plane-only values; (3) true process env vars are fixed at worker start and need a restart. `gbrain config set *_api_key` writes the DB plane, which `loadConfigWithEngine()` deliberately never merges for key fields — those writes do NOT reach workers (TODO filed to reroute them to the file plane). `facts-absorb` sits in `GATEWAY_REFRESH_JOB_NAMES`; its handler converts execution-time `chat_unavailable` in a KEYED worker into a typed retryable failure (`factsAbsorbShouldRetry`) while a keyless worker defers it (`JobDeferredError`, 30 min, no attempt counted) so the backlog runs once a key exists. Pinned by `test/jobs-gateway-refresh.serial.test.ts`.
- - `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file. It reads the page revision before the bytes it repairs, checks them with the coordinator's canonical predicate (`fileMatchesSnapshot`, so formatting differences are not divergence) and submits against that revision. A repair that must wait (no indexed page, a file that diverged from the database, a held or removed file, a publication mid-scan) is a non-fixable `managed-write-pending` issue with `code: 'managed_write_pending'`, a `reason` (the coordinator refusal's detail, `held_file`, `canonical_file_missing`, `revision_changed`, `not_indexed`), the refusal's own rendered `fix` (never a sync) and the guide link; the run continues (`LintResult.write_path` / `fix_pending` / `pending_issues`, first 50; #5180, `test/managed-lint.test.ts` on both engines). `llm-preamble` matches only a leading run at a body start (file top, after leading frontmatter, or after a whole-page ```markdown wrapper), and repair removes only that run, so a later line that begins like a preamble is never flagged or deleted. A filesystem fix write refused with EACCES/EPERM/EROFS leaves the file unchanged and becomes a non-fixable `fix-not-writable` issue (`code: 'fix_not_writable'`, the errno as `reason`, a user `fix` naming the permission change or `--exclude`) counted in `fix_pending`; the run continues (`test/lint-preamble-anchor.test.ts`).
-- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file. It reads the page revision before the bytes it repairs, checks them with the coordinator's canonical predicate (`fileMatchesSnapshot`, so formatting differences are not divergence) and submits against that revision. A repair that must wait (no indexed page, a file that diverged from the database, a held or removed file, a publication mid-scan) is a non-fixable `managed-write-pending` issue with `code: 'managed_write_pending'`, a `reason` (the coordinator refusal's detail, `held_file`, `canonical_file_missing`, `revision_changed`, `not_indexed`), the refusal's own rendered `fix` (never a sync) and the guide link; the run continues (`LintResult.write_path` / `fix_pending` / `pending_issues`, first 50; #5180, `test/managed-lint.test.ts` on both engines). A file the scan listed that is gone by its scan read (ENOENT only; other read errors still fail the run) is reported instead of aborting: a managed `--fix` run asks the coordinator (pending `canonical_file_missing`), otherwise a non-fixable `file-removed-during-scan` issue with code `file_removed_during_scan` and a `gbrain lint <target>` fix; the CLI prints each issue's `Fix:` command and `Docs:` link (`test/lint-file-removed-during-scan.test.ts`).
++- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions. On a managed brain (persistence enabled) `runLintCore` skips the legacy filesystem lock and publishes each repair through the persistence coordinator (`maintenancePreflight` + `publishMaintenancePage`: DB row and worktree file in one guarded write) instead of writing the file. It reads the page revision before the bytes it repairs, checks them with the coordinator's canonical predicate (`fileMatchesSnapshot`, so formatting differences are not divergence) and submits against that revision. A repair that must wait (no indexed page, a file that diverged from the database, a held or removed file, a publication mid-scan) is a non-fixable `managed-write-pending` issue with `code: 'managed_write_pending'`, a `reason` (the coordinator refusal's detail, `held_file`, `canonical_file_missing`, `revision_changed`, `not_indexed`), the refusal's own rendered `fix` (never a sync) and the guide link; the run continues (`LintResult.write_path` / `fix_pending` / `pending_issues`, first 50; #5180, `test/managed-lint.test.ts` on both engines). A file the scan listed that is gone by its scan read (ENOENT only; other read errors still fail the run) is reported instead of aborting: a managed `--fix` run asks the coordinator (pending `canonical_file_missing`), otherwise a non-fixable `file-removed-during-scan` issue with code `file_removed_during_scan` and a `gbrain lint <target>` fix; the CLI prints each issue's `Fix:` command and `Docs:` link (`test/lint-file-removed-during-scan.test.ts`). `llm-preamble` matches only a leading run at a body start (file top, after leading frontmatter, or after a whole-page ```markdown wrapper), and repair removes only that run, so a later line that begins like a preamble is never flagged or deleted. A filesystem fix write refused with EACCES/EPERM/EROFS leaves the file unchanged and becomes a non-fixable `fix-not-writable` issue (`code: 'fix_not_writable'`, the errno as `reason`, a user `fix` naming the permission change or `--exclude`) counted in `fix_pending`; the run continues (`test/lint-preamble-anchor.test.ts`).
- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.
diff --cc docs/architecture/key-files/core-ai.md
index 225a47d511,a3cb70f213..da8ead5de6
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@@ -3,9 -3,10 +3,11 @@@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, re-exported by `src/cli.ts`. Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Delegates the file-plane API-key fold + env merge to `mergedProviderEnv` (`src/core/ai/provider-env.ts`); keeps ownership of threading local-server `*_BASE_URL` env vars into base_urls. `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
+- `src/core/ai/build-gateway-config.ts` — `buildGatewayConfig(c: GBrainConfig): AIGatewayConfig`, re-exported by `src/cli.ts`. Lets core modules (`init-embed-check.ts`) reuse it without importing the CLI entrypoint. Delegates the file-plane API-key fold + env merge to `mergedProviderEnv` (`src/core/ai/provider-env.ts`); keeps ownership of threading local-server `*_BASE_URL` env vars into base_urls (`COMPAT_BASE_URL_ENVS`, the one table `providers env` also reads to label an env-var URL). `process.env` wins EXCEPT empty-string / undefined values are dropped before the merge, so an injected empty `ANTHROPIC_API_KEY=''` (Claude Code neuters subprocess LLM calls this way) can't clobber a valid config-plane key; `'0'` / `'false'` are preserved. Pinned by `test/ai/build-gateway-config.test.ts`.
+- `src/core/ai/db-plane-config-read.ts` — `readDbPlaneConfig(fileCfg)`: best-effort DB-plane config read for engine-free diagnostics (`providers env`). Returns the `loadConfigWithEngine` merge or why it was not read: no brain configured, a thin client, a PGLite lock already held (never waited out), or an open failure. Always disconnects.
+ - `src/core/ai/call-log.ts` + the observer half of `src/core/ai/invocation-guard.ts` — invocation observers and attribution. `observeAIInvocations(observer)` registers a process-level observer that `invokeAI` notifies once per call (guarded or not) with `{ call, outcome: ok | error | refused, usage, startedAt, ms, attribution }`; the unguarded branch of `guarded-generation.ts` routes through `invokeAI` only while an observer is installed and passes the caller's transport options unchanged, so observation never alters retries, token defaults or admission (pinned by `test/ai-invocation-observer.test.ts`). Observer throws are swallowed and counted (`aiInvocationObserverFailures`); adding the same function twice is a no-op. `withAIAttribution({ request_id, effect, job_id, job_name, phase }, fn)` merges into an async-local attribution read by observers: the persistence effect dispatcher (`effects.ts`), the in-process facts queue (`facts/queue.ts`, captured per entry at enqueue), the `facts-absorb` job handler (internal write-request id from `persistence_request_id`) and `timeContainedPhase` (`cycle:<phase>`) set it. `installAICallLogFromEnv` (called by `configureGateway`, idempotent per path) appends one JSON line per call to `GBRAIN_AI_CALL_LOG` (kind with multimodal counted as embedding, operation, model, outcome, ms, input/output/cache tokens or `unknown`, attribution; never prompt or response text; one warning on write failure). Pinned by `test/ai-call-log.test.ts`.
+
- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. `withChatCallMeter` counts successful calls on a `ChatCallMeter` (phase containment's `{ calls }`); a meter that declares `cost_usd` (the nightly probe's) also prices each call with the budget tracker's resolver (`priceFor` with the meter's `pricing_overrides`; a table row uses the same cache-aware `estimateChatCostUsd` value the record carries), counts an unpriced call in `unpriced_calls` instead of as 0, and is priced even when no sink is registered. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.
- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-2.5` is the runtime/mode-bundle reranker default. `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.
diff --cc src/commands/lint.ts
index b7f83c1cec,2f41aa98c7..fc73cc6e4c
--- a/src/commands/lint.ts
+++ b/src/commands/lint.ts
@@@ -51,11 -52,11 +52,11 @@@ export interface LintIssue
rule: string;
message: string;
fixable: boolean;
- /** A repair that was not applied: `managed_write_pending` (a managed brain's coordinator) or `fix_not_writable` (the file refused the write). */
- code?: 'managed_write_pending' | 'fix_not_writable';
- /** The stable machine code: a managed-brain repair that waits, or a listed file removed before lint read it. */
- code?: 'managed_write_pending' | 'file_removed_during_scan';
- /** Why it waits: the coordinator refusal's reason (`file_database_drift`, `held_file`, `canonical_file_missing`, ...), `revision_changed` or `not_indexed`. */
++ /** The stable machine code: a repair that was not applied (`managed_write_pending` from a managed brain's coordinator, `fix_not_writable` when the file refused the write), or a listed file removed before lint read it (`file_removed_during_scan`). */
++ code?: 'managed_write_pending' | 'fix_not_writable' | 'file_removed_during_scan';
+ /** Why: the coordinator refusal's reason (`file_database_drift`, `held_file`, `canonical_file_missing`, ...), `revision_changed`, `not_indexed`, or the lowercased errno (`eacces`, `eperm`, `erofs`). */
reason?: string;
- /** The coordinator refusal's own next step, rendered for the CLI; lint never adds one of its own. */
+ /** The next step, rendered for the CLI: the coordinator refusal's own fix, or the owner's permission fix. */
fix?: RenderedAction;
docs?: string;
}
@@@ -629,32 -605,15 +630,41 @@@ function pendingIssue(file: string, slu
...(envelope?.fix ? { fix: envelope.fix } : {}), docs: docsUrl(MANAGED_LINT_DOCS) };
}
+ /** A file the scan listed was gone by its scan read (deleted or renamed concurrently); the rest of the run continues. */
+ function removedDuringScanIssue(file: string, target: string): LintIssue {
+ return { file, line: 1, rule: 'file-removed-during-scan', fixable: false, code: 'file_removed_during_scan',
+ message: `${file} was removed after lint listed it and before lint read it, so it was not linted. Re-run lint to check the files that exist now.`,
+ fix: renderAction({ argv: ['gbrain', 'lint', target], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Lists the tree again and lints the files present now.' }, cliRenderContext()),
+ docs: docsUrl(ERROR_CATALOGUE.file_removed_during_scan.docs) };
+ }
+
+const UNWRITABLE_CODES: ReadonlySet<string> = new Set(['EACCES', 'EPERM', 'EROFS']);
+
+/**
+ * Write one filesystem lint fix. A file the process may not write (EACCES,
+ * EPERM, EROFS: permissions or a read-only mount) is left unchanged and
+ * returned as a non-fixable `fix-not-writable` issue so the rest of the tree
+ * is still linted; any other write error propagates.
+ */
+function writeLintFixOrRefusal(page: string, relPath: string, fixed: string): LintIssue | null {
+ try {
+ writeSourceFileSync(page, fixed);
+ return null;
+ } catch (e) {
+ const errno = (e as NodeJS.ErrnoException | null)?.code;
+ if (typeof errno !== 'string' || !UNWRITABLE_CODES.has(errno)) throw e;
+ const envelope = toAgentError(opError('storage_error', `fix not applied: ${relPath} is not writable (${errno}); the file was left unchanged.`,
+ 'Make the file writable by the user running gbrain, or pass its directory or file name to `gbrain lint --exclude`, then lint again.', {
+ why: 'Lint repairs files in place, and this file refused the write (its permissions or a read-only mount).',
+ fix: { consent: [], actor: 'user', requires_exclusive: false, why: 'Only the file owner can change its permissions or mount.',
+ user_message: `Make ${relPath} writable for gbrain, or exclude it from lint.` },
+ }), { transport: 'cli', command: 'lint', render: cliRenderContext() });
+ return { file: relPath, line: 1, rule: 'fix-not-writable', fixable: false, code: 'fix_not_writable', reason: errno.toLowerCase(),
+ message: envelope.message, ...(envelope.fix ? { fix: envelope.fix } : {}) };
+ }
+}
+
function refusalReason(error: OperationError): string {
if (error.code === 'revision_conflict') return 'revision_changed';
if (heldFileDiagnostic(error.message)) return 'held_file';