Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(slugs): refuse new hyphen-run slugs at put_page/capture; doctor slug_path_mismatch (#7305)
garrytan295c8e32fff9
diff --git a/docs/architecture/key-files/page-identity-and-administration.md b/docs/architecture/key-files/page-identity-and-administration.mdindex a392079374..afbbb0a566 100644--- a/docs/architecture/key-files/page-identity-and-administration.md+++ b/docs/architecture/key-files/page-identity-and-administration.md@@ -79,6 +79,7 @@ upgrade consequence and engine parity respectively.## Suffixed slugs-- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. The same admission refuses a NEW slug with a Windows reserved device segment or a segment over 240 bytes (`slug_not_portable`, suggestion from `portable-slug.ts`); a live page with that slug still updates and gets a `slug_advisory` naming the move. `:` stays valid slug grammar. `validateSlug` and path-derived import slugs are unchanged. Tests: `test/ingestion/put-page-write-through.test.ts`, `test/pathological/b5-export-unsafe-slugs.test.ts`, `test/pathological/b12-slug-segment-bytes.test.ts`.+- `src/core/persistence/suffixed-slug.ts` — `.md`/`.mdx`-suffixed slugs (#4807). `preparePageAdmission` refuses a new put_page/put_pages slug ending in `.md`/`.mdx` before any journal row (`invalid_params`, why, suggestion naming the bare slug, read-only `get_page` fix and verify); a live page with that exact (source_id, slug) still updates and the put_page response carries `slug_advisory` (put under the bare slug, then delete_page). `suffixedSlugDryRun` serves put_page dry runs; `suffixedFrontmatterSlugHold` holds a file import whose frontmatter `slug:` identity ends in `.md` as `frontmatter_slug_conflict`. The same admission refuses a NEW slug with a Windows reserved device segment or a segment over 240 bytes (`slug_not_portable`, suggestion from `portable-slug.ts`); a live page with that slug still updates and gets a `slug_advisory` naming the move. `:` stays valid slug grammar. #7305: put_page and capture (the `operation` argument; capture checks only this rule) refuse a NEW slug that `sync.ts` `hyphenFoldedSlug` changes (a hyphen run or a segment-final hyphen, which slugifySegment folds) with detail `slug_hyphen_run` and the folded slug as suggestion and read-only fix; a live exact page keeps updating with a `slug_advisory`; `suffixedSlugDryRun` serves both dry runs. `validateSlug` and path-derived import slugs are unchanged. Tests: `test/ingestion/put-page-write-through.test.ts`, `test/pathological/b5-export-unsafe-slugs.test.ts`, `test/pathological/b12-slug-segment-bytes.test.ts`, `test/hyphen-run-slugs-7305.test.ts`.+- `src/commands/doctor/checks/slug-path-mismatch.ts` — #7305 doctor `slug_path_mismatch` (BRAIN, after `origin_twins`): live file-backed pages of unarchived sources (scoped by `doctorSourceIds`) whose slug `resolveSlugForPath(source_path)` does not reproduce, such as a hyphen run the path rule folds. One read of candidate rows (slug regex prefilter, id order, `SLUG_PATH_SCAN_LIMIT` 20,000), then at most `SLUG_PATH_FILE_LIMIT` (200) recorded files read on this host (bound worktree, else `local_path`, else `sync.repo_path` for default) to tell a file stamped with the page's `slug:` line from an unstamped one. Unstamped files warn with counts, up to 5 samples (no `source_path` for a remote caller) and an `agentFix` naming the read-only `gbrain repair frontmatter --source <id> --json` preview; a hit bound with nothing unstamped is the #7145 bounded unknown; stamped, missing or not-checked-out files are ok. Read-only. Test: `test/doctor-slug-path-mismatch-7305.test.ts` (PGLite + Postgres via `test/e2e/doctor-slug-path-mismatch-7305-postgres.test.ts`).- `src/core/portable-slug.ts` — the one slug portability rule (GBRA-130 B-5/B-12): `FILE_NAME_MAX_BYTES` (240, a name's byte budget; a leaf also reserves `.json`), `RESERVED_DEVICE_NAME` (con, prn, aux, nul, com1-9, lpt1-9, alone or before an extension), `truncateUtf8`, `portableSegment` (a reserved name gets `-<suffix>`, an over-budget segment is cut at a code point boundary) and `slugPortabilityProblem` (reason, first segment, suggested slug). Used by `persistence/suffixed-slug.ts` admission; `enrichment-service.ts` `slugifyEntity` uses its parts, so a reserved entity name mints `people/con-person` or `companies/com1-company` and an over-budget one ends in a hash of the full name. `enrichEntity` reuses a page at a slug another entity also maps to (`Aux Company` at `companies/aux-company`) only when its title names the entity, preferring the matching legacy page (or, for a long name, the untagged cut slug an older gbrain minted, when its title maps to the same full slug), else uses the hash-tagged slug or skips with `entity_slug_taken` (F8, `test/pathological/b5-enrich-entity-identity.test.ts`).diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 5c3a64d147..d3d86865ba 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -1360,6 +1360,24 @@ origin; `CREATE UNIQUE INDEX CONCURRENTLY` on Postgres) only when the brain haschanges nothing and succeeds, and doctor's `origin_twins` check reports "Index pending". Once the last group isresolved, the repair's apply builds the index.+### Slug path mismatch++Doctor's `slug_path_mismatch` check (#7305) counts live pages whose slug their recorded file path does not derive. The+usual case is a hyphen run or a segment-final hyphen: `notes/x-1900---2000-ab.md` imports as `notes/x-1900-2000-ab`,+because the path rule folds every hyphen run to one hyphen. Import and sync keep such a page on its own slug only+through the `slug:` line every render stamps into its file (#5966). A file without that line, such as one an+older gbrain rendered or another tool rewrote, imports as the folded slug and forks a duplicate-origin twin, which sync+holds [`origin_conflict`](write-refusals.md#origin_conflict).++The check is read-only. It reads at most 20,000 candidate pages and 200 recorded files per run, and reports `Unknown`+when either bound stops it. It warns only when a file read on this host lacks the stamp, naming+`gbrain repair frontmatter --source <id>`, whose preview proposes the stamp as a safe repair. A twin that already forked+is reported by `origin_twins` and resolved with [`gbrain repair origin-twins`](#origin-twins).++`put_page` and `capture` refuse a new slug with a hyphen run or a segment-final hyphen (`invalid_params`, detail+`slug_hyphen_run`) and name the folded slug. A page that already holds such a slug keeps updating under it, and its+response carries `slug_advisory`. To move it, put its content under the folded slug, then delete the old page.+### Rename identityWhen sync cannot confirm an inexact Git rename (#6729), it imports the pair as adiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 75884ada01..1780b21a66 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -40,7 +40,7 @@ src/core/config.ts 2003 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factsrc/core/persistence/sync-run.ts 1682 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives)src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option-src/core/ops/pages.ts 727 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured)+src/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")diff --git a/src/commands/doctor/checks/slug-path-mismatch.ts b/src/commands/doctor/checks/slug-path-mismatch.tsnew file mode 100644index 0000000000..0741451847--- /dev/null+++ b/src/commands/doctor/checks/slug-path-mismatch.ts@@ -0,0 +1,113 @@+/**+ * #7305 `slug_path_mismatch`: live file-backed pages whose slug their recorded file path does not derive, such as a+ * hyphen run or a segment-final hyphen that the path rule folds (`notes/x-1900---2000-ab` recorded at+ * `notes/x-1900---2000-ab.md` imports as `notes/x-1900-2000-ab`). Import and sync keep such a page on its own slug only+ * through the `slug:` line its file carries (#5966); a file without that line imports as the derived slug and forks a+ * duplicate-origin twin (#6948), which sync then holds `origin_conflict`. put_page and capture refuse a new such slug;+ * this counts the pages that already exist.+ *+ * Read-only and bounded: one read of candidate rows (a slug pattern every non-derivable slug matches, in page id+ * order, at most SLUG_PATH_SCAN_LIMIT), then at most SLUG_PATH_FILE_LIMIT recorded files read on this host to tell a+ * stamped file from an unstamped one. Unstamped files warn and name `gbrain repair frontmatter --source <id>`, whose+ * preview proposes the stamp as a safe repair; a twin that already forked is `origin_twins`'s to report.+ */+import { existsSync, readFileSync, statSync } from 'node:fs';+import { join } from 'node:path';+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, doctorSourceIds, type DoctorContext, type DoctorEntry } from '../context.ts';+import { boundUnknownDetails } from '../bounded-unknown.ts';+import type { BrainEngine } from '../../../core/engine.ts';+import { parseMarkdown, resolveSourceLocalFilePath } from '../../../core/markdown.ts';+import { resolveSlugForPath } from '../../../core/sync.ts';+import { scannerSlugRootMode } from '../../../core/write-through.ts';+import { getWorktreeBinding } from '../../../core/persistence/ownership.ts';+import { localHostId } from '../../../core/persistence/identity.ts';++const DOCS = 'docs/guides/repair.md#slug-path-mismatch';+/** Candidate rows one run reads (pages whose slug matches the pattern, in id order). */+export const SLUG_PATH_SCAN_LIMIT = 20_000;+/** Recorded files one run reads to tell stamped from unstamped. */+export const SLUG_PATH_FILE_LIMIT = 200;+const SAMPLE_LIMIT = 5;+const FILE_MAX_BYTES = 1 << 20;+/** Every slug slugifyPath changes matches: a hyphen run or edge hyphen, an empty segment, any character outside a-z0-9/._- (a superset: a CJK slug matches and derives unchanged). */+const CANDIDATE_PATTERN = '[^a-z0-9/._-]|--|-/|/-|^-|-$|//';++type FileVerdict = 'stamped' | 'unstamped' | 'file_missing' | 'no_checkout' | 'not_read';+interface Mismatch { source_id: string; slug: string; source_path: string; imports_as: string; file: FileVerdict }+type Checkout = { root: string; mode: 'git-root' | 'source-root' } | null;++/** This host's checkout of a source (its bound owner worktree, else its local path, else sync.repo_path for default), or null. */+async function checkoutOf(engine: BrainEngine, sourceId: string): Promise<Checkout> {+ const binding = await getWorktreeBinding(engine, sourceId);+ const [source] = binding ? [] : await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [sourceId]);+ const root = binding ? binding.owner_host_id === localHostId() && binding.local_path ? join(binding.local_path, binding.relative_path) : null+ : source?.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);+ return root && existsSync(root) ? { root, mode: await scannerSlugRootMode(engine, sourceId, root) } : null;+}++/** Whether the page's recorded file names the page in its `slug:` line, the stamp import keeps it by. */+function fileVerdict(checkout: Checkout, page: Mismatch): FileVerdict {+ if (!checkout) return 'no_checkout';+ const file = resolveSourceLocalFilePath(checkout.root, page.source_path, page.slug, checkout.mode) ?? join(checkout.root, page.source_path);+ if (!existsSync(file) || !statSync(file).isFile() || statSync(file).size > FILE_MAX_BYTES) return 'file_missing';+ return parseMarkdown(readFileSync(file, 'utf8'), page.source_path).slug === page.slug ? 'stamped' : 'unstamped';+}++async function runSlugPathMismatch(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ try {+ const engine = connectedEngine(ctx);+ const scope = doctorSourceIds(ctx);+ const rows = await engine.executeRaw<{ source_id: string; slug: string; source_path: string }>(+ `SELECT p.source_id, p.slug, p.source_path FROM pages p JOIN sources s ON s.id = p.source_id AND s.archived IS NOT TRUE+ WHERE p.deleted_at IS NULL AND NULLIF(btrim(p.source_path), '') IS NOT NULL AND p.slug ~ $1${scope ? ' AND p.source_id = ANY($2::text[])' : ''}+ ORDER BY p.id LIMIT ${SLUG_PATH_SCAN_LIMIT + 1}`, scope ? [CANDIDATE_PATTERN, scope] : [CANDIDATE_PATTERN]);+ const truncated = rows.length > SLUG_PATH_SCAN_LIMIT;+ const inspected = rows.slice(0, SLUG_PATH_SCAN_LIMIT);+ const mismatches: Mismatch[] = inspected.flatMap(row => {+ const importsAs = resolveSlugForPath(row.source_path);+ return importsAs === row.slug ? [] : [{ ...row, imports_as: importsAs, file: 'not_read' as FileVerdict }];+ });+ const checkouts = new Map<string, Checkout>();+ for (const page of mismatches.slice(0, SLUG_PATH_FILE_LIMIT)) {+ if (!checkouts.has(page.source_id)) checkouts.set(page.source_id, await checkoutOf(engine, page.source_id));+ page.file = fileVerdict(checkouts.get(page.source_id)!, page);+ }+ const count = (verdict: FileVerdict) => mismatches.filter(page => page.file === verdict).length;+ const files = { stamped: count('stamped'), unstamped: count('unstamped'), file_missing: count('file_missing'), no_checkout: count('no_checkout'), not_read: count('not_read') };+ const samples = (pages: Mismatch[]) => pages.slice(0, SAMPLE_LIMIT).map(page => ({ source_id: page.source_id, slug: page.slug, imports_as: page.imports_as,+ ...(ctx.remote ? {} : { source_path: page.source_path }), file: page.file }));+ const details = { count: mismatches.length, files, inspected: inspected.length, truncated, scan_limit: SLUG_PATH_SCAN_LIMIT, file_limit: SLUG_PATH_FILE_LIMIT, docs: DOCS };+ const unstamped = mismatches.filter(page => page.file === 'unstamped');+ if (unstamped.length) {+ const first = unstamped[0]!.source_id;+ checks.push({ name: 'slug_path_mismatch', status: 'warn', details: { ...details, sources: [...new Set(unstamped.map(page => page.source_id))], samples: samples(unstamped) },+ message: `${unstamped.length} live page(s) record a file whose path imports as another slug, and the file has no slug: line naming the page `+ + `(e.g. ${unstamped.slice(0, 3).map(page => `${page.source_id}:${page.slug} imports as ${page.imports_as}`).join(', ')}), so the next import or full sync of that file forks a second page. `+ + `Preview the fix with gbrain repair frontmatter --source ${first} (writes nothing; it proposes the slug: stamp as a safe repair).`,+ fix: agentFix(['gbrain', 'repair', 'frontmatter', '--source', first, '--json'],+ 'Read-only preview: lists each file it would stamp with its page slug and prints the apply command with its hash. Apply only after the user agrees (it rewrites those files).',+ 'slug_path_mismatch', { docs: DOCS }) });+ return checks;+ }+ // #7145: a check stopped by its own bound did not see everything, so its health is unknown.+ if (truncated || files.not_read) {+ checks.push({ name: 'slug_path_mismatch', status: 'warn', details: { ...details, ...boundUnknownDetails(truncated ? 'rows' : 'files'), samples: samples(mismatches) },+ message: `Unknown: the check reads at most ${SLUG_PATH_SCAN_LIMIT} candidate pages and ${SLUG_PATH_FILE_LIMIT} recorded files (no setting), and ${truncated ? 'more pages were' : `${files.not_read} file(s) were`} not checked. `+ + `None of the files read lacks its slug: line. Preview gbrain repair frontmatter --source <id> to check every file of a source.` });+ return checks;+ }+ checks.push({ name: 'slug_path_mismatch', status: 'ok', details: { ...details, samples: samples(mismatches) },+ message: mismatches.length+ ? `${mismatches.length} live page(s) have a slug their file path does not derive, and every file read here carries the slug: line that keeps its page `+ + `(${files.stamped} stamped, ${files.file_missing} missing, ${files.no_checkout} with no checkout on this host).`+ : `Every live page's slug is the one its recorded file path derives (${inspected.length} candidate(s) inspected).` });+ } catch (error) {+ checks.push(checkError('slug_path_mismatch', 'check live pages whose slug their recorded file path does not derive', error, { details: { count: 'unknown', docs: DOCS } }));+ }+ return checks;+}++export const slugPathMismatchEntry: DoctorEntry = { name: 'slug_path_mismatch', emits: ['slug_path_mismatch'], run: runSlugPathMismatch };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex f843241f43..d9508bb593 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -122,6 +122,7 @@ import { fenceIntegrityEntry } from './checks/fence-integrity.ts';import { syncConfigKeysEntry } from './checks/sync-config-keys.ts';import { ghostPagesEntry } from './checks/ghost-pages.ts';import { originTwinsEntry } from './checks/origin-twins.ts';+import { slugPathMismatchEntry } from './checks/slug-path-mismatch.ts';import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';import { unindexedFilesEntry } from './checks/unindexed-files.ts';import { syncLandingGapsEntry } from './checks/landing-gaps.ts';@@ -265,6 +266,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [extractionInputTruncatedEntry,ghostPagesEntry,originTwinsEntry,+ slugPathMismatchEntry,renameIdentityDowngradesEntry,purgeParkedPagesEntry,missingRecordedFilesEntry,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 39ac344787..2291fb739d 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1097,6 +1097,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },// #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.{ since: '0.60.361.0', id: 'applied_watermark_7190', text: '`get_write_request` with `applied: true` (`gbrain write-request <id> --applied`) now returns `applied`, read live: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`), the request `sequence` and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`), and a pending write\'s hint names that read; a write\'s own reply is otherwise unchanged. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },+ // #7305: hyphen-run slugs at write time. `since` is stamped at the merge slot.+ { since: 'TBD', text: 'A put_page or capture of a new slug with a hyphen run or a segment-final hyphen (`notes/x-1900---2000-ab`, `notes/x-`) is refused with `invalid_params` (detail `slug_hyphen_run`) naming the folded slug (`notes/x-1900-2000-ab`), the slug import and sync derive from its file. A page that already exists under such a slug still updates, and its response carries `slug_advisory`. New doctor check `slug_path_mismatch` counts live pages whose slug their recorded file path does not derive and warns when the file lacks the `slug:` line that keeps the page, naming the read-only `gbrain repair frontmatter --source <id>` preview.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 6f1c7ff277..91ef95f05b 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -211,6 +211,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['ghost_pages',// #6948: files recorded by several live pages (origin twins) and the pages_live_origin_key index (doctor/checks/origin-twins.ts).'origin_twins',+ // #7305: live pages whose slug their recorded file path does not derive, and whose file lacks the slug: stamp (doctor/checks/slug-path-mismatch.ts).+ 'slug_path_mismatch',// #6729: inexact renames whose identity sync did not keep, until the pair gets a disposition (doctor/checks/rename-identity-downgrades.ts).'rename_identity_downgrades',// #6609: live pages of a classic checkout whose recorded file a full sync would not find (doctor/checks/missing-recorded-files.ts).diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 57c06cc799..c10056deac 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -705,12 +705,13 @@ const capture: Operation = {cliHints: { name: 'capture', hidden: true },handler: async (ctx, p) => {const { pageMutationSource, submitPageMutation } = await pageMutations();- pageMutationSource(ctx, p, 'capture');+ const sourceId = pageMutationSource(ctx, p, 'capture');if (ctx.dryRun) {if (typeof p.slug === 'string') {validatePageSlug(p.slug);enforceClientSlugFence(ctx, p.slug, 'capture');enforceSubagentSlugFence(ctx, p.slug, 'capture');+ await suffixedSlugDryRun(ctx, sourceId, p.slug, 'capture');}return { dry_run: true, action: 'capture', slug: p.slug };}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 5b51925e9d..f479e77114 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -370,8 +370,8 @@ export async function preparePageAdmission(ctx: OperationContext,await assertTimelineNotOmitted(ctx.engine, { intent, remote: ctx.remote !== false, writer: typeof p.expected_revision === 'string' ? 'editing' : 'preserving',slug, sourceId, content: intent.content, prior: snapshot });}- const slugAdvisory = input.operation === 'put_page' && input.managedFileImport !== true- ? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at) : null;+ const slugAdvisory = (input.operation === 'put_page' || input.operation === 'capture') && input.managedFileImport !== true+ ? suffixedSlugAdmission(ctx, slug, !!snapshot && !snapshot.page.deleted_at, input.operation) : null;// #5616: typed edit refusals before admission; publication repeats them on the locked snapshot.if (input.operation === 'edit_page') {const { applyPageEdits, assertEditRevision, assertSegmentedEditFences, parseEditWithin, parsePageEdits } = await import('./page-edit.ts');diff --git a/src/core/persistence/suffixed-slug.ts b/src/core/persistence/suffixed-slug.tsindex 0535d588f1..a38bfb49f0 100644--- a/src/core/persistence/suffixed-slug.ts+++ b/src/core/persistence/suffixed-slug.ts@@ -19,12 +19,22 @@* portable-slug.ts), naming the portable slug to write instead. A live page* already holding such a slug keeps accepting updates with an advisory, and a* replayed request never reaches this check.+ *+ * #7305: put_page and capture also refuse a new slug with a hyphen run or a+ * segment-final hyphen (`notes/x-1900---2000-ab`, `notes/x-`), naming the+ * folded slug (`notes/x-1900-2000-ab`): import and sync derive that folded slug+ * from the file, so the page would keep its identity only through the `slug:`+ * line its file is stamped with (#5966), and a file rewritten without it forks+ * a second page. A live page that already holds the exact slug keeps updating+ * with an advisory, like the rules above; nothing is ever redirected to the+ * folded slug's page.*/import type { BrainEngine } from '../engine.ts';import type { ContentRefusal } from '../import-screen.ts';import { opError, type OperationContext, type OperationError } from '../ops/contract.ts';import { opTransport, readFix } from '../ops/op-fix.ts';import { slugPortabilityProblem, type SlugPortabilityProblem } from '../portable-slug.ts';+import { hyphenFoldedSlug } from '../sync.ts';const MARKDOWN_SUFFIX = /(\.mdx?)+$/i;@@ -64,17 +74,39 @@ function portabilityRefusal(ctx: OperationContext, slug: string, problem: SlugPo});}+function hyphenRunRefusal(ctx: OperationContext, operation: SlugAdmissionOperation, folded: string): OperationError {+ const cli = opTransport(ctx) === 'cli';+ return opError('invalid_params', 'New page slugs must not contain a hyphen run or end a segment in a hyphen.',+ cli ? `Write the page as ${folded}: ${operation === 'capture' ? `gbrain capture --slug ${folded}` : `gbrain put ${folded}`}`+ : `Call ${operation} again with slug "${folded}" and the same content.`, {+ detail: 'slug_hyphen_run',+ why: `A page is stored at <slug>.md, and import and sync derive a file's slug with every hyphen run folded to one hyphen, so this file would import as ${folded}. `+ + 'The page would keep its identity only through the slug: line in its file; a copy of the file without that line forks a second page.',+ fix: {+ ...readFix('Checks whether the folded slug already holds a page before writing it there.',+ { argv: ['gbrain', 'get', folded], mcp: { tool: 'get_page', arguments: { slug: folded } } }),+ verify: { argv: ['gbrain', 'get', folded], mcp: { tool: 'get_page', arguments: { slug: folded } } },+ },+ });+}++type SlugAdmissionOperation = 'put_page' | 'capture';+/**- * Refuses a new suffixed or unportable slug; for a live exact-identity page- * returns the advisory to attach to the response. Null for every other slug.+ * Refuses a new slug that is suffixed, unportable (put_page only) or not+ * hyphen-folded (put_page and capture); for a live exact-identity page returns+ * the advisory to attach to the response. Null for every other slug.*/-export function suffixedSlugAdmission(ctx: OperationContext, slug: string, liveExactRow: boolean): string | null {- const bare = bareSlugOf(slug);- const problem = slugPortabilityProblem(bare ?? slug);- if (bare === null && problem === null) return null;- if (!liveExactRow) throw bare !== null ? refusal(ctx, bare) : portabilityRefusal(ctx, slug, problem!);- const target = problem?.suggestion ?? bare!;- const why = bare !== null ? 'ends in .md, which new pages cannot use' : 'is not a portable file name, which new pages need';+export function suffixedSlugAdmission(ctx: OperationContext, slug: string, liveExactRow: boolean, operation: SlugAdmissionOperation = 'put_page'): string | null {+ const bare = operation === 'put_page' ? bareSlugOf(slug) : null;+ const problem = operation === 'put_page' ? slugPortabilityProblem(bare ?? slug) : null;+ const folded = bare === null && problem === null ? hyphenFoldedSlug(slug) : null;+ if (bare === null && problem === null && folded === null) return null;+ if (!liveExactRow) throw bare !== null ? refusal(ctx, bare) : problem !== null ? portabilityRefusal(ctx, slug, problem) : hyphenRunRefusal(ctx, operation, folded!);+ const target = problem?.suggestion ?? bare ?? folded!;+ const why = bare !== null ? 'ends in .md, which new pages cannot use'+ : problem !== null ? 'is not a portable file name, which new pages need'+ : `has a hyphen run or a segment-final hyphen, which new pages cannot use: its file path imports as "${folded}", so the page keeps its identity only through the slug: line in its file`;return `This page's slug ${why}. To move it, put_page its content under "${target}", then delete_page "${slug}".`;}@@ -85,10 +117,9 @@ async function liveExactRow(engine: BrainEngine, sourceId: string, slug: string)}/** Dry-run form: reads the exact `(source_id, slug)` row itself. */-export async function suffixedSlugDryRun(ctx: OperationContext, sourceId: string, slug: string): Promise<void> {- const bare = bareSlugOf(slug);- if (bare === null && slugPortabilityProblem(slug) === null) return;- suffixedSlugAdmission(ctx, slug, await liveExactRow(ctx.engine, sourceId, slug.toLowerCase()));+export async function suffixedSlugDryRun(ctx: OperationContext, sourceId: string, slug: string, operation: SlugAdmissionOperation = 'put_page'): Promise<void> {+ if (suffixedSlugAdmission(ctx, slug, true, operation) === null) return;+ suffixedSlugAdmission(ctx, slug, await liveExactRow(ctx.engine, sourceId, slug.toLowerCase()), operation);}/**diff --git a/src/core/sync.ts b/src/core/sync.tsindex c8c471fae9..cd2e95ea5a 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -721,7 +721,7 @@ export const SLUG_SEGMENT_PATTERN = new RegExp(`[${SLUG_WORD_CHARS}._\\-]+`, 'u'const SLUGIFY_KEEP_RE = new RegExp(`[^${SLUG_WORD_CHARS}.\\s_\\-]`, 'gu');export function slugifySegment(segment: string): string {- return segment+ return foldSegmentHyphens(segment.normalize('NFD') // Decompose accented chars.replace(/[\u0300-\u036f]/g, '') // Strip accent marks// #3700: Hebrew niqqud (vowel points) + cantillation are optional@@ -739,9 +739,22 @@ export function slugifySegment(segment: string): string {.replace(SLUG_VARIATION_SELECTORS_RE, '').toLowerCase().replace(SLUGIFY_KEEP_RE, '') // Keep alnum, dots, spaces, _-, and CJK (v0.32.7)- .replace(/[\s]+/g, '-') // Spaces → hyphens- .replace(/-+/g, '-') // Collapse multiple hyphens- .replace(/^-|-$/g, ''); // Strip leading/trailing hyphens+ .replace(/[\s]+/g, '-')); // Spaces → hyphens+}++/** Collapse hyphen runs and strip leading/trailing hyphens: slugifySegment's last step. */+function foldSegmentHyphens(segment: string): string {+ return segment.replace(/-+/g, '-').replace(/^-|-$/g, '');+}++/**+ * #7305: a slug with every segment's hyphen runs collapsed and its edge hyphens+ * stripped, as slugifySegment does to a file name; null when nothing changes.+ * put_page and capture refuse a new slug this changes, naming the result.+ */+export function hyphenFoldedSlug(slug: string): string | null {+ const folded = slug.split('/').map(foldSegmentHyphens).join('/');+ return folded === slug ? null : folded;}/**diff --git a/test/doctor-slug-path-mismatch-7305.test.ts b/test/doctor-slug-path-mismatch-7305.test.tsnew file mode 100644index 0000000000..5f30ed4e5f--- /dev/null+++ b/test/doctor-slug-path-mismatch-7305.test.ts@@ -0,0 +1,97 @@+/**+ * #7305 `slug_path_mismatch` doctor check: live file-backed pages whose slug their recorded file path does not derive+ * (a hyphen run the path rule folds). A file stamped with the page's `slug:` line keeps the page and is ok; a file+ * without it would import as the folded slug and fork a twin, so it warns with a sample and the read-only+ * `gbrain repair frontmatter --source <id>` preview as the fix. Read-only: no row or file changes.+ *+ * PGLite and, with DATABASE_URL, Postgres. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { Check } from '../src/commands/doctor.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { slugPathMismatchEntry } from '../src/commands/doctor/checks/slug-path-mismatch.ts';+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';+import { categorizeCheck } from '../src/core/doctor-categories.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++setDefaultTimeout(60_000);++for (const backend of testBackends()) describe(`[${backend}] #7305 doctor slug_path_mismatch`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const home = mkdtempSync(join(tmpdir(), `gbrain-7305-doctor-${backend}-`));++ beforeAll(async () => {+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ }, 120_000);+ afterAll(async () => { await close(); rmSync(home, { recursive: true, force: true }); }, 60_000);++ /** A source with a checkout of its own; each test reads only its source. */+ async function source(id: string): Promise<string> {+ const root = join(home, id);+ mkdirSync(root, { recursive: true });+ await engine.executeRaw("INSERT INTO sources(id, name, local_path, config) VALUES ($1, $1, $2, '{}')", [id, root]);+ return root;+ }+ /** A live page recording `<slug>.md`, written with or without the slug: stamp (null: no file). */+ async function page(sourceId: string, root: string, slug: string, file: 'stamped' | 'unstamped' | null) {+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () =>+ tx.putPage(slug, { type: 'note', title: 'Example', compiled_truth: 'example body', timeline: '' }, { sourceId }), TEST_WRITE_ATTRIBUTION));+ await engine.executeRaw('UPDATE pages SET source_path=$3 WHERE source_id=$1 AND slug=$2', [sourceId, slug, `${slug}.md`]);+ if (!file) return;+ mkdirSync(dirname(join(root, `${slug}.md`)), { recursive: true });+ writeFileSync(join(root, `${slug}.md`), `---\ntype: note\ntitle: Example${file === 'stamped' ? `\nslug: ${slug}` : ''}\n---\n\nexample body\n`);+ }+ const run = async (sourceId: string) => ((await slugPathMismatchEntry.run({ engine, sourceIds: [sourceId] } as unknown as DoctorContext)) as Check[])[0]!;++ test('is registered, categorized, and ok when every page slug is the one its file path derives', async () => {+ expect(DOCTOR_CHECK_REGISTRY).toContain(slugPathMismatchEntry);+ expect(categorizeCheck('slug_path_mismatch')).toBe('brain');+ const root = await source('source-clean');+ await page('source-clean', root, 'notes/x-example', 'unstamped');+ await page('source-clean', root, 'notes/v1.0.0', 'unstamped');+ const check = await run('source-clean');+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ count: 0 });+ });++ test('a hyphen-run page whose file carries its slug: stamp is ok, and is counted', async () => {+ const root = await source('source-stamped');+ await page('source-stamped', root, 'notes/x-1900---2000-ab', 'stamped');+ const check = await run('source-stamped');+ expect(check.status).toBe('ok');+ expect(check.details).toMatchObject({ count: 1, files: { stamped: 1, unstamped: 0 } });+ });++ test('a hyphen-run page whose file lacks the stamp warns with a bounded sample and the read-only repair preview; nothing is written', async () => {+ const root = await source('source-a');+ for (let i = 0; i < 7; i++) await page('source-a', root, `notes/x-${i}---example-`, 'unstamped');+ await page('source-a', root, 'notes/y--example', null);+ const before = readFileSync(join(root, 'notes/x-0---example-.md'), 'utf8');+ const pagesBefore = await engine.executeRaw('SELECT slug, source_path, knowledge_revision::text AS r FROM pages WHERE source_id=$1 ORDER BY id', ['source-a']);+ const check = await run('source-a');+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ count: 8, files: { unstamped: 7, file_missing: 1, stamped: 0 }, sources: ['source-a'] });+ const samples = (check.details as { samples: Array<Record<string, unknown>> }).samples;+ expect(samples).toHaveLength(5);+ expect(samples[0]).toEqual({ source_id: 'source-a', slug: 'notes/x-0---example-', imports_as: 'notes/x-0-example', source_path: 'notes/x-0---example-.md', file: 'unstamped' });+ expect(check.message).toContain('source-a:notes/x-0---example- imports as notes/x-0-example');+ expect(check.fix).toMatchObject({ argv: ['gbrain', 'repair', 'frontmatter', '--source', 'source-a', '--json'] });+ expect(readFileSync(join(root, 'notes/x-0---example-.md'), 'utf8')).toBe(before);+ expect(await engine.executeRaw('SELECT slug, source_path, knowledge_revision::text AS r FROM pages WHERE source_id=$1 ORDER BY id', ['source-a'])).toEqual(pagesBefore);+ });++ test('a remote caller sees slugs but no file paths', async () => {+ const check = ((await slugPathMismatchEntry.run({ engine, sourceIds: ['source-a'], remote: true } as unknown as DoctorContext)) as Check[])[0]!;+ expect((check.details as { samples: Array<Record<string, unknown>> }).samples[0]).not.toHaveProperty('source_path');+ });+});diff --git a/test/e2e/doctor-slug-path-mismatch-7305-postgres.test.ts b/test/e2e/doctor-slug-path-mismatch-7305-postgres.test.tsnew file mode 100644index 0000000000..760a557e5e--- /dev/null+++ b/test/e2e/doctor-slug-path-mismatch-7305-postgres.test.ts@@ -0,0 +1,4 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// #7305: the slug_path_mismatch doctor check on Postgres.+await registerPostgresTests(() => import('../doctor-slug-path-mismatch-7305.test.ts'));diff --git a/test/e2e/hyphen-run-slugs-7305-postgres.test.ts b/test/e2e/hyphen-run-slugs-7305-postgres.test.tsnew file mode 100644index 0000000000..59188ba961--- /dev/null+++ b/test/e2e/hyphen-run-slugs-7305-postgres.test.ts@@ -0,0 +1,4 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// #7305: hyphen-run slugs at write time on Postgres.+await registerPostgresTests(() => import('../hyphen-run-slugs-7305.test.ts'));diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 08ac4073c4..817603cf0a 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -2914,6 +2914,29 @@"name": "origin_twins","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#slug-path-mismatch",+ "file_limit": 200,+ "files": {+ "file_missing": 0,+ "no_checkout": 0,+ "not_read": 0,+ "stamped": 0,+ "unstamped": 0+ },+ "inspected": 0,+ "samples": [],+ "scan_limit": 20000,+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "Every live page's slug is the one its recorded file path derives (0 candidate(s) inspected).",+ "name": "slug_path_mismatch",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 57c105df4d..0575f2df63 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -2957,6 +2957,29 @@"name": "origin_twins","status": "ok"},+ {+ "category": "brain",+ "details": {+ "count": 0,+ "docs": "docs/guides/repair.md#slug-path-mismatch",+ "file_limit": 200,+ "files": {+ "file_missing": 0,+ "no_checkout": 0,+ "not_read": 0,+ "stamped": 0,+ "unstamped": 0+ },+ "inspected": 0,+ "samples": [],+ "scan_limit": 20000,+ "truncated": false+ },+ "elapsed_ms": "<volatile>",+ "message": "Every live page's slug is the one its recorded file path derives (0 candidate(s) inspected).",+ "name": "slug_path_mismatch",+ "status": "ok"+ },{"category": "brain","details": {diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex d192590ec6..12ba7a015d 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -901,6 +901,10 @@"category": "brain","name": "origin_twins"},+ {+ "category": "brain",+ "name": "slug_path_mismatch"+ },{"category": "brain","name": "rename_identity_downgrades"diff --git a/test/hyphen-run-slugs-7305.test.ts b/test/hyphen-run-slugs-7305.test.tsnew file mode 100644index 0000000000..7a77bb68ae--- /dev/null+++ b/test/hyphen-run-slugs-7305.test.ts@@ -0,0 +1,171 @@+/**+ * #7305 part 1: put_page and capture admit a NEW slug with a hyphen run (`notes/x-1900---2000-ab`) or a segment-final+ * hyphen, publish its file at that slug path, and every path-derived reader (sync, import) folds the file's slug to+ * `notes/x-1900-2000-ab`: the page keeps its identity only through the `slug:` line the render stamps (#5966), and a+ * file that loses it imports as a second page. Such a new slug is refused before admission with the folded slug as the+ * recovery (the #4807 `.md` rule); a live page that already holds the exact slug keeps accepting updates with a+ * `slug_advisory`, and the folded slug's own page is never touched.+ *+ * Trusted local CLI (remote=false) and MCP (remote=true) callers, PGLite and, with DATABASE_URL, Postgres.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, OperationError } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { resolveSlugForPath } from '../src/core/sync.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++setDefaultTimeout(60_000);++const HYPHEN_RUN = 'notes/x-1900---2000-ab';+const FOLDED = 'notes/x-1900-2000-ab';+const content = '---\ntitle: Example\n---\n\nexample body';++for (const backend of testBackends()) describe(`[${backend}] #7305 hyphen-run slugs at write time`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let tmpRoot: string;+ let brainDir: string;++ beforeAll(async () => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-7305-'));+ brainDir = path.join(tmpRoot, 'brain');+ fs.mkdirSync(brainDir, { recursive: true });+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }+ await engine.setConfig('sync.repo_path', brainDir);+ // Postgres refuses writes to an unbound classic checkout, so the source gets a canonical owner on both engines.+ execFileSync('git', ['-C', brainDir, 'init', '-q']);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await withEnv({ GBRAIN_HOME: path.join(tmpRoot, 'home') }, () => claimWorktree(engine, 'default', brainDir));+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }, 120_000);+ afterAll(async () => { await disposePersistenceConsumer(engine); await close(); resetGateway(); fs.rmSync(tmpRoot, { recursive: true, force: true }); }, 60_000);+ beforeEach(() => resetGateway());++ const ctx = (overrides: Partial<OperationContext> = {}): OperationContext => ({+ engine, config: { engine: backend, embedding_disabled: true } as OperationContext['config'],+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default', ...overrides,+ });+ const run = (name: 'put_page' | 'capture', c: OperationContext, params: Record<string, unknown>) =>+ withEnv({ GBRAIN_HOME: path.join(tmpRoot, 'home') }, () => operations.find(o => o.name === name)!.handler(c, params)) as Promise<Record<string, unknown>>;+ async function refusalOf(promise: Promise<unknown>): Promise<OperationError> {+ try { await promise; } catch (error) { return error as OperationError; }+ throw new Error('expected a refusal');+ }+ const requests = async () => Number((await engine.executeRaw<{ n: number }>('SELECT COUNT(*)::int AS n FROM persistence_requests'))[0]!.n);+ const row = async (slug: string) => (await engine.executeRaw<{ id: number; compiled_truth: string }>(+ "SELECT id, compiled_truth FROM pages WHERE source_id='default' AND slug=$1", [slug]))[0] ?? null;+ const fixture = (slug: string, body: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.putPage(slug, { type: 'note', title: 'Example', compiled_truth: body, timeline: '' }, { sourceId: 'default' }), TEST_WRITE_ATTRIBUTION));+ /** A page an earlier gbrain wrote under a hyphen-run slug, with its stamped file. */+ async function legacyPage(slug: string, body: string) {+ await fixture(slug, body);+ const file = path.join(brainDir, `${slug}.md`);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, `---\ntype: note\ntitle: Example\nslug: ${slug}\n---\n\n${body}\n`);+ await engine.executeRaw("UPDATE pages SET source_path=$2 WHERE source_id='default' AND slug=$1", [slug, `${slug}.md`]);+ return (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ }++ test('put_page from the trusted CLI refuses a new hyphen-run or hyphen-ended slug before admission, naming the folded slug', async () => {+ const before = await requests();+ for (const [slug, folded] of [[HYPHEN_RUN, FOLDED], ['notes/x-example-', 'notes/x-example'], ['Notes/A--B/c-example', 'notes/a-b/c-example']]) {+ const error = await refusalOf(run('put_page', ctx(), { slug, content }));+ expect(error).toBeInstanceOf(OperationError);+ expect(error.code).toBe('invalid_params');+ expect(error.detail).toBe('slug_hyphen_run');+ expect(error.suggestion).toBe(`Write the page as ${folded}: gbrain put ${folded}`);+ expect(error.fix).toMatchObject({ argv: ['gbrain', 'get', folded], verify: { argv: ['gbrain', 'get', folded] } });+ }+ expect(await requests()).toBe(before);+ expect(await row(HYPHEN_RUN)).toBeNull();+ expect(fs.existsSync(path.join(brainDir, `${HYPHEN_RUN}.md`))).toBe(false);+ });++ test('put_page from an MCP caller (remote=true) gets the same refusal with the MCP recovery; the CLI envelope carries why and fix', async () => {+ const remote = await refusalOf(run('put_page', ctx({ remote: true }), { slug: 'notes/m-1900---2000-ab', content }));+ expect(remote.code).toBe('invalid_params');+ expect(remote.detail).toBe('slug_hyphen_run');+ expect(remote.suggestion).toBe(`Call put_page again with slug "${'notes/m-1900-2000-ab'}" and the same content.`);+ expect(remote.fix?.mcp).toEqual({ tool: 'get_page', arguments: { slug: 'notes/m-1900-2000-ab' } });+ const { toAgentError, cliRenderContext } = await import('../src/core/agent-output.ts');+ const cli = toAgentError(await refusalOf(run('put_page', ctx(), { slug: 'notes/m-1900---2000-ab', content })), { transport: 'cli', command: 'put', render: cliRenderContext() });+ expect(cli).toMatchObject({ code: 'invalid_params', class: 'caller', contract_version: 1 });+ expect(cli.why).toContain('notes/m-1900-2000-ab');+ expect(cli.fix).toMatchObject({ argv: ['gbrain', 'get', 'notes/m-1900-2000-ab'], next: 'run' });+ expect(await row('notes/m-1900---2000-ab')).toBeNull();+ });++ test('capture refuses a new hyphen-run slug for CLI and MCP callers, and dry runs of put_page and capture refuse too', async () => {+ const before = await requests();+ const cli = await refusalOf(run('capture', ctx(), { slug: 'notes/c-1900---2000-ab', content: 'captured example text' }));+ expect(cli.code).toBe('invalid_params');+ expect(cli.detail).toBe('slug_hyphen_run');+ expect(cli.suggestion).toBe(`Write the page as ${'notes/c-1900-2000-ab'}: gbrain capture --slug ${'notes/c-1900-2000-ab'}`);+ const remote = await refusalOf(run('capture', ctx({ remote: true }), { slug: 'notes/c-1900---2000-ab', content: 'captured example text' }));+ expect(remote.detail).toBe('slug_hyphen_run');+ expect(remote.suggestion).toBe(`Call capture again with slug "${'notes/c-1900-2000-ab'}" and the same content.`);+ for (const name of ['put_page', 'capture'] as const) {+ const dry = await refusalOf(run(name, ctx({ dryRun: true }), { slug: 'notes/c-1900---2000-ab', content }));+ expect(dry.detail).toBe('slug_hyphen_run');+ }+ expect(await requests()).toBe(before);+ expect(await row('notes/c-1900---2000-ab')).toBeNull();+ });++ test('the folded slug writes with no advisory, and its file imports as that same slug', async () => {+ const put = await run('put_page', ctx({ remote: true }), { slug: FOLDED, content });+ expect(put.slug_advisory).toBeUndefined();+ const captured = await run('capture', ctx(), { slug: 'notes/y-example', content: 'captured example text' });+ expect(captured.slug_advisory).toBeUndefined();+ const [page] = await engine.executeRaw<{ source_path: string }>("SELECT source_path FROM pages WHERE source_id='default' AND slug=$1", [FOLDED]);+ expect(resolveSlugForPath(page!.source_path)).toBe(FOLDED);+ });++ test('a live page that already holds a hyphen-run slug stays writable by that slug (put and capture, CLI and MCP) with an advisory; the folded page is untouched', async () => {+ const existing = 'notes/z-1900---2000-ab', other = 'notes/z-1900-2000-ab';+ await fixture(other, 'a different page');+ const snapshot = await legacyPage(existing, 'old body');+ const advisory = `This page's slug has a hyphen run or a segment-final hyphen, which new pages cannot use: its file path imports as "${other}", so the page keeps its identity only through the slug: line in its file. To move it, put_page its content under "${other}", then delete_page "${existing}".`;++ const cli = await run('put_page', ctx(), { slug: existing, content: '---\ntitle: Example\n---\n\ncli body', expected_revision: snapshot.revision });+ expect(cli.slug_advisory).toBe(advisory);+ expect(Number((await row(existing))!.id)).toBe(Number(snapshot.page.id));+ expect((await row(existing))!.compiled_truth).toContain('cli body');++ const afterCli = (await engine.readPageSnapshot(existing, { sourceId: 'default' }))!;+ const mcp = await run('put_page', ctx({ remote: true }), { slug: existing, content: '---\ntitle: Example\n---\n\nmcp body', expected_revision: afterCli.revision });+ expect(mcp.slug_advisory).toBe(advisory);+ expect((await row(existing))!.compiled_truth).toContain('mcp body');++ for (const remote of [false, true]) {+ const current = (await engine.readPageSnapshot(existing, { sourceId: 'default' }))!;+ const captured = await run('capture', ctx({ remote }), { slug: existing, content: `captured ${remote ? 'mcp' : 'cli'} text`, expected_revision: current.revision });+ expect(captured.slug_advisory).toBe(advisory);+ expect(Number((await row(existing))!.id)).toBe(Number(snapshot.page.id));+ }+ expect((await row(other))!.compiled_truth).toBe('a different page');+ expect(fs.readFileSync(path.join(brainDir, `${existing}.md`), 'utf8')).toContain(`slug: ${existing}`);+ });++ test('a soft-deleted hyphen-run row is not live: re-creating it is refused', async () => {+ await legacyPage('notes/gone--example', 'gone');+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>+ tx.executeRaw("UPDATE pages SET deleted_at=now() WHERE source_id='default' AND slug='notes/gone--example'"), TEST_WRITE_ATTRIBUTION));+ const error = await refusalOf(run('put_page', ctx(), { slug: 'notes/gone--example', content }));+ expect(error.detail).toBe('slug_hyphen_run');+ });+});diff --git a/test/slug-stamp-double-hyphen.test.ts b/test/slug-stamp-double-hyphen.test.tsindex 07fa893ff8..dbaee0d16e 100644--- a/test/slug-stamp-double-hyphen.test.ts+++ b/test/slug-stamp-double-hyphen.test.ts@@ -20,6 +20,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { OperationContext } from '../src/core/ops/contract.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { importFile } from '../src/core/import-file.ts';import { readReconcileState } from '../src/core/persistence/reconcile-state.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { resolveRepairScope, type RepairResult } from '../src/core/repair/core.ts';@@ -83,13 +84,17 @@ for (const kind of backends) describe(`repair frontmatter stamps a legacy unstamgit(root, 'config', 'user.name', 'Example'); git(root, 'config', 'user.email', '[email protected]');writeFileSync(join(root, '.git', 'hooks', 'post-commit'), '#!/bin/sh\n# gbrain brain-durability post-commit hook (v0.42.44+)\n'); chmodSync(join(root, '.git', 'hooks', 'post-commit'), 0o755);writeFileSync(join(root, 'notes', 'ok.md'), '---\ntitle: Ok\n---\nFine.\n');+ // #7305: put_page refuses a NEW notes/a--b, so the page an earlier gbrain wrote is imported from its stamped file.+ writeFileSync(join(root, 'notes', 'a--b.md'), '---\ntitle: Double\nslug: notes/a--b\n---\nTwo hyphens.\n');git(root, 'add', '-A'); git(root, 'commit', '-qm', 'fixture');await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await importFile(engine, join(root, 'notes', 'a--b.md'), 'notes/a--b.md', { noEmbed: true, sourceId: id });await claimWorktree(engine, id, root);await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');try {- await submitPageMutation(localCtx(engine, id), { operation: 'put_page', params: { slug: 'notes/a--b', source_id: id, content: '---\ntitle: Double\n---\nTwo hyphens.\n' } });+ const imported = (await engine.readPageSnapshot('notes/a--b', { sourceId: id }))!;+ await submitPageMutation(localCtx(engine, id), { operation: 'put_page', params: { slug: 'notes/a--b', source_id: id, content: '---\ntitle: Double\n---\nTwo hyphens, updated.\n', expected_revision: imported.revision } });const written = readFileSync(join(root, 'notes', 'a--b.md'), 'utf8');expect(written).toContain('slug: notes/a--b');// A file an earlier gbrain rendered without the stamp.