Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(slug): refuse colon-slug write-through on Windows, per-file sync refusal (#5032)

garrytand30ec11cf513
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index d14913a558..c101e81b55 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -141,6 +141,8 @@ jobs:
run: bun test --timeout 60000 test/frontmatter-security.test.ts test/data-frontmatter.test.ts test/authorization-boundaries.test.ts test/url-safety.test.ts test/guarded-http.test.ts
- name: Isolated TLS and proxy regressions
run: bun test --timeout 60000 test/guarded-http-tls.serial.test.ts
+ - name: Colon-slug Windows refusals and bound explicit reads (#5032, #5081)
+ run: bun test --timeout 60000 test/colon-slug-windows-5032.test.ts test/cross-lane-5081-5032.test.ts
dependency-audit:
if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index d55c4f9453..970d8341cf 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -49,7 +49,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
-- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.
+- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 827c38cec7..bf51486e41 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -15,7 +15,7 @@
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity.
+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 1b10b09aa2..1b5104169d 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -59,6 +59,7 @@ of making a duplicate.
| <a id="writer_not_quiesced"></a>`writer_not_quiesced` | `writer_not_quiesced` | Activation found an older writer, a legacy lock, or queued, running or recovering work. When work blocks it, the message names the blocking effect id, kind, source, page and request id. | Stop the writers named in the [claim and activate runbook](../architecture/topologies.md#claim-and-activate-runbook), inspect the named work with `gbrain sources writer status <source> --json`, let it finish, then retry. A committed write whose embedding effect is stuck queued or failed is settled by `gbrain repair embedding-effects --source <source>` (preview), then the same command with `--apply`; see [stale queued embedding effects](repair.md#stale-queued-embedding-effects). |
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
+| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, or an unbound source) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
### Other error codes
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index dee1654df5..dfb1e129c7 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -12,7 +12,7 @@ src/commands/extract.ts 2621 ratchet grown v0.46.26.0 megawave: FS-walk stamp sn
src/commands/jobs.ts 635 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts
src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts
src/core/ai/gateway.ts 4358 ratchet +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)
-src/commands/sync.ts 472 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary)
+src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
src/core/cycle.ts 3221 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge
src/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge
src/core/cycle/extract-atoms.ts 1802 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts)
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index 3d038144ca..63bdb9f91b 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -16,11 +16,14 @@ export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.Writ
return true;
}
-/** Informational managed-sync lines: skipped slug collisions and the links derived after the checkpoint. */
+/** Informational managed-sync lines: skipped slug collisions, refused files and the links derived after the checkpoint. */
export function printManagedSyncNotes(result: SyncResult, write: (line: string) => void): void {
for (const collision of result.slugCollisions ?? []) {
write(` Slug collision: ${collision.skipped.join(', ')} and ${collision.kept} map to ${collision.slug}; kept ${collision.kept}. Rename one file to import both.`);
}
+ for (const refusal of result.fileRefusals ?? []) {
+ write(` Refused ${refusal.code}: ${refusal.message} ${refusal.suggestion} (${refusal.docs})`);
+ }
const skips = result.legacySkips;
if (skips?.contextualMode) write(` ${skips.contextualMode} legacy file(s) skipped because they parse to the same page but have no contextual retrieval mode, which a skipped import cannot stamp; to stamp it: gbrain repair contextual-mode`);
if (skips?.canonicalBytes) write(` ${skips.canonicalBytes} legacy file(s) skipped because they parse to the same page but their bytes are not what gbrain reads back (for example, not valid UTF-8); re-save them as UTF-8 to publish them exactly.`);
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 8b8dc2915a..db97eb054a 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -49,7 +49,8 @@ export interface SyncResult {
/** #5751: unchanged managed working-tree files skipped although a no-op publication cannot resolve their admit reason. */
legacySkips?: { contextualMode: number; canonicalBytes: number };
/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */
- slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
+ slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];
+ fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
/**
* Aggregated alias/undeclared explicit-type warnings (schema.type_warnings,
* default on) — one entry per distinct non-canonical type this run.
diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.ts
index e45b023274..0a13f77b32 100644
--- a/src/commands/sync/imports.ts
+++ b/src/commands/sync/imports.ts
@@ -25,6 +25,7 @@ import {
import { isPathSafe } from '../../core/sync-git.ts';
import { resolveStallAbortSeconds, composeAbortSignals } from '../../core/sync-reconcile.ts';
import { sanitizePathForDisplay } from '../../core/sync.ts';
+import { isWindowsColonTarget } from '../../core/persistence/native-file-target.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
import { partial, markCompleted, noteTypeWarning, maybeYield } from './sync-run.ts';
import type { SyncPlan, SyncProgress, SyncRun } from './sync-run.ts';
@@ -245,6 +246,16 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
const { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress } = ctx;
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `path` is a git-diff path from the synced repo (repo content can be hostile), but the joined path is checked by isPathSafe(filePath, gitContextRoot) realpath containment below before any read
const filePath = join(syncRepoPath, path);
+ // #5032: Windows cannot store ':' in a file name (it names an alternate data
+ // stream), so the file cannot be in this checkout; a named per-file refusal
+ // instead of the silent "deleted after the pin" skip below.
+ if (isWindowsColonTarget(path)) {
+ failedFiles.push({ path, error: `colon_slug_windows_write_through: ${path} has a ':' in its name, which Windows cannot store. `
+ + `Rename it without ':' on a macOS or Linux checkout and commit, then re-run gbrain sync (docs/guides/write-refusals.md#colon_slug_windows_write_through).` });
+ progressAt.last = Date.now();
+ progress.tick(1, `skip:${path}`);
+ return;
+ }
if (!company && !existsSync(filePath)) {
// v0.42.x (#1794, Codex #3): the diff is against the PINNED target, but
// importFile reads the live working tree. A file added in lastCommit..pin
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 791729e2e2..a1300b766b 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -46,6 +46,7 @@ export type ErrorCode =
| 'unavailable' // a required dependency cannot serve (no API key, gateway down, model refusal)
| 'budget_unsatisfiable' // RESERVED in v1 — schema-listed, never returned
| 'embedding_budget_below_worst_case' // #5680: migration cap below its worst-case authorization; refused before any change
+ | 'colon_slug_windows_write_through' // #5032: a ':' file name cannot be stored on Windows; refused before admission
// eslint-disable-next-line @typescript-eslint/ban-types
| (string & {}); // OPEN union for forward-compat (eE7 / D13)
diff --git a/src/core/persistence/native-file-target.ts b/src/core/persistence/native-file-target.ts
index 3844983d15..bc73a35084 100644
--- a/src/core/persistence/native-file-target.ts
+++ b/src/core/persistence/native-file-target.ts
@@ -51,3 +51,21 @@ export function nativeFileTarget(root: string, target: string, code?: string): s
throw inaccessible();
}
}
+
+/**
+ * #5032: `:` is not a legal NTFS file-name character (Windows reads it as an
+ * alternate data stream), so a page whose canonical file name would contain
+ * one has no file on Windows. Refused rather than mangled; database-only
+ * writes of the same slug are unaffected.
+ */
+export function colonSlugWindowsRefusal(slug: string, sourceId: string): OperationError {
+ return new OperationError('colon_slug_windows_write_through',
+ `Page ${slug} has a ':' in its file name, which Windows cannot store.`,
+ `Use a slug without ':' (for example ${slug.replaceAll(':', '-')}), or write ${slug} from a macOS or Linux host that owns source ${sourceId}.`,
+ 'docs/guides/write-refusals.md#colon_slug_windows_write_through');
+}
+
+/** #5032: true when this process is on Windows and the relative file target contains `:`. */
+export function isWindowsColonTarget(relativeTarget: string): boolean {
+ return process.platform === 'win32' && relativeTarget.includes(':');
+}
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 5c91c8c081..f2b73ce502 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -19,7 +19,8 @@ import { assertPurgeParams } from './purge-params.ts';
import type { Principal } from './model.ts';
import { normalizeSubagentPageInput } from './page-input.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';
+import { isUnboundSourcePage, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';
+import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {
@@ -180,6 +181,12 @@ export async function submitPageMutation(ctx: OperationContext,
authority.databaseOnlyReason = 'unbound_source';
}
}
+ // #5032: this host publishes the canonical file, and on Windows a ':' in its
+ // name cannot be stored; refuse before admission. Database-only writes pass.
+ if (writeThrough && binding?.owner_host_id === localHostId() && isWindowsColonTarget(snapshot?.page.source_path ?? `${slug}.md`)
+ && !(snapshot && !snapshot.page.source_path && await isUnboundSourcePage(ctx.engine, sourceId, slug))) {
+ throw colonSlugWindowsRefusal(slug, sourceId);
+ }
const row = await admitWrite(ctx.engine, { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,
slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,
worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index d0d2c20ada..db123cc621 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1,7 +1,7 @@
import { isEmbedSkipped } from '../embed-skip.ts';
import { isQuarantined } from '../quarantine.ts';
import { existsSync, readFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, relative } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
@@ -28,7 +28,7 @@ import { isAutoLinkEnabled } from '../link-extraction.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './page-advisories.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { nativeFileTarget } from './native-file-target.ts';
+import { colonSlugWindowsRefusal, isWindowsColonTarget, nativeFileTarget } from './native-file-target.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
@@ -84,8 +84,10 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
// #5622: a new page captured from a file inside the source is published to that file.
const capturedPath = !snapshot && options.capture ? options.capture.path : recordedPathFromFileUri(snapshot?.page.source_uri, root);
const mode = snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, root) : undefined;
- const path = nativeFileTarget(root, resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug, mode)
- ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`)));
+ const candidate = resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug, mode)
+ ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`));
+ if (isWindowsColonTarget(relative(root, candidate))) throw colonSlugWindowsRefusal(row.slug, row.source_id);
+ const path = nativeFileTarget(root, candidate);
if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical file target is outside its registered source.');
const before = existsSync(path) ? readFileSync(path) : null;
if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 55c5a5ec8d..1557e7b0ae 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -12,6 +12,7 @@ import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { localHostId } from './identity.ts';
import { sha256 } from './digest.ts';
+import { isWindowsColonTarget } from './native-file-target.ts';
import { currentCompanyBrainSync } from '../company-brain/profile.ts';
import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
@@ -23,8 +24,10 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'
renameFrom?: SyncRename; }
/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */
export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }
+/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */
+export interface SyncFileRefusal { path: string; code: 'colon_slug_windows_write_through'; message: string; suggestion: string; docs: string; }
export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
- companyPlan?: CompanyBrainPlan; slugCollisions?: SyncSlugCollision[];
+ companyPlan?: CompanyBrainPlan; slugCollisions?: SyncSlugCollision[]; fileRefusals?: SyncFileRefusal[];
from: string | null; target: string; entries: SyncEntry[]; uncommitted?: { added: number; modified: number; deleted: number }; slugMode: 'git-root' | 'source-root'; }
export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
source: { last_commit: string | null; config: Record<string, unknown> }; }
@@ -133,8 +136,21 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;
const entries = new Map<string, SyncEntry>();
const renamedFrom = new Map<string, string>();
+ // #5032: a ':' path has no file on Windows. Each eligible one gets a named
+ // refusal and takes no part in this run, including the origin checks below.
+ const refused = new Map<string, SyncFileRefusal>();
+ const refuse = (path: string) => {
+ if (!isWindowsColonTarget(path)) return false;
+ if (eligible(path)) refused.set(path, { path, code: 'colon_slug_windows_write_through',
+ message: `${path} has a ':' in its name, which Windows cannot store; sync skipped it.`,
+ suggestion: `Rename it without ':' on a macOS or Linux checkout and commit, then run gbrain sync --source ${sourceId} --no-pull.`,
+ docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' });
+ return true;
+ };
+ const storable = <T extends { source_path: string | null }>(page: T) => page.source_path === null || !isWindowsColonTarget(page.source_path);
const put = (path: string, action: SyncEntry['action'], working = false) => {
if (process.platform === 'win32' && path.includes('\\')) throw new OperationError('page_identity_changed', 'Git paths containing literal backslashes are not safe Windows sync targets.');
+ if (refuse(path)) return;
if (eligible(path)) entries.set(path, { path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });
};
if (delta?.status === 'ok') {
@@ -143,11 +159,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
for (const rename of delta.manifest.renamed) { put(rename.from, 'delete'); put(rename.to, 'import'); renamedFrom.set(rename.to, rename.from); }
} else {
const paths = syncGit(gitRoot, ['ls-tree', '-r', '--name-only', '-z', target]).split('\0')
- .filter(path => path && (!scope || path.startsWith(`${scope}/`)));
+ .filter(path => path && (!scope || path.startsWith(`${scope}/`)) && !refuse(path));
assertDistinctSyncOrigins(paths);
const present = new Set(paths.map(path => syncOriginPath(sourcePath(path))));
for (const path of paths) put(path, 'import');
- const pages = await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
+ const pages = (await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId])).filter(storable);
assertDistinctSyncOrigins([...present, ...pages.map(page => page.source_path)]);
for (const page of pages) {
const origin = syncOriginPath(page.source_path);
@@ -177,15 +193,16 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const selected = [...entries.values()].sort((a, b) => a.action.localeCompare(b.action) || a.path.localeCompare(b.path));
if (selected.some(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path))) throw new OperationError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.');
if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw new OperationError('request_too_large', 'Sync discovery exceeds the bounded cursor size.');
- const discovered: SyncDiscovery = { binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
+ const discovered: SyncDiscovery = { ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
// Freeze all logical identities in one database statement, before yielding
// between pages. A later interactive edit must conflict with this scan.
const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string }>(
'SELECT id,slug,source_path,knowledge_revision FROM pages WHERE source_id=$1', [sourceId]);
const bySlug = new Map(identities.map(p => [p.slug, p]));
const byPath = new Map<string, typeof identities>();
- assertDistinctSyncOrigins([...selected.map(entry => entry.sourcePath), ...identities.flatMap(page => page.source_path ? [page.source_path] : [])]);
- for (const page of identities) if (page.source_path) {
+ const storableIdentities = identities.filter(storable);
+ assertDistinctSyncOrigins([...selected.map(entry => entry.sourcePath), ...storableIdentities.flatMap(page => page.source_path ? [page.source_path] : [])]);
+ for (const page of storableIdentities) if (page.source_path) {
const origin = syncOriginPath(page.source_path);
byPath.set(origin, [...(byPath.get(origin) ?? []), page]);
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index efb6707000..152ff5c6c3 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -117,6 +117,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
toCommit: cursor.authority.writer.remote ? '' : cursor.target, added: cursor.counts.added, modified: cursor.counts.modified,
deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],
...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),
+ ...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),
filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {
contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };
diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.ts
index 7db8b886ba..362347601a 100644
--- a/src/core/sync-failure-ledger.ts
+++ b/src/core/sync-failure-ledger.ts
@@ -215,6 +215,9 @@ export function classifyErrorCode(errorMsg: string): string {
// it the blocked-run breakdown also printed a bare `UNKNOWN: 1`.
if (/rename reconcile failed|RENAME_RECONCILE/i.test(errorMsg)) return 'RENAME_RECONCILE';
+ // #5032: a ':' file name on Windows (src/commands/sync/imports.ts).
+ if (/^colon_slug_windows_write_through:/.test(errorMsg)) return 'COLON_SLUG_WINDOWS_WRITE_THROUGH';
+
// SLUG_MISMATCH: thrown by importFromFile() at src/core/import-file.ts.
if (/slug.*does not match|SLUG_MISMATCH/i.test(errorMsg)) return 'SLUG_MISMATCH';
diff --git a/test/colon-slug-windows-5032.test.ts b/test/colon-slug-windows-5032.test.ts
new file mode 100644
index 0000000000..fd06924308
--- /dev/null
+++ b/test/colon-slug-windows-5032.test.ts
@@ -0,0 +1,203 @@
+/**
+ * #5032 — colon slugs (`calendar:abc`) are writable again (PR #5044's grammar,
+ * pinned in test/file-upload-security.test.ts), and on Windows, where `:` in a
+ * file name names an alternate data stream, gbrain refuses rather than mangles:
+ *
+ * - a put_page whose canonical file name would contain `:` refuses before
+ * admission with `colon_slug_windows_write_through`, naming the slug;
+ * - the same slug written database-only (no repo configured) succeeds;
+ * - the publication step refuses the same target (a write admitted on another
+ * host and published by a Windows owner);
+ * - managed sync skips each committed colon file with a named refusal and
+ * imports the rest instead of failing the run;
+ * - macOS and Linux are unchanged: the colon file is written.
+ *
+ * Off Windows the Windows cases run with `process.platform` forced to win32;
+ * on the `windows-latest` security-regressions job they run natively.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { nativeLockCapability } from '../src/core/persistence/native-lock.ts';
+import { printManagedSyncNotes } from '../src/commands/sync-diagnostics.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NATIVE_WINDOWS = process.platform === 'win32';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-5032-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const putPage = operations.find((op) => op.name === 'put_page')!;
+const CONTENT = '---\ntitle: Calendar event\ntype: note\n---\n\nA calendar event.\n';
+
+async function asWindows<T>(fn: () => Promise<T>): Promise<T> {
+ if (NATIVE_WINDOWS) return fn();
+ const original = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { ...original, value: 'win32' });
+ try { return await fn(); } finally { Object.defineProperty(process, 'platform', original); }
+}
+
+function ctxOf(engine: BrainEngine, sourceId: string): OperationContext {
+ return {
+ engine, config: { engine: engine.kind } as OperationContext['config'],
+ logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: false, sourceId,
+ };
+}
+
+async function addSource(engine: BrainEngine, root: string | null): Promise<string> {
+ const id = `c${randomUUID().replace(/-/g, '').slice(0, 20)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ return id;
+}
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-c', 'core.protectNTFS=false', '-C', root, ...args], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
+}
+
+beforeAll(async () => {
+ // Load the native writer-lock addon for the real platform before any test
+ // forces win32 (the binding is chosen by process.platform and cached).
+ await nativeLockCapability();
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('#5032 put_page with a colon slug', () => {
+ test('Windows: a write-through write refuses before admission with colon_slug_windows_write_through', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `wt-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ const error = await asWindows(() => putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT }))
+ .then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ expect((error as OperationError).toJSON()).toMatchObject({
+ error: 'colon_slug_windows_write_through',
+ message: "Page calendar:abc has a ':' in its file name, which Windows cannot store.",
+ suggestion: `Use a slug without ':' (for example calendar-abc), or write calendar:abc from a macOS or Linux host that owns source ${sourceId}.`,
+ docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through',
+ });
+ expect(await engine.getPage('calendar:abc', { sourceId })).toBeNull();
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).toEqual([]);
+ }), 60_000);
+
+ test('Windows: a database-only write of the same slug succeeds', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const sourceId = await addSource(engine, null);
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT }));
+ expect((await engine.getPage('calendar:abc', { sourceId }))?.compiled_truth).toContain('A calendar event.');
+ }), 60_000);
+
+ test('Windows: publication refuses a colon file target admitted elsewhere', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `pub-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ const binding = await claimWorktree(engine, sourceId, root);
+ const row = { source_id: sourceId, worktree_id: binding.worktree_id, slug: 'calendar:abc' };
+ await expect(asWindows(() => prepareFileTarget(engine, row, null, CONTENT))).rejects.toMatchObject({
+ code: 'colon_slug_windows_write_through',
+ });
+ expect(await prepareFileTarget(engine, { ...row, slug: 'calendar-abc' }, null, CONTENT)).toBeDefined();
+ }), 60_000);
+
+ test.skipIf(NATIVE_WINDOWS)('macOS and Linux: the colon slug is written through to its file, unchanged', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `nix-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ await putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT });
+ expect(await engine.getPage('calendar:abc', { sourceId })).not.toBeNull();
+ expect(existsSync(join(root, 'calendar:abc.md'))).toBe(true);
+ }), 60_000);
+});
+
+describe('#5032 managed sync of committed colon files on Windows', () => {
+ test('each colon file gets a named refusal; the rest import and the run completes', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const root = join(home, `sync-${randomUUID()}`); mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes', 'plain.md'), '---\ntitle: Plain\n---\nAn ordinary note.\n');
+ git(root, 'add', '-A');
+ // Commit the colon file through the index only: Windows cannot create it
+ // in a checkout, and the Windows clone this models never has it on disk.
+ const blob = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: CONTENT, encoding: 'utf8' }).trim();
+ git(root, 'update-index', '--add', '--cacheinfo', `100644,${blob},notes/calendar:abc.md`);
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'colon');
+ git(root, 'update-index', '--skip-worktree', 'notes/calendar:abc.md');
+ const head = git(root, 'rev-parse', 'HEAD');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = await addSource(engine, root);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+
+ const result = await asWindows(() => performManagedSync(engine, { sourceId, noPull: true }));
+ expect(result.status).toBe('first_sync');
+ expect(result.fileRefusals).toEqual([{
+ path: 'notes/calendar:abc.md', code: 'colon_slug_windows_write_through',
+ message: "notes/calendar:abc.md has a ':' in its name, which Windows cannot store; sync skipped it.",
+ suggestion: `Rename it without ':' on a macOS or Linux checkout and commit, then run gbrain sync --source ${sourceId} --no-pull.`,
+ docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through',
+ }]);
+ expect(await engine.getPage('notes/plain', { sourceId })).not.toBeNull();
+ const [source] = await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
+ expect(source.last_commit).toBe(head);
+ const lines: string[] = [];
+ printManagedSyncNotes(result, (line) => lines.push(line));
+ expect(lines).toContain(` Refused colon_slug_windows_write_through: ${result.fileRefusals![0].message} ${result.fileRefusals![0].suggestion} (docs/guides/write-refusals.md#colon_slug_windows_write_through)`);
+ }
+ }), 180_000);
+});
+
+describe('#5032 unmanaged incremental sync of a committed colon file on Windows', () => {
+ test('the colon file is a named per-file failure; the other files import', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ const engine = engines[0];
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try {
+ const root = join(home, `legacy-${randomUUID()}`); mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes', 'first.md'), '---\ntitle: First\n---\nThe first note.\n');
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'first');
+ const sourceId = await addSource(engine, root);
+ expect((await performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+
+ writeFileSync(join(root, 'notes', 'second.md'), '---\ntitle: Second\n---\nThe second note.\n');
+ git(root, 'add', '-A');
+ const blob = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: CONTENT, encoding: 'utf8' }).trim();
+ git(root, 'update-index', '--add', '--cacheinfo', `100644,${blob},notes/calendar:abc.md`);
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'colon');
+ git(root, 'update-index', '--skip-worktree', 'notes/calendar:abc.md');
+
+ const result = await asWindows(() => performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true }));
+ expect(result.status).toBe('blocked_by_failures');
+ expect(result.failedFiles).toBe(1);
+ expect(await engine.getPage('notes/second', { sourceId })).not.toBeNull();
+ const failure = loadSyncFailures().find((row) => row.path === 'notes/calendar:abc.md');
+ expect(failure?.error).toStartWith("colon_slug_windows_write_through: notes/calendar:abc.md has a ':' in its name");
+ expect(failure?.code).toBe('COLON_SLUG_WINDOWS_WRITE_THROUGH');
+ } finally {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ }), 120_000);
+});
diff --git a/test/cross-lane-5081-5032.test.ts b/test/cross-lane-5081-5032.test.ts
new file mode 100644
index 0000000000..d7df880f52
--- /dev/null
+++ b/test/cross-lane-5081-5032.test.ts
@@ -0,0 +1,96 @@
+/**
+ * ENG-O14 cross-lane journey: #5081 with #5032. A stdio connection bound by
+ * GBRAIN_SOURCE=work reads a colon-slug page from a federated source by naming
+ * it (#5081), still cannot write into that source (read admission confers no
+ * write right), and its own colon-slug writes follow #5032: refused before
+ * admission on Windows when the write source writes through to files,
+ * database-only writes succeed, and macOS and Linux are unchanged.
+ *
+ * Off Windows the Windows case runs with `process.platform` forced to win32;
+ * on the windows-latest security-regressions job it runs natively.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { nativeLockCapability } from '../src/core/persistence/native-lock.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import { resolveMcpStdioSourceScope } from '../src/mcp/server.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NATIVE_WINDOWS = process.platform === 'win32';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-5081-5032-'));
+const workRoot = join(home, 'work');
+let engine: PGLiteEngine;
+const PAGE = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${title} body.\n`;
+
+async function asWindows<T>(fn: () => Promise<T>): Promise<T> {
+ if (NATIVE_WINDOWS) return fn();
+ const original = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { ...original, value: 'win32' });
+ try { return await fn(); } finally { Object.defineProperty(process, 'platform', original); }
+}
+
+async function boundOpts(): Promise<DispatchOpts> {
+ const scope = await withEnv({ GBRAIN_SOURCE: 'work' }, () => resolveMcpStdioSourceScope(engine, home));
+ return {
+ remote: true, transport: 'stdio', takesHoldersAllowList: ['world'], sourceId: scope.sourceId,
+ ...(scope.explicitReadBinding ? { explicitReadBinding: scope.explicitReadBinding } : {}),
+ };
+}
+
+async function call(name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(engine, name, params, await boundOpts());
+ return { isError: result.isError === true, body: JSON.parse(result.content[0].text) };
+}
+
+beforeAll(async () => {
+ await nativeLockCapability();
+ mkdirSync(workRoot);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('work', 'work', $1, '{}'::jsonb)`, [workRoot]);
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('notes', 'notes', NULL, '{"federated": true}'::jsonb)`);
+ const seeded = await importFromContent(engine, 'calendar:standup', PAGE('Standup'), { sourceId: 'notes', noEmbed: true });
+ expect(seeded.status).toBe('imported');
+}, 60_000);
+
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('ENG-O14 #5081 + #5032', () => {
+ test('the bound connection reads a federated colon-slug page by naming its source', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError, body } = await call('get_page', { slug: 'calendar:standup', source_id: 'notes' });
+ expect(isError).toBe(false);
+ expect(body.source_id).toBe('notes');
+ expect((await call('get_page', { slug: 'calendar:standup' })).isError).toBe(true);
+ }));
+
+ test('read admission confers no write right into the admitted source', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError, body } = await call('put_page', { slug: 'calendar:retro', content: PAGE('Retro'), source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.error).toBe('permission_denied');
+ expect(await engine.getPage('calendar:retro', { sourceId: 'notes' })).toBeNull();
+ }));
+
+ test('Windows: a colon-slug write into the write-through bound source is refused before admission', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError, body } = await asWindows(() => call('put_page', { slug: 'calendar:planning', content: PAGE('Planning') }));
+ expect(isError).toBe(true);
+ expect(body.error).toBe('colon_slug_windows_write_through');
+ expect(body.docs).toBe('docs/guides/write-refusals.md#colon_slug_windows_write_through');
+ expect(await engine.getPage('calendar:planning', { sourceId: 'work' })).toBeNull();
+ }));
+
+ test.skipIf(NATIVE_WINDOWS)('macOS and Linux: the same write lands in the bound source and its file', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError } = await call('put_page', { slug: 'calendar:planning', content: PAGE('Planning') });
+ expect(isError).toBe(false);
+ expect(await engine.getPage('calendar:planning', { sourceId: 'work' })).not.toBeNull();
+ expect(existsSync(join(workRoot, 'calendar:planning.md'))).toBe(true);
+ }));
+});