diff --git a/.gstack/pregate.json b/.gstack/pregate.json index 983140ad2f4..7d4a76df592 100644 --- a/.gstack/pregate.json +++ b/.gstack/pregate.json @@ -183,13 +183,15 @@ "workflow": "test.yml", "events": ["workflow_dispatch", "push"], "jobs": ["full-suite"], - "artifact": "full-suite-tree" + "artifact": "full-suite-tree", + "os": "Linux" }, "e2e": { "workflow": "e2e.yml", "events": ["workflow_dispatch", "push"], "jobs": ["e2e-full-suite"], - "artifact": "e2e-full-suite-tree" + "artifact": "e2e-full-suite-tree", + "os": "Linux" }, "native-locks.yml/native": { "workflow": "test.yml", diff --git a/changelog.d/gbra635-concept-purge-rebuild.md b/changelog.d/gbra635-concept-purge-rebuild.md new file mode 100644 index 00000000000..b853ff04f86 --- /dev/null +++ b/changelog.d/gbra635-concept-purge-rebuild.md @@ -0,0 +1,7 @@ +**A concept page hidden because one of its source notes was purged is now rebuilt from its remaining notes, unless anyone wrote something on it.** + +### Fixed +- When purging an old note hid a concept that synthesis built from it, the next concept synthesis now deletes the hidden page for good and writes a new one from the notes still in the group. Nothing of the old text reaches the model or stays in the brain. Previously the concept stayed hidden and was never shown again. (#9653) +- A hidden concept stays hidden, and the purge preview says why, when it holds anything synthesis did not write: a new title, extra frontmatter, a timeline, curated sections, a file under another name, facts, takes, tags, attached files or data, hand-made links, an entity identity, a guest mark, or a person's decision on an edge proposal. It also stays hidden when the new page would be readable more widely than the hidden one, or when no synthesis model is set. +- Links from other pages to the concept move to the rebuilt page with all their details kept. +- Brains with no git repository get the same behavior. On brains whose writes go through the write owner, hidden concepts stay hidden for now; their rebuild waits for a later release. diff --git a/changelog.d/gst3186-remember-valid-from-starter.md b/changelog.d/gst3186-remember-valid-from-starter.md new file mode 100644 index 00000000000..29ba58282b0 --- /dev/null +++ b/changelog.d/gst3186-remember-valid-from-starter.md @@ -0,0 +1,4 @@ +**An MCP client on the starter tool list can now say when a remembered fact was true by passing `valid_from` to `remember`.** + +### Fixed +- Since starter clients were limited to the parameters their tool list shows, a single `remember` call with `valid_from` was refused with `param_not_on_surface`, although the same date was already accepted inside `items`. Ingest clients that know when each message was said can now date a single fact too. `valid_from` still doesn't appear in the starter tool list, so the list's size is unchanged. diff --git a/changelog.d/secret-restore-marker.md b/changelog.d/secret-restore-marker.md new file mode 100644 index 00000000000..8dc3b60dc81 --- /dev/null +++ b/changelog.d/secret-restore-marker.md @@ -0,0 +1,9 @@ +--- +important: security +--- +**A secret store restore ties an original only to the page at its backed-up slug, and only when that page still holds its marker.** + +### Fixed +- `gbrain secrets backup --restore` no longer ties an original to a page that merely took its old slug and does not hold its marker (`:>`), so that page's readers never pass the `reveal_secret` read check for it. A page that holds a full copy of the marker, in its text or in a timeline entry or fact filed on it, still counts as holding it. +- A backup that names a page by a slug it had before a rename (one taken before 0.60.744.0) skips that entry (`skipped_no_page`) instead of tying it to another page, and a restore never brings back what a purge removed. This replaces the 0.60.744.0 note saying such an entry would be restored without a place. +- A restore that loses the race with a purge of the same page no longer leaves the sealed original behind. diff --git a/changelog.d/vorflux-pregate-linux-os.md b/changelog.d/vorflux-pregate-linux-os.md new file mode 100644 index 00000000000..a7c4181aa71 --- /dev/null +++ b/changelog.d/vorflux-pregate-linux-os.md @@ -0,0 +1,4 @@ +**Shipping a gbrain change no longer reruns the full test suite on the developer's machine when Linux CI already passed at the same code.** + +### Changed +- For contributors: `.gstack/pregate.json` now records that the CI `test` and `e2e` jobs run on Linux, and each full run's `tree.json` now records the runner's OS, which gstack requires before it accepts the run. `/ship` reuses a passed CI run of those jobs only when the local machine runs the same operating system, and without this field it could not match them, so it ran the whole suite locally (about an hour). Nothing changes for gbrain users. diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv index d4161fd4d97..1b087c1e2d8 100644 --- a/docs/architecture/canonical-writers.tsv +++ b/docs/architecture/canonical-writers.tsv @@ -316,3 +316,4 @@ src/core/access/attest-sources.ts 1 projection GST-1113: applyAttestSources sets src/core/storage-manifest/source.ts 1 contract markRole sets role and federated in the config of the storage source that addSource or hostRepo created in the same storage init or first repo-less register; it writes source configuration only, never page content. src/core/guests/sources.ts 1 projection GBRA-504 guest source setup (initGuestSource, the trusted local gbrain guests init): merges the guest, federated and trust_ceiling keys into sources.config in the transaction that writes the guest_sources row; a settings field, not page content, and canonical columns stay guarded by SQL triggers. src/core/git/redact-finish.ts 1 contract GST-2988 PR 2: finishRedactions moves sources.last_commit from a commit a publish redaction rebuilt to its rebuilt copy (compare-and-set on the old sha, from the redactions journal beside the checkout); it writes no page content, and the page side goes through repair/secret-spans.ts redactPageForPublish. +src/core/persistence/concept-rebuild.ts 1 engine_guard #9653: on an unmanaged brain, a concept an input purge hid is rebuilt in one transaction that hard-purges only that tombstone through the engine purge (purgeDeletedPages onlyIds, the expiry statements and holds), inside a belief batch (page.expired) like the recorded-tombstone expiry, then imports the fresh page; a managed brain submits delete_page purge through the coordinator instead. diff --git a/docs/ci-event-parity.md b/docs/ci-event-parity.md index cfb680b278c..74bf23ae8ad 100644 --- a/docs/ci-event-parity.md +++ b/docs/ci-event-parity.md @@ -234,6 +234,9 @@ inventory: the same run, attempt and commit. Otherwise both are left out with a warning: the run still counts for merge, but gstack refuses it (`inventory_uncovered`). A push that reused a run has no `full-suite` job, so it is never evidence. +- `tree.json` carries `os`, the runner's OS from `RUNNER_OS` (`Linux` for both + jobs). A run profile that sets `os` refuses a run whose `tree.json` records a + different OS or none (`os_mismatch`). - `bash scripts/pregate-remote-gate.sh --list` prints the inventory: the gate command with `--list` (`scripts/ci-ubicloud.ts --list`), the same lanes and discovery the gate runs, one file per line. It exits non-zero when the @@ -259,7 +262,12 @@ inventory: (`test.yml`, job `full-suite`, artifact `full-suite-tree`) and `e2e` (`e2e.yml`, job `e2e-full-suite`, artifact `e2e-full-suite-tree`), each accepting `workflow_dispatch` and `push` runs from the last 24 hours, and - `remote_gate_runs` naming both with this inventory command. gstack reads them + `remote_gate_runs` naming both with this inventory command. Both profiles set + `os` to `Linux`, the OS of the runners that execute these jobs: gstack uses a + run only when its `tree.json` records that OS, and the final pregate's tests + stage reuses it only on a machine running the same OS (on macOS or Windows + that stage runs the selected tests locally; the lane carries below don't + need it). gstack reads the profiles only from `origin/`, so a branch cannot loosen them. gstack accepts these keys from 1.91.377.0 on. diff --git a/docs/guides/secret-store.md b/docs/guides/secret-store.md index 25eb57fd4c3..87650aff899 100644 --- a/docs/guides/secret-store.md +++ b/docs/guides/secret-store.md @@ -131,10 +131,16 @@ one `gbrain files` uses), gbrain also uploads an encrypted export of the store t a host whose keyring holds the key the backup names (import the escrow copy first), and it skips, and lists, any row that does not authenticate under it. An entry already here is left as it is, even when the backup's copy differs; the places the backup recorded for it that this brain lacks are added, so a later purge of one page never removes an - original another page still holds. A restore only adds rows and never deletes one, and each restored place is tied - to the page that holds its slug in this brain now. - An original whose every recorded place was on a page this brain does not hold is skipped and counted as - `skipped_no_page` ("skipped because their page is not in this brain"): the page was purged, or is not synced yet, + original another page still holds. A restore only adds rows and never deletes one it did not write, and it ties a restored place to + the page at its backed-up slug only when that page holds the entry's marker (`:>`), so a page + that merely took an old slug, or quotes only the id, never gets the original. The marker counts when it sits in the page + itself or in a timeline entry or fact filed on or about that page, so a copy another page wrote into that page's + timeline counts too. A page whose body is stored in segments is read segment by segment. The restore ties the place + to the exact page it checked and holds that page until it commits, so a rename running at the same time cannot hand + the original to a page that takes the slug. + An original recorded only on pages, none of which at its backed-up slugs holds its marker, is skipped and counted as + `skipped_no_page` ("skipped because no page in this brain holds their marker"): the page was purged, is not synced + yet, or was renamed before the backup named it by its current slug (a backup from before 0.60.744.0), and a restore cannot tell which, so it never brings back what a page purge removed. Sync the pages, then run the same restore again; it adds what it skipped. When every entry is skipped that way (a rebuilt brain before sync), the restore refuses with `invalid_params` and writes nothing, so a script never reads it as finished. @@ -169,8 +175,4 @@ store is backed up, and warns when: - It does not erase bytes physically: dead database rows and WAL can hold old text until the database reclaims them. - An original an older gbrain left an occurrence for after its page was purged stays: that occurrence still names it, so the cascade and doctor's count treat it as referenced. -- A restore from a backup taken before a rename can tie an original to a different page that has since taken the - renamed page's old slug, and that page's readers then pass the `reveal_secret` read check for it. It needs both: an - older backup and another page now at that slug. After a restore, `gbrain secrets list` shows the pages each original - is tied to. A backup taken after the rename names the new slug. - Markers written before the store existed (`` with no id) stay unrecoverable. diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.md index 5316c018f71..a1909f94b6c 100644 --- a/docs/operations/mcp-surface-runbook.md +++ b/docs/operations/mcp-surface-runbook.md @@ -61,7 +61,7 @@ connection may widen, and otherwise asks the user, because only the operator wid a pinned client. `STARTER_CALLABLE_PARAMS` in `src/mcp/surface.ts` lists the few hidden parameters a starter caller may still pass, each with its reason (page windows, the shared-skill follower, the thin client's source binding, the -connection check, a delegating client's `submit_agent` `queue`, `model` and +connection check, `remember` `valid_from` (already accepted inside `items`), a delegating client's `submit_agent` `queue`, `model` and `allowed_slug_prefixes`, `list_pages` paging with `offset`). An agent job (`submit_agent`) records the surface of the connection that submitted it, and its tool calls are refused the same way; a job queued before the surface was recorded keeps the full surface until diff --git a/scripts/ci-full-suite-tree.sh b/scripts/ci-full-suite-tree.sh index cdccb4866a8..fc01fa68415 100755 --- a/scripts/ci-full-suite-tree.sh +++ b/scripts/ci-full-suite-tree.sh @@ -5,8 +5,12 @@ # aggregate succeeded. scripts/ci-reuse.ts reads the artifact on a push to master; # `gstack-pregate clear --run` reads it as run evidence for the remote gate. # Input (environment): ARTIFACT_DIR, RUN_ID, RUN_ATTEMPT, WORKFLOW, EVENT, and -# optionally MANIFEST, the run's ci-manifest.json (scripts/ci-manifest.ts). +# optionally MANIFEST, the run's ci-manifest.json (scripts/ci-manifest.ts), and +# RUNNER_OS, which GitHub Actions sets on every runner. # Output: $ARTIFACT_DIR/tree.json and step-summary lines. +# `os` is the runner's OS (Linux, macOS or Windows) when RUNNER_OS is set. +# gstack refuses a run under a .gstack/pregate.json run profile that sets `os` +# unless tree.json records that OS (gstack docs/pregate.md#run-evidence). # `files` (every test file the run loaded, repo-relative, across lanes and # arms; a file whose tests all skipped counts, because the remote gate's # inventory lists the same env- and platform-gated files) and `tests` (its @@ -45,8 +49,9 @@ else fi fi jq -n --arg tree "$tree" --arg sha "$sha" --arg workflow "$WORKFLOW" --arg event "$EVENT" \ - --argjson run_id "$RUN_ID" --argjson run_attempt "$RUN_ATTEMPT" --slurpfile evidence "$evidence" \ - '{tree: $tree, sha: $sha, workflow: $workflow, event: $event, run_id: $run_id, run_attempt: $run_attempt, profile: "full"} + $evidence[0]' \ + --argjson run_id "$RUN_ID" --argjson run_attempt "$RUN_ATTEMPT" --slurpfile evidence "$evidence" --arg os "${RUNNER_OS:-}" \ + '{tree: $tree, sha: $sha, workflow: $workflow, event: $event, run_id: $run_id, run_attempt: $run_attempt, profile: "full"} + + (if $os == "" then {} else {os: $os} end) + $evidence[0]' \ > "$ARTIFACT_DIR/tree.json" rm -f "$evidence" jq -c 'del(.files)' "$ARTIFACT_DIR/tree.json" diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv index 45bb4c092f8..9b7dd2ba19b 100644 --- a/scripts/core-world-reads-baseline.tsv +++ b/scripts/core-world-reads-baseline.tsv @@ -740,6 +740,7 @@ src/core/persistence/protocol.ts module_collection 1 W6: per-engine state, or ma src/core/persistence/publication-deadline.ts als_store 1 W2: engine scope (decision E) replaces ad hoc async context src/core/persistence/publication-deadline.ts module_collection 1 W6: per-engine state, or mark as a constant table src/core/persistence/publication-timing.ts process_env 1 W6: settings plane out of the core +src/core/persistence/concept-rebuild.ts load_config 1 #9653: the rebuild's retention purge goes through the coordinator with the same config as purge-deleted.ts src/core/persistence/purge-deleted.ts load_config 1 W6: settings plane out of the core src/core/persistence/put-page-screen.ts load_config 1 W6: settings plane out of the core src/core/persistence/reconcile-audit.ts fs_import 1 W5: repo-less persistence for hosts diff --git a/scripts/engine-raw-sql-baseline.tsv b/scripts/engine-raw-sql-baseline.tsv index 4cbb72b441b..4141b03f20b 100644 --- a/scripts/engine-raw-sql-baseline.tsv +++ b/scripts/engine-raw-sql-baseline.tsv @@ -735,6 +735,7 @@ src/core/persistence/capacity-view.ts execute_raw 1 src/core/persistence/change-reason.ts execute_raw 4 src/core/persistence/checkpoint-validation.ts execute_raw 5 src/core/persistence/compaction-pass.ts execute_raw 2 +src/core/persistence/concept-rebuild.ts execute_raw 12 #9653: the held-concept rebuild's hold, member and stated-row checks run in its purge transaction, next to the engine purge it calls src/core/persistence/config-snapshot.ts execute_raw 2 src/core/persistence/connector-account-mismatch.ts execute_raw 2 src/core/persistence/connector-checkpoint-migration.ts execute_raw 13 @@ -1100,7 +1101,7 @@ src/core/search/transcript-quote.ts execute_raw 3 src/core/search/two-pass.ts execute_raw 5 src/core/secret-store/restore.ts execute_raw 3 secret restore reads the page revision and live knowledge_revision and flips secret_store.status; no typed engine method for the secret store exists yet src/core/secret-store/spool.ts execute_raw 1 GST-2988 PR 2 spool: reads every allowed (restored) key_id and value_mac from secret_store to rebuild allowed.json; branched before the #9641 ratchet; no typed engine method for the secret store exists yet -src/core/secret-store/store.ts execute_raw 22 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; all move behind typed engine methods with the rest after gbrain#9694 +src/core/secret-store/store.ts execute_raw 24 secret_store and secret_store_occurrence inserts and reads (dedupe by value_mac, entry, occurrences, list, key summary); GST-2988 PR 2 adds +5: drain inserts a spooled original by id (exists check, value_mac lookup, insert), the per-rule counts for secrets list, and the allowed value_macs one source restored; branched before the #9641 ratchet; no typed engine method for the secret store exists yet; GST-2988 PR 3 adds +3: backup export reads every entry and occurrence row in one statement (one snapshot) and restore inserts them in one transaction; GST-3074 adds +5: restore reads whether an entry it did not insert is the same one, so it adds that entry's missing occurrences; the purge cascade deletes a purged page's occurrences, locks the entries they pointed at, and deletes those nothing else references; doctor counts unreferenced originals; GST-3178 adds +2: restore reads which backed-up slugs name a page holding the marker, and takes back out an entry it wrote whose every place failed to land because its page was purged while the restore ran; all move behind typed engine methods with the rest after gbrain#9694 src/core/serve-sync-runner.ts execute_raw 1 src/core/session-lane.ts execute_raw 3 src/core/shared-skills/adopted-packs.ts execute_raw 1 diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv index 553ce2f4667..b7dbf2e2ff3 100644 --- a/scripts/page-body-readers-baseline.tsv +++ b/scripts/page-body-readers-baseline.tsv @@ -664,6 +664,7 @@ src/core/search/relational-recall.ts hydrate field LEAD synopsis from boundedBod src/core/search/safe-chunks.ts bodyWriteChunkVersion sql SEGW spliced into inline body writes only; a segmented row refuses those writes (CHECK) src/core/search/safe-chunks.ts protectedBodyFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) src/core/search/safe-chunks.ts protectedTakesFilter sql META segmented page: body_flags.has_protected decides, missing flag counts as protected (fail closed) +src/core/secret-store/marker-sql.ts pageHoldsSql sql INLINE presence check on inline columns in SQL; a segmented body is not read here, and restore reads its segments through readSegmentedBody src/core/secret-store/restore.ts previewRestore sql INLINE presence check on inline columns in SQL; a segmented page counts as a hit and the apply reads it whole src/core/shared-skills/migration-export.ts exportInventory call:serializeMarkdown INLINE src/core/shared-skills/migration-export.ts exportInventory field INLINE @@ -725,3 +726,4 @@ src/commands/doctor/checks/atom-body-recheck.ts unchangedBodyAtoms sql INLINE do src/core/guests/promote.ts promoteGuestNote call:serializeMarkdown INLINE assertInlineBody refuses a guest note stored in segments (page_body_segmented) before its body is copied into the owner page src/core/guests/promote.ts promoteGuestNote field INLINE assertInlineBody before the body is read src/core/rust-engine/store-codec.ts guardNullBody field META reads only whether the Rust store sent compiled_truth/timeline as null (a segmented shell, PGLite pages_body_storage_chk), never the body text; a null body becomes the guarded segmented page of rowToPage +src/core/persistence/concept-rebuild.ts STATED_SQL sql INLINE reads only an inline page timeline for emptiness; a segmented page counts as unread and stays hidden diff --git a/src/commands/maintain.ts b/src/commands/maintain.ts index 78095823835..c9322b0b4e6 100644 --- a/src/commands/maintain.ts +++ b/src/commands/maintain.ts @@ -369,22 +369,24 @@ export function purgePreviewHash(retentionHours: number, pages: ReadonlyArray<{ } async function runPurgeCli(engine: BrainEngine, opts: MaintainOptions): Promise { - const [{ selectPurgeCandidates, purgeDeletedPagesCoordinated }, { readPurgeRetentionHours }] = await Promise.all([ + const [{ selectPurgeCandidates, purgeDeletedPagesCoordinated, rebuildNote }, { readPurgeRetentionHours }] = await Promise.all([ import('../core/persistence/purge-deleted.ts'), import('../core/sync-reconcile.ts')]); const retention = await readPurgeRetentionHours(engine); - const selection = await selectPurgeCandidates(engine, retention, { automatic: true }); + const selection = await selectPurgeCandidates(engine, retention, { automatic: true, model: (await import('../core/ai/gateway.ts')).isAvailable('chat') }); const pages: Array<{ source_id: string; slug: string }> = (selection.managed ? selection.candidates : selection.pages ?? []) .map((p) => ({ source_id: p.source_id, slug: p.slug })); const hash = purgePreviewHash(retention, pages); const apply = ['gbrain', 'maintain', '--purge', '--yes', '--expect', hash]; if (!opts.yes) { const preview = { mode: 'preview', retention_hours: retention, count: pages.length, pages: pages.slice(0, 50), blocked: selection.blocked.length, hash, + ...(selection.rebuild.held.length ? { rebuild: selection.rebuild, rebuild_note: rebuildNote(selection.rebuild) } : {}), ...(pages.length ? { apply: renderAction({ argv: apply, consent: ['destructive'], actor: 'agent', requires_exclusive: false, why: `Permanently deletes the ${pages.length} page(s) listed (soft-deleted more than ${retention}h ago); gbrain restore cannot bring them back.` }, cliRenderContext()) } : {}) }; if (opts.json) { console.log(JSON.stringify(preview, null, 2)); return; } console.log(`${pages.length} soft-deleted page(s) are past the ${retention}h recovery window.`); for (const p of pages.slice(0, 50)) console.log(` ${p.source_id}/${p.slug}`); if (pages.length > 50) console.log(` ...and ${pages.length - 50} more`); + if (selection.rebuild.held.length) console.log(rebuildNote(selection.rebuild)); if (pages.length) console.log(`Nothing was deleted. To purge exactly these, run: ${apply.join(' ')}`); return; } diff --git a/src/commands/pages.ts b/src/commands/pages.ts index 59a9e904023..12645daac4b 100644 --- a/src/commands/pages.ts +++ b/src/commands/pages.ts @@ -10,7 +10,7 @@ * page_links, chunk_relations via existing FKs. */ import type { BrainEngine } from '../core/engine.ts'; -import { notHeld, purgeConsentRequest, purgeDeletedPagesCoordinated, selectPurgeCandidates } from '../core/persistence/purge-deleted.ts'; +import { notHeld, purgeConsentRequest, purgeDeletedPagesCoordinated, rebuildNote, selectPurgeCandidates } from '../core/persistence/purge-deleted.ts'; import { PURGE_PARK_LIMIT } from '../core/persistence/purge-parks.ts'; import { setCliExitVerdict } from '../core/cli-force-exit.ts'; import { consentGate } from '../core/consent-cli.ts'; @@ -50,10 +50,11 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise park.retried).length; const notes = { ...(selection.parked.length ? { parked: selection.parked, retry_parked: retryParked } : {}), ...(selection.blocked.length ? { blocked: selection.blocked } : {}), - ...(selection.released_origins.length ? { released_origins: selection.released_origins } : {}) }; + ...(selection.released_origins.length ? { released_origins: selection.released_origins } : {}), + ...(selection.rebuild.held.length ? { rebuild: selection.rebuild, rebuild_note: rebuildNote(selection.rebuild, true) } : {}) }; if (dryRun) { // Read-only: the same predicate and DB now() clock as the real purge; only the verb differs. @@ -68,6 +69,7 @@ async function runPurgeDeleted(engine: BrainEngine, args: string[]): Promise !park.retried)) console.log(` parked: ${p.source_id}/${p.slug} after ${p.failures} failures (${p.code ?? 'error'}); skipped unless --retry-parked`); for (const b of selection.blocked.filter(entry => entry.code === 'writer_not_active')) console.log(` waiting: ${b.source_id}/${b.slug}: ${b.reason}`); + if (selection.rebuild.held.length) console.log(rebuildNote(selection.rebuild, true).split('\n').map(line => ` ${line}`).join('\n')); for (const o of selection.released_origins) console.log(` released: ${o.source_id}/${o.slug} is parked (gbrain doctor: derived_origin_parked); the run labels the pages derived from it private first and keeps it parked if that fails`); return; } diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts index b8b0a71459c..4ffcc8d34c3 100644 --- a/src/core/cli-flag-registry.generated.ts +++ b/src/core/cli-flag-registry.generated.ts @@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--error-unmatch', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-assume-unchanged', '--no-autostash', '--no-cron', '--no-pull', '--no-renames', '--no-skip-worktree', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--porcelain', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--readers', '--rebase', '--require-clean', '--resolve', '--room', '--scan-secrets', '--scan-timeout', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--stdin', '--timeout', '--timings', '--unset-all', '--untracked-files', '--verify', '--wait', '--yes'], 'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'], 'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'], - 'maintain': ['--absolute-git-dir', '--accept-dns', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--as', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--contains', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--db-url', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from', '--from-meetings', '--full', '--get', '--grammar', '--grep', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--out', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--passphrase-stdin', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remotes', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'], + 'maintain': ['--absolute-git-dir', '--accept-dns', '--accept-pending', '--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--alert', '--all', '--allow-outside-source-root', '--apply', '--as', '--assign-corpus', '--attest-read', '--audit', '--background', '--bg', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--cask', '--catch-up', '--check-only', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--contains', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--db-url', '--delete-brain', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--entity', '--exclude', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from', '--from-meetings', '--full', '--get', '--grammar', '--grep', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--https', '--id', '--ignore-missing', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-extensions', '--no-extract', '--no-hard-deadline', '--no-instructions', '--no-pull', '--no-renames', '--no-schema-pack', '--no-walk', '--non-interactive', '--not', '--now', '--older-than', '--once', '--only', '--operations', '--operator', '--out', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--passphrase-stdin', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefix', '--preview', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--public-url', '--pull', '--purge', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw-only', '--reader-mode', '--readers', '--reads-unscoped', '--reauth', '--rebase', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remote', '--remotes', '--remove', '--remove-core', '--repo', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--room', '--runner', '--safe', '--scan-secrets', '--schedule', '--scope', '--scopes', '--serves', '--session', '--set-path', '--show-current', '--show-toplevel', '--since', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--strict', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--top-k', '--trust', '--type', '--unattended', '--unindexed', '--unschedule', '--untracked-files', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--wakeshift', '--where', '--window', '--workers', '--working-tree', '--workspace', '--yes'], 'mcp': ['--admin-token-file', '--advertise', '--agent', '--all', '--arg', '--attest-actor', '--attest-ops', '--attest-read', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--command', '--credentials-file', '--credentials-out', '--cursor', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--email', '--enable-dcr', '--env', '--federated-read', '--flow', '--force', '--funnel', '--groups', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--member', '--name', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--qm', '--queue', '--reason', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'], 'memory-proposals': ['--all', '--brain', '--dry-run', '--help', '--json', '--limit', '--reason', '--replace', '--source'], 'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--concurrency', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--room', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'], @@ -97,7 +97,7 @@ export const CLI_FLAG_REGISTRY: Record = { 'notices': ['--brain', '--help', '--json', '--source'], 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--card', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--expected-revision', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--patch', '--path', '--phase', '--prefer', '--privacy-url', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--terms-url', '--to', '--token', '--updated-after', '--url', '--yes'], 'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--room', '--source', '--timeout', '--timings', '--wait'], - 'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'], + 'pages': ['--brain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--force', '--help', '--json', '--limit', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--status', '--verify', '--yes'], 'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'], 'post-upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backend', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--check-only', '--client', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expect', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--id', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--may-act-for', '--member', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--prefix', '--quiet', '--readers', '--reads-unscoped', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--slugs-file', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--synopsis', '--tags', '--target', '--token', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'], 'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'], diff --git a/src/core/cycle.ts b/src/core/cycle.ts index 801399a0708..9e69308bf78 100644 --- a/src/core/cycle.ts +++ b/src/core/cycle.ts @@ -1792,7 +1792,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise { // #9653: kept for the next concept synthesis + console.warn(`[cycle] held-concept report skipped: ${e instanceof Error ? e.message : String(e)}`); + return { held: [], kept: [] }; + }); // #6770: request-log rows past cycle.purge.mcp_request_log_retention_days, when set (logic in mcp-request-log-retention.ts). let purgedMcpLog = 0; try { purgedMcpLog = (await (await import('./mcp-request-log-retention.ts')).runMcpLogRetention(engine))?.deleted ?? 0; } catch (e) { console.warn(`[cycle] request-log retention skipped: ${e instanceof Error ? e.message : String(e)}`); } @@ -1812,7 +1816,8 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise 0 ? ` (${purgeResult.blocked.length} blocked, see details)` : '') + `, ${purgedPages.count} page(s)${purgePhaseNote(purgedPages)}, ` + - `and ${purgedClones.count} orphan clone temp dir(s)`, + `and ${purgedClones.count} orphan clone temp dir(s)` + + (rebuild.held.length ? `; ${rebuild.held.length} concept(s) hidden by an input purge kept for the next concept synthesis${rebuild.kept.length ? ` (${rebuild.kept.length} of them stay hidden, reasons in details)` : ''}` : ''), details: { purged_sources_count: purgedSources.length, purged_sources_blocked: purgeResult.blocked, @@ -1821,6 +1826,7 @@ async function runPhasePurge(engine: BrainEngine, dryRun: boolean): Promise 0 ? { purged_mcp_request_log_count: purgedMcpLog } : {}), }, }; diff --git a/src/core/cycle/concept-publication.ts b/src/core/cycle/concept-publication.ts index 8965f0d15c5..edfde7b3fa7 100644 --- a/src/core/cycle/concept-publication.ts +++ b/src/core/cycle/concept-publication.ts @@ -25,6 +25,7 @@ import { acquirePageLock } from '../page-lock.ts'; import { derivedFileTarget, writeDerivedPageThrough } from './derived-write-through.ts'; import { fileDatabaseDriftToken, replaceableFile } from '../facts/file-body-guard.ts'; import { declareDerivation, deriveTrust, lowerDerivedPage } from '../trust/taint.ts'; +import { rebuildHeldConcept, type ConceptRebuild } from '../persistence/concept-rebuild.ts'; /** #5575 I2: the narrative carries the tier of the member atoms its prompt was built from (capped at agent_written). */ const conceptDerivation = (engine: BrainEngine, sourceId: string, members: readonly string[]) => @@ -262,13 +263,15 @@ export function stripFenceSections(body: string): string { */ export async function publishClassicConcept(engine: BrainEngine, slug: string, sourceId: string, synthesized: Record, narrative: string, baseline: string, - opts: { writeThrough: boolean; importPage: (markdown: string) => Promise; members?: readonly string[] }): Promise { + opts: { writeThrough: boolean; importPage: (markdown: string, tx?: BrainEngine) => Promise; members?: readonly string[]; rebuild?: ConceptRebuild }): Promise { const lock = await acquirePageLock(slug, { timeoutMs: 5_000 }); if (!lock) throw Object.assign(new Error('The concept page is locked by another writer.'), { code: 'revision_conflict' }); try { - const snapshot = await engine.readPageSnapshot(slug, { sourceId }); - const page = snapshot?.page ?? null; - if (stripFenceSections(page?.compiled_truth ?? '') !== stripFenceSections(baseline) + const { rebuild } = opts; + const snapshot = await engine.readPageSnapshot(slug, { sourceId, ...(rebuild ? { includeDeleted: true } : {}) }); + // #9653: a rebuild is composed from nothing in the tombstone; rebuildHeldConcept confirms the hold under the lock. + const page = rebuild ? null : snapshot?.page ?? null; + if (rebuild ? snapshot?.page.deleted_at == null : stripFenceSections(page?.compiled_truth ?? '') !== stripFenceSections(baseline) || (page && !String(page.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts'))) { throw Object.assign(new Error('The concept narrative changed during synthesis.'), { code: 'revision_conflict' }); } @@ -281,7 +284,9 @@ export async function publishClassicConcept(engine: BrainEngine, slug: string, s const markdown = page ? composeConceptRepublication(page, snapshot!.tags, synthesized, narrative) : serializeMarkdown(synthesized, narrative, '', { type: 'concept', title, tags: [] }); - await opts.importPage(markdown); + if (rebuild) { + await rebuildHeldConcept(engine, sourceId, slug, rebuild, tx => opts.importPage(markdown, tx)); + } else await opts.importPage(markdown); // The import stamps the page by its own channel; the derivation lowers it to the members' taint and records the edges. if (opts.members) await lowerDerivedPage(engine, await conceptDerivation(engine, sourceId, opts.members), sourceId, slug); if (file && (file.expectedFileBytes !== null || opts.writeThrough)) { diff --git a/src/core/cycle/concept-writes.ts b/src/core/cycle/concept-writes.ts index 6af9dc7b4bc..5ff9102d7d5 100644 --- a/src/core/cycle/concept-writes.ts +++ b/src/core/cycle/concept-writes.ts @@ -17,6 +17,7 @@ import { isAvailable } from '../ai/gateway.ts'; import { importFromContent } from '../import-file.ts'; import type { ConceptRetryBound } from './concept-retry-bound.ts'; import { publicationHold } from '../persistence/accepted-pending.ts'; +import type { ConceptRebuild } from '../persistence/concept-rebuild.ts'; import { conceptProvenanceCovers, replaceConceptProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcepts, } from './concept-publication.ts'; @@ -39,6 +40,10 @@ export interface ConceptWrite { revision: string | null; /** Unmanaged: the narrative the page held when synthesis started; a different narrative under the page lock defers the concept (D-N3). */ baseline: string; + /** #9653: a held concept's rebuild: unmanaged, the tombstone its transaction purges; managed, 'purged' (its purge committed). */ + rebuild?: ConceptRebuild | 'purged'; + /** #9653: set once the rebuilt page was written. */ + rebuilt?: boolean; } export interface ConceptWriterDeps { @@ -76,10 +81,13 @@ export function conceptWriter(deps: ConceptWriterDeps) { }; const publishClassic = async (write: ConceptWrite, pageVisibility: Visibility): Promise => { try { + // #9653: a rebuild imports inside its locked transaction, so its chunks wait for the embedding backlog instead. + const rebuild = write.rebuild && write.rebuild !== 'purged' ? write.rebuild : undefined; write.baseline = await publishClassicConcept(engine, write.conceptSlug, src, write.synthesized(pageVisibility), write.narrative, - write.baseline, { writeThrough: deps.writeThrough, members: write.atomSlugs, importPage: (markdown) => importFromContent(engine, write.conceptSlug, markdown, { - noEmbed: !isAvailable('embedding'), sourceId: deps.importSourceId, preserveGateMarkers: true, + write.baseline, { writeThrough: deps.writeThrough, members: write.atomSlugs, rebuild, importPage: (markdown, tx) => importFromContent(tx ?? engine, write.conceptSlug, markdown, { + noEmbed: !!rebuild || !isAvailable('embedding'), sourceId: deps.importSourceId, preserveGateMarkers: true, }) }); + if (write.rebuild) { write.rebuilt = true; write.rebuild = undefined; } return true; } catch (err) { return recorded(write, err); } }; @@ -131,6 +139,7 @@ export function conceptWriter(deps: ConceptWriterDeps) { const outcome = outcomes[i]!; if ('error' in outcome) return recorded(write, outcome.error); write.revision = outcome.revision; + if (write.rebuild) { write.rebuilt = true; write.rebuild = undefined; } return true; }); }; diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts index 4278a29b29b..f731a6d05e5 100644 --- a/src/core/cycle/synthesize-concepts.ts +++ b/src/core/cycle/synthesize-concepts.ts @@ -20,7 +20,7 @@ // For T3/T4: deterministic stub narrative. // 6. Write concept-typed pages with the synthesis mode made explicit. -import type { BrainEngine } from '../engine.ts'; +import type { BrainEngine, PageSnapshot } from '../engine.ts'; import { resolveModel } from '../model-config.ts'; import type { PhaseResult } from '../cycle.ts'; import type { ProgressReporter } from '../progress.ts'; @@ -41,6 +41,7 @@ import { derivedWriteThrough, reportDerivedWriteThrough } from './derived-write- import { addSpellingRedirects, canonicalConceptStem, loadConceptRedirects, loadLiveConceptStems } from './concept-redirects.ts'; import { conceptProvenanceCovers, conceptPublicationHold, stripFenceSections } from './concept-publication.ts'; import { conceptWriter, type ConceptWrite } from './concept-writes.ts'; +import { heldConceptRebuild, keptReason, submitHeldConceptPurge, type ConceptRebuild, type RebuildKept } from '../persistence/concept-rebuild.ts'; import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts'; import { ConceptRetryBound, MAX_CONCEPT_ATTEMPTS } from './concept-retry-bound.ts'; import { ConceptDriftSkips } from '../persistence/drift-conflicts.ts'; @@ -138,7 +139,7 @@ export interface SynthesizeConceptsOpts { /** Test seam: alternative chat function. */ _chat?: typeof gatewayChat; /** Test seam: skip DB query; cluster these atoms directly. */ - _atoms?: Array<{ slug: string; concept_refs: string[]; body: string; title: string; visibility?: Visibility }>; + _atoms?: Array<{ slug: string; concept_refs: string[]; body: string; title: string; visibility?: Visibility; revision?: string }>; } interface AtomGroup { @@ -147,6 +148,8 @@ interface AtomGroup { atomSlugs: string[]; atomTitles: string[]; atomBodies: string[]; + /** #9653: each member's knowledge_revision when its body was read (a held concept's rebuild refuses if it moved). */ + atomRevisions: Array; /** #5525: strictest effective visibility of the member atoms. */ visibility: Visibility; tier: 'T1' | 'T2' | 'T3' | 'T4'; @@ -165,6 +168,14 @@ Output ONLY the summary paragraph (3-5 sentences). No headers, no JSON, no preamble. Write in plain English, present-tense voice. Synthesize what the atoms collectively SAY about the concept; don't enumerate the atoms.`; +/** #9653: the rebuild of a held concept tombstone, or null; a held concept kept hidden is added to `kept` with why. */ +async function conceptRebuildFor(engine: BrainEngine, sourceId: string, snapshot: PageSnapshot, group: AtomGroup, dryRun: boolean, + kept: RebuildKept[]): Promise { + const held = dryRun ? null : await heldConceptRebuild(engine, sourceId, snapshot, group.atomSlugs, group.atomRevisions, group.visibility); + if (held && 'kept' in held) kept.push(held.kept); + return held && 'rebuild' in held ? held.rebuild : null; +} + export async function runPhaseSynthesizeConcepts( engine: BrainEngine, opts: SynthesizeConceptsOpts = {}, @@ -179,13 +190,14 @@ export async function runPhaseSynthesizeConcepts( slug: string; title: string; compiled_truth: string; + revision: string; frontmatter: { concepts?: string[]; imported_from?: string }; private: boolean; }>( // Codex P2: scoped to the cycle source — the provenance edges below // are pinned to it, so a brain-global scan grouped same-slug atoms // from OTHER sources into this source's concepts. - `SELECT slug, title, compiled_truth, frontmatter, NOT (${privatePagesFilterFragment('pages')}) AS private + `SELECT slug, title, compiled_truth, knowledge_revision::text AS revision, frontmatter, NOT (${privatePagesFilterFragment('pages')}) AS private FROM pages WHERE type = 'atom' AND source_id = $1 @@ -199,6 +211,7 @@ export async function runPhaseSynthesizeConcepts( slug: r.slug, title: r.title, body: r.compiled_truth, + revision: r.revision, concept_refs: r.frontmatter!.concepts!, visibility: r.private ? 'private' as const : 'world' as const, })); @@ -219,13 +232,14 @@ export async function runPhaseSynthesizeConcepts( // 2. Group atoms by concept stem (#6161 human redirects, then #5965 spelling folds; see resolveAtomConceptStems); one atom counts once per concept. const { atomStems, foldedSpellings } = await resolveAtomConceptStems(engine, opts.sourceId ?? 'default', atoms); - const groups = new Map(); + const groups = new Map; visibilities: Visibility[] }>(); for (const [i, atom] of atoms.entries()) { for (const conceptSlug of atomStems[i]!) { - const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], visibilities: [] }; + const existing = groups.get(conceptSlug) ?? { slugs: [], titles: [], bodies: [], revisions: [], visibilities: [] }; existing.slugs.push(atom.slug); existing.titles.push(atom.title); existing.bodies.push(atom.body); + existing.revisions.push(atom.revision); // An atom with no recorded visibility is private (derived pages fail closed). existing.visibilities.push(atom.visibility ?? 'private'); groups.set(conceptSlug, existing); @@ -244,6 +258,7 @@ export async function runPhaseSynthesizeConcepts( atomSlugs: data.slugs, atomTitles: data.titles, atomBodies: data.bodies, + atomRevisions: data.revisions, visibility: strictestVisibility(data.visibilities), tier, }); @@ -335,6 +350,9 @@ export async function runPhaseSynthesizeConcepts( const publicationPending: Array<{ concept: string; reason: string }> = []; const skippedHumanOwned: string[] = []; const skippedDeleted: string[] = []; + const rebuilds: ConceptWrite[] = []; + const rebuildDeferred: Array<{ concept: string; reason: string }> = []; + const rebuildKept: RebuildKept[] = []; const skippedUnchanged: string[] = []; const provenanceRestored: string[] = []; const rehashed: string[] = []; @@ -368,8 +386,11 @@ export async function runPhaseSynthesizeConcepts( // A concept page this phase did not write belongs to a human (or another // writer). Check before any spend; never replace its body. const existingSnapshot = await engine.readPageSnapshot(conceptSlug, { sourceId: opts.sourceId ?? 'default', includeDeleted: true }); - if (existingSnapshot?.page.deleted_at) { skippedDeleted.push(conceptSlug); continue; } // #6161: a deleted concept is never resurrected - const existing = existingSnapshot?.page ?? null; + // #6161: a deleted concept is never resurrected, except (#9653) one hidden only by an input purge and carrying nothing + // stated: after the model call its tombstone is purged and a fresh page written from the current members (concept-rebuild.ts). + const rebuild = existingSnapshot?.page.deleted_at ? await conceptRebuildFor(engine, src, existingSnapshot, group, !!opts.dryRun, rebuildKept) : null; + if (existingSnapshot?.page.deleted_at && !rebuild) { skippedDeleted.push(conceptSlug); continue; } + const existing = rebuild ? null : existingSnapshot?.page ?? null; if (existing && !String(existing.frontmatter?.synthesized_by ?? '').startsWith('synthesize_concepts')) { skippedHumanOwned.push(conceptSlug); continue; @@ -405,7 +426,7 @@ export async function runPhaseSynthesizeConcepts( continue; } // #6643 (B1): a drifted concept would only add a conflict receipt per publication; checked live before any spend. - if (await driftSkips.skip(conceptSlug, existingSnapshot)) continue; + if (!rebuild && await driftSkips.skip(conceptSlug, existingSnapshot)) continue; const held = existing && conceptPublicationHold(existing); // checked before any spend if (held) { publicationHeld.push({ concept: group.conceptSlug, reason: held }); continue; } // A page hashed by the pre-D-N3 formula (full atom bodies) whose inputs are @@ -505,12 +526,17 @@ export async function runPhaseSynthesizeConcepts( keptExistingNarrative.push(conceptSlug); continue; } + // #9653: a failed synthesis never rebuilds a held concept; it stays hidden and held for the next cycle. + if (rebuild && synthesisMode !== 'llm' && synthesisMode !== 'deterministic_tier') { rebuildDeferred.push({ concept: conceptSlug, reason: 'the synthesis did not produce a narrative; retried next run' }); continue; } if (!grandfathered) synthesisModeCounts[synthesisMode]++; await stopIfAborted(); if (!opts.dryRun) { + // #9653: managed, the tombstone's retention purge commits before the fresh page is queued; otherwise nothing more is written. + const purged = rebuild && maintenance ? await submitHeldConceptPurge(engine, src, conceptSlug, rebuild) : true; + if (purged !== true) { rebuildDeferred.push({ concept: conceptSlug, reason: purged }); continue; } // #5525: tighten-only — a concept already private stays private. - const prior = await engine.getPage(conceptSlug, { sourceId: src }); + const prior = rebuild ? null : await engine.getPage(conceptSlug, { sourceId: src }); const visibility = strictestVisibility([group.visibility, prior?.frontmatter?.visibility === 'private' ? 'private' : 'world']); // #2163: serialize to markdown and import via the canonical pipeline so // the page is chunked (+ embedded when a provider is configured) — @@ -530,9 +556,10 @@ export async function runPhaseSynthesizeConcepts( // edge is durable, because a later private flip reaches it through them. // GBRA-60: one whose edges already cover every member publishes once, at // world, so a strict source never commits an intermediate private page. - const covered = visibility === 'world' && await conceptProvenanceCovers(engine, src, conceptSlug, group.atomSlugs); + const covered = !rebuild && visibility === 'world' && await conceptProvenanceCovers(engine, src, conceptSlug, group.atomSlugs); const write: ConceptWrite = { concept: group.conceptSlug, conceptSlug, atomSlugs: group.atomSlugs, visibility, covered, synthesisMode, synthesized, narrative, - revision: existingSnapshot?.revision ?? null, baseline: existing?.compiled_truth ?? '' }; + revision: rebuild ? null : existingSnapshot?.revision ?? null, baseline: existing?.compiled_truth ?? '', ...(rebuild ? { rebuild: maintenance ? 'purged' as const : rebuild } : {}) }; + if (rebuild) rebuilds.push(write); // GBRA-60: a managed run's concepts publish in batches (concept-writes.ts), each one publication group on Postgres. await stopIfAborted(); await (maintenance ? writer.queue(write) : writer.publish(write)); @@ -588,6 +615,7 @@ export async function runPhaseSynthesizeConcepts( }); } + const rebuilt = rebuilds.filter(write => write.rebuilt).map(write => write.conceptSlug); return reportDerivedWriteThrough({ phase: 'synthesize_concepts', status: failures.length > 0 || linkWarnings.length > 0 || publicationDeferred.length > 0 || publicationHeld.length > 0 || publicationPending.length > 0 @@ -599,6 +627,9 @@ export async function runPhaseSynthesizeConcepts( (failures.length > 0 ? ` (${failures.length} LLM-failed → template fallback)` : '') + (budgetCapped > 0 ? ` (${budgetCapped} over the $${budgetCap.toFixed(2)} budget → template fallback)` : '') + (linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : '') + + (rebuilt.length > 0 ? ` (${rebuilt.length} hidden by an input purge rebuilt)` : '') + + (rebuildDeferred.length > 0 ? ` (${rebuildDeferred.length} hidden by an input purge left hidden for the next run)` : '') + + (rebuildKept.length > 0 ? ` (${rebuildKept.length} hidden by an input purge kept hidden: ${rebuildKept.map(keptReason).join('; ')})` : '') + (skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : '') + (skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') + (rehashed.length > 0 ? ` (${rehashed.length} rehashed without synthesis)` : '') + @@ -619,6 +650,9 @@ export async function runPhaseSynthesizeConcepts( warnings, skipped_human_owned: skippedHumanOwned, skipped_deleted: skippedDeleted, + rebuilt, + rebuild_deferred: rebuildDeferred, + rebuild_kept: rebuildKept, skipped_unchanged: skippedUnchanged, provenance_restored: provenanceRestored, rehashed, diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts index 8e7ddbbe97a..314f4de7555 100644 --- a/src/core/engine-sql/pages.ts +++ b/src/core/engine-sql/pages.ts @@ -333,15 +333,18 @@ export async function restorePage(exec: SqlExecutor, slug: string, opts?: { sour export async function purgeDeletedPages( exec: SqlExecutor, olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }> { // Clamp to non-negative integer; runaway purge protection. The DELETE // cascades through content_chunks, page_links, chunk_relations via FKs. const hours = Math.max(0, Math.floor(olderThanHours)); // GBRA-130 A-49: tombstones the unmanaged belief-ledger expiry could not delete (or parked) stay for their own retry. + // #9653: `onlyIds` narrows the same statements to those pages (a concept rebuild's one tombstone). + const only = opts?.onlyIds ? sqlFragment` AND pages.id = ANY(${opts.onlyIds}::bigint[])` : sqlFragment``; + const onlyManifest = opts?.onlyIds ? sqlFragment` AND p.id = ANY(${opts.onlyIds}::bigint[])` : sqlFragment``; const excluded = opts?.excludeIds?.length ? sqlFragment` - AND NOT (pages.id = ANY(${opts.excludeIds}::bigint[]))` : sqlFragment``; - const excludedManifest = opts?.excludeIds?.length ? sqlFragment` AND NOT (p.id = ANY(${opts.excludeIds}::bigint[]))` : sqlFragment``; + AND NOT (pages.id = ANY(${opts.excludeIds}::bigint[]))${only}` : only; + const excludedManifest = opts?.excludeIds?.length ? sqlFragment` AND NOT (p.id = ANY(${opts.excludeIds}::bigint[]))${onlyManifest}` : onlyManifest; if (opts?.dryRun) { // SAME WHERE predicate as the DELETE below (same cutoff arithmetic, // same DB now() clock source) — only the verb differs, so preview and diff --git a/src/core/engine.ts b/src/core/engine.ts index 50fe860e503..ed2245d878a 100644 --- a/src/core/engine.ts +++ b/src/core/engine.ts @@ -1117,12 +1117,12 @@ export interface BrainEngine { * the cutoff (or is soft-deleted/restored) between the two statements. * Dry-run responses additionally carry `pages` (slug, source_id, deleted_at) for * display; the destructive path leaves `pages` undefined. - * `opts.excludeIds` keeps those page ids out of both (GBRA-130 A-49: the - * tombstones the unmanaged belief-ledger expiry failed or parked). + * `opts.excludeIds` keeps those page ids out of both (GBRA-130 A-49: tombstones the unmanaged belief-ledger + * expiry failed or parked); `opts.onlyIds` limits both to those ids under the same holds (#9653 concept rebuild). */ purgeDeletedPages( olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }>; /** * v0.26.5: by default `listPages` excludes soft-deleted rows. Set diff --git a/src/core/persistence/concept-rebuild.ts b/src/core/persistence/concept-rebuild.ts new file mode 100644 index 00000000000..5c570f0d86b --- /dev/null +++ b/src/core/persistence/concept-rebuild.ts @@ -0,0 +1,310 @@ +/** + * #9653: a concept the input purge hid is rebuilt as a new page. purge's hideDerivedRows soft-deletes a concept derived + * from a purged input and marks it needs_rederive with marked_at equal to the deleted_at it set; while that mark is open + * the automatic purge keeps the tombstone (purge-deleted.ts readRederiveHeldConcepts). The next synthesis, after its + * model call, hard-purges that one tombstone through the purge's own code and writes a fresh concept at the slug from + * the current members only. Unmanaged, both run in one transaction under the page lock; managed, the retention purge + * is submitted pinned to the tombstone's revision and the publish follows only once its receipt shows it committed. + * A purged slug is written again by any later synthesis, so a run that stops between the two leaves nothing a person + * must fix. A concept carrying anything a person or an agent stated, or whose fresh access would be wider than the + * tombstone's, is never rebuilt: it stays hidden and held. The rebuild's retention purge is no person's delete, so any + * later record of "a person deleted this concept" must stay outside it. Everything lives in the database, so a + * repo-less brain gets it unchanged. + */ +import { randomUUID } from 'node:crypto'; +import type { BrainEngine, PageSnapshot } from '../engine.ts'; +import type { OperationContext } from '../ops/contract.ts'; +import { loadConfig } from '../config.ts'; +import { submitPageMutation } from './page-mutations.ts'; +import { linkStreamSlugs } from './page-purge.ts'; +import { withBeliefBatch } from '../belief/ledger.ts'; +import { markBeliefCommits } from '../belief/append.ts'; +import { maintenancePublishWaitMs } from './maintenance-wait.ts'; +import { pendingRequestId } from '../cycle/dream-write-deferral.ts'; +import { OWED_PURGE_OP } from './derived-origin-hold.ts'; +import { extractedFromPageSql } from '../facts/gone-page-facts.ts'; +import { PRIVACY_ALIASES, privacyPartSql, privatePagesFilterFragment } from '../search/private-visibility.ts'; +import { preservedConceptSections } from '../cycle/concept-sections.ts'; +import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts'; +import { BOUNDED_PREFIX_BYTES } from '../page-window/document.ts'; +import { managedPersistenceEnabled } from './ownership.ts'; + +type Sql = Pick; + +/** The tombstone a synthesis rebuilds: its row, delete instant and revision, and the members (at the revisions read). */ +export interface ConceptRebuild { page_id: number; deleted_us: string; revision: string; members: Array<{ slug: string; revision: string }> } + +/** Why a held concept is not rebuilt: something a person or an agent stated (with the kinds), no model, or wider access. */ +export type RebuildKept = { source_id: string; slug: string } & ({ reason: 'stated'; kinds: string[] } | { reason: 'no_model' } | { reason: 'managed' } | { reason: 'access'; why: string }); + +let managedRebuild = false; +/** GST-3179 re-checks the hold and the members inside the write owner's transaction; until then a managed brain keeps its held concepts hidden. */ +export function __setManagedConceptRebuildForTests(on: boolean): void { managedRebuild = on; } +const managedHeld = async (engine: Sql) => !managedRebuild && await managedPersistenceEnabled(engine); + +/** Frontmatter keys only an owner or an agent sets on a concept (synthesis writes visibility alone): any of them is stated. */ +const STATED_LABEL_KEYS: readonly string[] = [...Object.keys(PRIVACY_ALIASES), 'readable_by', 'pinned_question', 'derived_from']; + +/** Link provenances a reconciler derives from page text; any other one (add_link's 'manual' or a caller's tag) is stated. */ +const DERIVED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved', 'concept-provenance']; + +/** + * Every store a hard purge of a page removes rows from, keyed as the purge receipt names them + * (test/concept-purge-rebuild-9653.test.ts fails on a receipt key missing here). `stated`: a row there was stated by a + * person or an agent, and a concept with one is never rebuilt (statedKinds checks each). `derived`: rows built from the + * page's own body or kept as telemetry, which the purge drops and the fresh page rebuilds as needed. + */ +export const REBUILD_STORES: Readonly> = { + facts: 'stated', takes: 'stated', timeline_entries: 'stated', page_aliases: 'stated', slug_aliases: 'stated', tags: 'stated', + files: 'stated', raw_data: 'stated', secret_store: 'stated', secret_store_occurrence: 'stated', core_edit_notices: 'stated', write_gate_holds: 'stated', write_gate_receipts: 'stated', links: 'stated', labels: 'stated', + pages: 'derived', page_versions: 'derived', content_chunks: 'derived', query_cache: 'derived', take_proposals: 'derived', open_loops: 'derived', + slug_rename_history: 'derived', trust_proposals: 'derived', decide_proposals: 'derived', decide_review_queue: 'derived', + decide_review_proposals: 'derived', persistence_requests: 'derived', persistence_effects: 'derived', derived_generations: 'derived', + derived_generation_items: 'derived', retrieval_event_pages: 'derived', retrieval_event_links: 'derived', retrieval_feedback: 'derived', + retrieval_weights: 'derived', 'eval_candidates.retrieved_slugs': 'derived', mention_gazetteer_entries: 'derived', + context_volunteer_events: 'derived', op_checkpoints: 'derived', belief_events: 'derived', + page_body_manifest: 'derived', page_body_stagings: 'derived', page_segment_texts: 'derived', +}; + +/** + * Every column of links (test/concept-purge-rebuild-9653.test.ts fails on one missing here). An incoming link the fresh + * page takes over keeps each carried column; to_page_id, and an origin_page_id naming the old row, point at the fresh row. + */ +export const REBUILD_LINK_COLUMNS: Readonly> = { + id: 'regenerated', from_page_id: 'carried', to_page_id: 'carried', link_type: 'carried', context: 'carried', link_source: 'carried', + link_kind: 'carried', origin_page_id: 'carried', origin_field: 'carried', resolution_type: 'carried', created_at: 'carried', assertion_tense: 'carried', +}; +const CARRIED_LINK_COLUMNS = Object.keys(REBUILD_LINK_COLUMNS).filter(column => REBUILD_LINK_COLUMNS[column] === 'carried'); +/** The fresh row at (`$1`, `$2`), with the incoming links `$3` (to_jsonb rows of the old row `$4`) carried onto it. */ +const CARRY_LINKS_SQL = `WITH fresh AS (SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL), + carried AS (INSERT INTO links (${CARRIED_LINK_COLUMNS.join(', ')}) SELECT ${CARRIED_LINK_COLUMNS.map(column => column === 'to_page_id' ? 'fresh.id' + : column === 'origin_page_id' ? 'CASE WHEN r.origin_page_id = $4::int THEN fresh.id ELSE r.origin_page_id END' : `r.${column}`).join(', ')} + FROM fresh, jsonb_populate_recordset(NULL::links, $3::text::jsonb) r ON CONFLICT DO NOTHING RETURNING 1) + SELECT id, (SELECT count(*)::int FROM carried) AS carried FROM fresh`; + +/** Frontmatter keys synthesis and its write path set on a concept (synthesize-concepts.ts, serializeMarkdown, the trust stamp); any other key keeps it hidden. */ +const SYNTHESIS_KEYS: readonly string[] = ['type', 'title', 'trust_tier', 'tier', 'mention_count', 'composite_score', 'synthesis_mode', 'member_hash', + 'synthesized_at', 'synthesized_by', 'visibility', 'unverified_claims']; + +const WIDER = 'its current members are all world-readable and the hidden concept was not'; + +const HELD_SQL = `p.deleted_at IS NOT NULL AND p.type = 'concept' AND coalesce(p.frontmatter->>'synthesized_by', '') LIKE 'synthesize_concepts%' + AND EXISTS (SELECT 1 FROM needs_rederive n WHERE n.derived_table = 'pages' AND n.derived_id = p.id::text AND n.marked_at = p.deleted_at) + AND NOT EXISTS (SELECT 1 FROM op_checkpoints o WHERE o.op = '${OWED_PURGE_OP}' AND o.fingerprint = p.id::text)`; +const DELETED_US = `floor(extract(epoch FROM p.deleted_at)*1000000)::bigint::text`; + +/** + * What on or about the concept row `$1` (source `$2`, slug `$3`) synthesis did not write: REBUILD_STORES kinds for rows a + * person or an agent stated, plus a title other than the slug's, a frontmatter key synthesis does not write, a stored + * timeline, a file other than `.md`, dated link transitions, an attached raw_data payload, a person's decision on an + * edge proposal (rejected, undone or reverted), an entity identity, a guest mark or promotion, and a sealed secret original recorded on the page (even one copied + * from a live member, until entries can be compared across pages). + */ +const STATED_SQL = `SELECT array_remove(ARRAY[ + CASE WHEN EXISTS (SELECT 1 FROM facts f WHERE f.source_id = $2 AND (f.entity_slug = $3 OR f.source_markdown_slug = $3) AND NOT ${extractedFromPageSql('f', '$3')}) THEN 'facts' END, + CASE WHEN EXISTS (SELECT 1 FROM takes t WHERE t.page_id = $1) THEN 'takes' END, + CASE WHEN EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = $1) THEN 'timeline_entries' END, + CASE WHEN EXISTS (SELECT 1 FROM links l WHERE (l.to_page_id = $1 OR l.from_page_id = $1) AND l.link_source IS NOT NULL + AND l.link_source <> ALL($4::text[])) THEN 'links' END, + CASE WHEN EXISTS (SELECT 1 FROM tags t WHERE t.page_id = $1) THEN 'tags' END, + CASE WHEN EXISTS (SELECT 1 FROM files x WHERE x.page_id = $1) THEN 'files' END, + CASE WHEN EXISTS (SELECT 1 FROM page_aliases a WHERE a.source_id = $2 AND a.slug = $3) THEN 'page_aliases' END, + CASE WHEN EXISTS (SELECT 1 FROM slug_aliases a WHERE a.source_id = $2 AND a.canonical_slug = $3) THEN 'slug_aliases' END, + CASE WHEN EXISTS (SELECT 1 FROM core_edit_notices c WHERE c.source_id = $2 AND c.slug = $3) THEN 'core_edit_notices' END, + CASE WHEN EXISTS (SELECT 1 FROM write_gate_holds h WHERE h.source_id = $2 AND h.slug = $3) THEN 'write_gate_holds' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.title <> replace(regexp_replace(p.slug, '^.*/', ''), '-', ' ')) THEN 'title' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p, jsonb_each(p.frontmatter) e WHERE p.id = $1 AND e.key <> ALL($6::text[]) AND e.key <> ALL($5::text[]) + AND NOT (e.key = 'tags' AND e.value = '[]'::jsonb)) THEN 'frontmatter' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND p.body_storage IS DISTINCT FROM 'segmented' AND coalesce(p.timeline, '') <> '') THEN 'timeline' END, + CASE WHEN EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 AND ((p.source_path IS NOT NULL AND p.source_path <> p.slug || '.md') + OR p.source_uri IS NOT NULL OR p.withheld_source_path IS NOT NULL)) THEN 'source_path' END, + CASE WHEN EXISTS (SELECT 1 FROM link_transitions t WHERE t.from_page_id = $1 OR t.to_page_id = $1 OR t.origin_page_id = $1) THEN 'link_transitions' END, + CASE WHEN EXISTS (SELECT 1 FROM raw_data r WHERE r.page_id = $1) THEN 'raw_data' END, + CASE WHEN EXISTS (SELECT 1 FROM link_edge_proposals e WHERE $1 IN (e.from_page_id, e.a_to_page_id, e.b_to_page_id, e.ending_to_page_id) + AND e.status IN ('rejected', 'undone', 'reverted_by_user')) THEN 'link_edge_proposals' END, + CASE WHEN EXISTS (SELECT 1 FROM entity_identities i WHERE i.page_id = $1) THEN 'entity_identities' END, + CASE WHEN EXISTS (SELECT 1 FROM guest_marks g WHERE g.page_id = $1) THEN 'guest_marks' END, + CASE WHEN EXISTS (SELECT 1 FROM guest_promotions g WHERE g.guest_page_id = $1) THEN 'guest_promotions' END, + CASE WHEN EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.source_id = $2 AND o.commit_sha IS NULL + AND (o.page_id = $1 OR (o.page_id IS NULL AND o.slug = $3))) THEN 'secret_store_occurrence' END, + CASE WHEN EXISTS (SELECT 1 FROM page_label_guards g WHERE g.page_id = $1) OR EXISTS (SELECT 1 FROM pages p WHERE p.id = $1 + AND p.frontmatter ?| $5::text[]) THEN 'labels' END +], NULL) AS kinds, + (SELECT ${boundedBodyPrefixSql('p')} FROM pages p WHERE p.id = $1) AS lead, (SELECT p.body_storage = 'segmented' FROM pages p WHERE p.id = $1) AS segmented`; + +/** What the concept carries that synthesis did not write, as kinds; empty when it carries nothing else. */ +export async function statedKinds(engine: Sql, pageId: number, sourceId: string, slug: string): Promise { + const [row] = await engine.executeRaw<{ kinds: string[] | null; lead: string | null; segmented: boolean | null }>(STATED_SQL, [pageId, sourceId, slug, DERIVED_LINK_SOURCES, STATED_LABEL_KEYS, SYNTHESIS_KEYS]); + // A body past the bounded lead is not scanned, so it may hold curated sections and counts as if it did. + const unread = row?.segmented === true || (row?.lead ?? '').length >= BOUNDED_PREFIX_BYTES; + return [...row?.kinds ?? [], ...unread || preservedConceptSections(row?.lead ?? '').length ? ['curated_sections'] : []]; +} + +/** Who may read a page, as the read predicate decides it: compared before and after a rebuild (rebuildWidens). */ +export interface RebuildAccess { open: boolean; public_part: boolean; readers: string[] | null; page_readers: string[] | null; folder_rule_ids: string[] | null } +const ACCESS_SQL = `SELECT ${privatePagesFilterFragment('p')} AS open, ${privacyPartSql('p')} AS public_part, gbrain_access_readers(p.frontmatter) AS readers, + p.page_readers, p.folder_rule_ids FROM pages p WHERE p.id = $1`; + +export async function readRebuildAccess(engine: Sql, pageId: number): Promise { + return (await engine.executeRaw(ACCESS_SQL, [pageId]))[0] ?? null; +} + +/** Why the fresh page would be readable by someone who could not read the tombstone, or null. Anything it cannot tell widens. */ +export function rebuildWidens(before: RebuildAccess | null | undefined, after: RebuildAccess | null | undefined): string | null { + if (!before || !after) return 'its access could not be read'; + const within = (inner: readonly string[] | null, outer: readonly string[] | null) => (inner ?? []).every(id => (outer ?? []).includes(id)); + if (!before.open && after.open) return 'it would be readable by any caller'; + if (!before.public_part && after.public_part) return 'it would no longer be private'; + if (before.readers && (!after.readers || !within(after.readers, before.readers))) return 'it would name readers the hidden concept did not'; + if (before.page_readers && (!after.page_readers || !within(after.page_readers, before.page_readers))) return 'its stored readers would widen'; + if (before.folder_rule_ids && (!after.folder_rule_ids || !within(before.folder_rule_ids, after.folder_rule_ids))) return 'a folder rule would stop covering it'; + return null; +} + +/** + * The rebuild a synthesis would run for `snapshot`, a tombstone. Null when the concept is not held (a person or a sync + * deleted it, or an owner purge is owed); `kept` when it is held but carries something stated, or when its fresh + * visibility (`visibility`, derived from the current members) would be wider than the tombstone's. Records each + * member at `read`, the revision its body was read at for the narrative, so the rebuild refuses when one moved. + */ +export async function heldConceptRebuild(engine: Sql, sourceId: string, snapshot: PageSnapshot, members: readonly string[], + read: ReadonlyArray, visibility: 'private' | 'world'): Promise<{ rebuild: ConceptRebuild } | { kept: RebuildKept } | null> { + const pageId = Number(snapshot.page.id); + const [held] = await engine.executeRaw<{ deleted_us: string }>(`SELECT ${DELETED_US} AS deleted_us FROM pages p WHERE p.id = $1 AND ${HELD_SQL}`, [pageId]); + if (!held) return null; + const slug = snapshot.page.slug; + const kinds = await statedKinds(engine, pageId, sourceId, slug); + if (kinds.length) return { kept: { source_id: sourceId, slug, reason: 'stated', kinds } }; + if (await managedHeld(engine)) return { kept: { source_id: sourceId, slug, reason: 'managed' } }; + const access = await readRebuildAccess(engine, pageId); + if (!access || (visibility === 'world' && !access.public_part)) return { kept: { source_id: sourceId, slug, reason: 'access', why: WIDER } }; + const rows = await engine.executeRaw<{ slug: string; revision: string }>(`SELECT slug, knowledge_revision::text AS revision FROM pages + WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [sourceId, [...new Set(members)]]); + if (!rows.length || rows.length !== new Set(members).size) return null; + const readAt = new Map(members.flatMap((m, i) => read[i] === undefined ? [] : [[m, read[i]!] as const])); + return { rebuild: { page_id: pageId, deleted_us: held.deleted_us, revision: snapshot.revision, + members: rows.map(row => ({ slug: row.slug, revision: readAt.get(row.slug) ?? row.revision })) } }; +} + +/** + * Unmanaged, inside the rebuild's transaction and under the page lock: confirms the concept is still held at the same + * delete, carries nothing stated and every member is live at the revision the narrative read (locking them against a + * purge), then hard-purges the tombstone with the expiry's own statements (engine purgeDeletedPages, onlyIds). Returns + * why it purged nothing, or the tombstone's access and the incoming links the fresh page takes over. + */ +async function purgeHeldConcept(tx: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { + const [held] = await tx.executeRaw<{ id: number }>(`SELECT p.id FROM pages p WHERE p.id = $1 AND p.source_id = $2 AND p.slug = $3 + AND ${DELETED_US} = $4 AND ${HELD_SQL} FOR UPDATE OF p`, [rebuild.page_id, sourceId, slug, rebuild.deleted_us]); + if (!held) return 'The concept is no longer held for a rebuild (a person or sync deleted, restored or purged it), so the rebuild wrote nothing.'; + if ((await statedKinds(tx, rebuild.page_id, sourceId, slug)).length) return 'Something was stated on the concept during synthesis, so the rebuild wrote nothing and it stays held.'; + const live = await tx.executeRaw(`SELECT m.slug FROM pages m JOIN jsonb_to_recordset($2::text::jsonb) AS r(slug text, revision text) + ON m.slug = r.slug AND m.knowledge_revision::text = r.revision WHERE m.source_id = $1 AND m.deleted_at IS NULL FOR SHARE OF m`, [sourceId, JSON.stringify(rebuild.members)]); + if (!rebuild.members.length || live.length !== rebuild.members.length) return 'A member the rebuilt narrative was built from changed or was removed during synthesis, so the rebuild wrote nothing; the next run builds it again.'; + const access = await readRebuildAccess(tx, rebuild.page_id); + const incoming = (await tx.executeRaw<{ link: unknown }>(`SELECT to_jsonb(l) AS link FROM links l JOIN pages f ON f.id = l.from_page_id + WHERE l.to_page_id = $1 AND l.from_page_id <> $1 AND f.deleted_at IS NULL AND l.link_source IS DISTINCT FROM 'concept-provenance'`, [rebuild.page_id])).map(row => row.link); + const { parkUncarriedInPurge } = await import('../repair/origin-carry.ts'); + if ((await parkUncarriedInPurge(tx, [rebuild.page_id])).length) { + return { parked: 'A page written since depends on the concept for its privacy, so the concept is parked until the next purge labels it and the rebuild wrote nothing.' }; + } + const purged = await tx.purgeDeletedPages(0, { onlyIds: [rebuild.page_id] }); + if (purged.count !== 1 || !access) return 'The tombstone is held by another purge rule, so the rebuild wrote nothing and it stays held.'; + return { access, incoming, oldId: rebuild.page_id }; +} + +/** Unmanaged, after the fresh write in the same transaction: points the incoming links at it and confirms it reads no wider. */ +async function finishConceptRebuild(tx: BrainEngine, sourceId: string, slug: string, before: { access: RebuildAccess; incoming: unknown[]; oldId: number }): Promise { + const [fresh] = await tx.executeRaw<{ id: number }>(CARRY_LINKS_SQL, [sourceId, slug, JSON.stringify(before.incoming), before.oldId]); + if (!fresh) throw Object.assign(new Error('The rebuilt concept was not written (the import refused it), so the rebuild wrote nothing and the concept stays held.'), { code: 'revision_conflict' }); + const widened = rebuildWidens(before.access, await readRebuildAccess(tx, Number(fresh.id))); + if (widened) { + const error: Error & { code?: string } = new Error(`The rebuilt concept would be readable more widely than the hidden one (${widened}), so the rebuild wrote nothing and the concept stays held.`); + error.code = 'revision_conflict'; + throw error; + } +} + +/** + * Unmanaged: one transaction purges the held tombstone, writes the fresh page through `write` and carries the incoming + * links over. Like the expiry of a recorded tombstone (purge-deleted.ts), it runs in one belief batch over the page and + * its link streams, so the ledger ends the old page's lifetime as `page.expired` and the fresh page starts a new one. + */ +export async function rebuildHeldConcept(engine: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild, write: (tx: BrainEngine) => Promise): Promise { + const publicationId = randomUUID(), report = { appended: 0 }; + let parked: string | undefined; + await engine.transaction(async tx => { + const slugs = [...new Set([slug, ...await linkStreamSlugs(tx, sourceId, rebuild.page_id)])].sort(); + await tx.lockPageKeys(slugs.map(key => ({ sourceId, slug: key }))); + await withBeliefBatch(tx, { sourceId, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report }, async () => { + const before = await purgeHeldConcept(tx, sourceId, slug, rebuild); + if (typeof before === 'string') throw Object.assign(new Error(before), { code: 'revision_conflict' }); + if ('parked' in before) { parked = before.parked; return; } + await write(tx); + await finishConceptRebuild(tx, sourceId, slug, before); + }); + }); + if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined); + if (parked) throw Object.assign(new Error(parked), { code: 'revision_conflict' }); +} + +/** + * Managed: submits the retention purge of the tombstone, pinned to the revision the synthesis read, so a person's edit, + * restore or delete in between refuses it. True only when its receipt shows the purge committed; a pending, failed or + * refused purge returns why, and the next synthesis handles whatever it finds. + */ +export async function submitHeldConceptPurge(engine: BrainEngine, sourceId: string, slug: string, rebuild: ConceptRebuild): Promise { + const live = await engine.executeRaw(`SELECT m.slug FROM pages m JOIN jsonb_to_recordset($2::text::jsonb) AS r(slug text, revision text) + ON m.slug = r.slug AND m.knowledge_revision::text = r.revision WHERE m.source_id = $1 AND m.deleted_at IS NULL`, [sourceId, JSON.stringify(rebuild.members)]); + if (live.length !== rebuild.members.length) return 'a member the rebuilt narrative was built from changed or was removed during synthesis'; + const [held] = await engine.executeRaw(`SELECT 1 FROM pages p WHERE p.id = $1 AND ${DELETED_US} = $2 AND ${HELD_SQL}`, [rebuild.page_id, rebuild.deleted_us]); + if (!held) return 'the concept is no longer held for a rebuild (a person or sync deleted, restored or purged it)'; + if ((await statedKinds(engine, rebuild.page_id, sourceId, slug)).length) return 'something was stated on the concept during synthesis'; + const ctx: OperationContext = { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, sourceId, dryRun: false, + logger: { info() {}, warn() {}, error() {} } }; + try { + const purged = await submitPageMutation(ctx, { operation: 'delete_page', waitMs: maintenancePublishWaitMs(), params: { slug, source_id: sourceId, + purge: true, retention: true, expected_revision: rebuild.revision, request_id: randomUUID() } }); + return purged.status === 'purged' ? true : `the purge of the hidden concept did not commit (${String(purged.status ?? 'no status')})`; + } catch (error) { + const pending = pendingRequestId(error); + if (pending) return `the purge of the hidden concept is accepted and still pending (request_id ${pending})`; + return `the purge of the hidden concept was refused: ${error instanceof Error ? error.message : String(error)}`; + } +} + +/** + * Every held concept and, for those the next synthesis will not rebuild, why (the purge previews name them). `model`: + * whether a synthesis model is configured; without one a concept built from many atoms is not rebuilt. + */ +export async function readHeldConcepts(engine: Sql, model: boolean): Promise<{ held: Array<{ source_id: string; slug: string }>; kept: RebuildKept[] }> { + const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; private: boolean; members_private: boolean }>(`SELECT p.id, p.source_id, p.slug, + NOT ${privacyPartSql('p')} AS private, + EXISTS (SELECT 1 FROM derivation_inputs d JOIN pages m ON m.id::text = d.input_id AND d.input_table = 'pages' + WHERE d.derived_table = 'pages' AND d.derived_id = p.id::text AND m.deleted_at IS NULL AND NOT (${privatePagesFilterFragment('m')})) AS members_private + FROM pages p WHERE ${HELD_SQL} ORDER BY p.source_id, p.slug`); + const kept: RebuildKept[] = []; + const managed = rows.length > 0 && await managedHeld(engine); + for (const row of rows) { + const kinds = await statedKinds(engine, Number(row.id), row.source_id, row.slug); + if (kinds.length) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'stated', kinds }); + else if (managed) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'managed' }); + else if (row.private && !row.members_private) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'access', why: WIDER }); + else if (!model) kept.push({ source_id: row.source_id, slug: row.slug, reason: 'no_model' }); + } + return { held: rows.map(({ source_id, slug }) => ({ source_id, slug })), kept }; +} + +/** When a tombstone's recovery window ends: its own delete plus `hours` (UTC, to the second), and whether that has passed. */ +export async function tombstoneWindow(tx: Sql, pageId: number, hours: number): Promise<{ until: string; past: boolean } | null> { + const [window] = await tx.executeRaw<{ until: string; past: boolean }>(`SELECT to_char((deleted_at + ($2 || ' hours')::interval) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS until, + deleted_at + ($2 || ' hours')::interval <= now() AS past FROM pages WHERE id = $1 AND deleted_at IS NOT NULL`, [pageId, String(hours)]); + return window ?? null; +} + +/** One preview line per kept concept, naming its reason. */ +export function keptReason(kept: RebuildKept): string { + if (kept.reason === 'stated') return `${kept.source_id}/${kept.slug}: stays hidden, it carries what a person or an agent stated (${kept.kinds.join(', ')})`; + if (kept.reason === 'access') return `${kept.source_id}/${kept.slug}: stays hidden, a rebuild would be readable more widely (${kept.why})`; + if (kept.reason === 'managed') return `${kept.source_id}/${kept.slug}: stays hidden, its rebuild on a managed brain waits for a later release`; + return `${kept.source_id}/${kept.slug}: stays hidden, no synthesis model is configured to rebuild it`; +} diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts index 02dec813093..3637f69d7d5 100644 --- a/src/core/persistence/page-prepare.ts +++ b/src/core/persistence/page-prepare.ts @@ -44,6 +44,7 @@ import { findLiveFileClaimants, type FileClaimant, type FileClaimTarget } from ' import { digest, sha256 } from './digest.ts'; import { replaceableFile } from '../facts/file-body-guard.ts'; import { releaseHiddenMoment } from '../facts/derivation-inputs.ts'; +import { tombstoneWindow } from './concept-rebuild.ts'; import { getWorktreeBinding } from './ownership.ts'; import type { PreparedContentImport } from './prepared-import.ts'; import type { PreparedMutation } from './coordinator.ts'; @@ -755,6 +756,7 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest, const observedRevision = snapshot.revision; const purge = p.purge === true; const noop = !purge && snapshot.page.deleted_at != null; + const retentionHours = purge ? 0 : await (await import('../sync-reconcile.ts')).readPurgeRetentionHours(engine); // Always-loaded core pages: a remote caller cannot delete one (owner-only). if (!noop) { enterClaimStep(clock, 'core_guard', undefined, 'db'); await prepareCoreGuard(engine, { row, snapshot, incoming: null }); } enterClaimStep(clock, 'file_target', undefined, 'fs'); @@ -826,8 +828,11 @@ async function prepareDeletePageMutation(engine: BrainEngine, row: WriteRequest, // GST-2518: a soft delete authors no content, so the tombstone keeps its tier (and a write over it the page's label guard). if (!noop) { await tx.createVersion(row.slug, source); await withTrustKeep(tx, ['pages'], () => tx.softDeletePage(row.slug, source)); } else await releaseHiddenMoment(tx, Number(snapshot.page.id)); + // #9653: a page already deleted keeps its tombstone's date, so its window runs from that date (a released hold included). + const window = noop ? await tombstoneWindow(tx, Number(snapshot.page.id), retentionHours) : null; + const until = !window ? `now + ${retentionHours}h` : window.past ? `the next purge (its ${retentionHours}h window ended ${window.until})` : window.until; return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop, - recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete --purge, local CLI only)' }; + recoverable_until: `${until} via restore_page (remove immediately instead: gbrain delete --purge, local CLI only)` }; } }; return prepared; } diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.ts index 6af272e2f8b..59a05833a83 100644 --- a/src/core/persistence/purge-deleted.ts +++ b/src/core/persistence/purge-deleted.ts @@ -33,7 +33,24 @@ async function readRederiveHeldConcepts(engine: Pick) AND EXISTS (SELECT 1 FROM needs_rederive n WHERE n.derived_table = 'pages' AND n.derived_id = p.id::text AND n.marked_at = p.deleted_at)`); return rows.map(row => Number(row.id)); } + +/** + * #9653: the preview lines for the concepts an input purge hid: how many the next concept synthesis rebuilds, and one + * line per concept it keeps hidden with the reason (concept-rebuild.ts). `removes` (an explicit purge) says it purges + * the expired ones instead. + */ +export function rebuildNote(rebuild: PurgeSelection['rebuild'], removes = false): string { + if (!rebuild.held.length) return ''; + const kept = new Set(rebuild.kept.map(k => `${k.source_id}/${k.slug}`)); + const next = rebuild.held.filter(c => !kept.has(`${c.source_id}/${c.slug}`)); + return [`${rebuild.held.length} concept(s) hidden by an input purge are kept out of the automatic purge.`, + ...(next.length ? [`${next.length} of them are rebuilt by the next concept synthesis that still finds at least two members for them (one with fewer stays hidden until an explicit purge): ${next.slice(0, 20).map(c => `${c.source_id}/${c.slug}`).join(', ')}${next.length > 20 ? ` and ${next.length - 20} more` : ''}.`] : []), + ...rebuild.kept.slice(0, 20).map(keptReason), ...(rebuild.kept.length > 20 ? [`...and ${rebuild.kept.length - 20} more kept hidden`] : []), + ...(removes ? ['This purge removes any of them listed above instead.'] : [])].join('\n'); +} + import { scrubPurgedSlugs } from '../feedback/store.ts'; +import { keptReason, readHeldConcepts, type RebuildKept } from './concept-rebuild.ts'; import { scrubPurgedNameStores } from './purge-name-stores.ts'; import { pageSecretOccurrences, scrubPurgedSlugHolds, scrubPurgedSlugStores } from './purge-slug-stores.ts'; import { expireGonePageFacts } from '../facts/gone-page-facts.ts'; @@ -248,6 +265,8 @@ export interface PurgeSelection { writers: Record; /** GST-2689: the candidates that are parked origins the run's carry releases first (`forecast.release`). */ released_origins: Array<{ source_id: string; slug: string }>; + /** #9653: the concepts an input purge hid, which an automatic purge keeps, and those the next synthesis will not rebuild, with why. */ + rebuild: { held: Array<{ source_id: string; slug: string }>; kept: RebuildKept[] }; } /** @@ -265,7 +284,7 @@ export function purgeHoldsSql(page: string, source: string, released?: string): * selection the run makes once its carry has run, so it counts the parked origins the carry releases and leaves out the * origins it parks; the run itself reads the parks as they are. */ -export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean; forecast?: CarryForecast } = {}): Promise { +export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: number, opts: { retryParked?: boolean; automatic?: boolean; forecast?: CarryForecast; model?: boolean } = {}): Promise { const release = (opts.forecast?.release ?? []).map(origin => origin.id), hold = (opts.forecast?.hold ?? []).map(origin => origin.id); if (!await managedPersistenceEnabled(engine)) { const parked = (await recordedTombstones(engine, String(Math.max(0, Math.floor(olderThanHours))), release)) @@ -287,7 +306,7 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: blocked: [...(opts.retryParked ? [] : parked.map(row => ({ source_id: row.source_id, slug: row.slug, code: 'purge_parked', reason: parkedReason(row.park) }))), ...held.map(row => syncDeleteHeld(row, olderThanHours))], parked: parked.map(row => ({ source_id: row.source_id, slug: row.slug, failures: row.park.failures, code: row.park.code, retried: opts.retryParked === true })), - inactive: 0, held: held.length, sync_unreviewed: opts.automatic ? 0 : unreviewed.filter(row => row.expired).length, writers: {} }; + inactive: 0, held: held.length, sync_unreviewed: opts.automatic ? 0 : unreviewed.filter(row => row.expired).length, writers: {}, rebuild: await readHeldConcepts(engine, opts.model ?? true) }; } const hours = Math.max(0, Math.floor(olderThanHours)); const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string; cutoff: string; deleted_us: string }>( @@ -300,7 +319,8 @@ export async function selectPurgeCandidates(engine: BrainEngine, olderThanHours: const parks = rows.length ? await readPurgeParks(engine) : new Map(); const unreviewed = new Set(rows.length ? (await readUnreviewedSyncTombstones(engine, hours)).map(row => row.id) : []); const rederive = new Set(rows.length && opts.automatic ? await readRederiveHeldConcepts(engine) : []); - const selection: PurgeSelection = { managed: true, count: 0, slugs: [], candidates: [], blocked: [], parked: [], inactive: 0, held: 0, sync_unreviewed: 0, writers: {}, released_origins: [] }; + const selection: PurgeSelection = { managed: true, count: 0, slugs: [], candidates: [], blocked: [], parked: [], inactive: 0, held: 0, sync_unreviewed: 0, writers: {}, released_origins: [], + rebuild: await readHeldConcepts(engine, opts.model ?? true) }; for (const { id, ...row } of rows) { const writer = states.get(row.source_id); const active = writer?.state !== 'recovery_required'; diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts index 60f0178f258..635a0187938 100644 --- a/src/core/pglite-engine.ts +++ b/src/core/pglite-engine.ts @@ -1337,7 +1337,7 @@ export class PGLiteEngine implements BrainEngine { async purgeDeletedPages( olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }> { return pagesImpl.purgeDeletedPages(this.engineSql, olderThanHours, opts); } diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts index 4f1a6fed012..ed1b31bb6d5 100644 --- a/src/core/postgres-engine.ts +++ b/src/core/postgres-engine.ts @@ -980,7 +980,7 @@ export class PostgresEngine implements BrainEngine { async purgeDeletedPages( olderThanHours: number, - opts?: { dryRun?: boolean; excludeIds?: number[] }, + opts?: { dryRun?: boolean; excludeIds?: number[]; onlyIds?: number[] }, ): Promise<{ slugs: string[]; count: number; pages?: { slug: string; source_id: string; deleted_at: Date }[] }> { return pagesImpl.purgeDeletedPages(this.engineSql, olderThanHours, opts); } diff --git a/src/core/secret-store/backup.ts b/src/core/secret-store/backup.ts index dc3b1bbf29a..826dd3a3206 100644 --- a/src/core/secret-store/backup.ts +++ b/src/core/secret-store/backup.ts @@ -139,7 +139,7 @@ export async function backupDue(engine: BrainEngine, backend?: string): Promise< export interface RestoreResult { object: string; key_id: string; inserted: number; existing: number; skipped_no_page: number; unreadable: string[]; occurrences: number } -export const SKIPPED_NO_PAGE_TEXT = 'skipped because their page is not in this brain (purged, or not synced yet)'; +export const SKIPPED_NO_PAGE_TEXT = 'skipped because no page in this brain holds their marker (purged, or not synced yet)'; export const SKIPPED_NO_PAGE_NEXT = 'Sync the pages, then run the same restore again.'; /** diff --git a/src/core/secret-store/marker-sql.ts b/src/core/secret-store/marker-sql.ts new file mode 100644 index 00000000000..7116c791e6c --- /dev/null +++ b/src/core/secret-store/marker-sql.ts @@ -0,0 +1,16 @@ +/** + * SQL that is true when page `p` (an alias over pages) holds a store marker for entry `idExpr` (a SQL text expression + * naming an `ss_` id): `:>` in its inline columns, its raw data, timeline entries, takes, outgoing + * link contexts or facts (repair/secret-spans.ts reads the same stores). A body stored in segments is not read here, + * so a segmented page holds a marker in SQL only through those other stores; insertBackupRows reads its segments. + */ +export function pageHoldsSql(p: string, idExpr: string): string { + const has = (text: string) => `(${text}) ~ ('')`; + return `(${has(`${p}.title || ' ' || coalesce(${p}.compiled_truth, '') || ' ' || coalesce(${p}.timeline, '') || ' ' || ${p}.frontmatter::text`)} + OR EXISTS (SELECT 1 FROM raw_data hr WHERE hr.page_id = ${p}.id AND ${has('hr.data::text')}) + OR EXISTS (SELECT 1 FROM timeline_entries ht WHERE (ht.page_id = ${p}.id OR ht.event_page_id = ${p}.id) AND ${has("ht.summary || ' ' || ht.detail || ' ' || ht.source")}) + OR EXISTS (SELECT 1 FROM takes hk WHERE hk.page_id = ${p}.id AND ${has("coalesce(hk.claim, '') || ' ' || coalesce(hk.source, '') || ' ' || coalesce(hk.resolved_source, '')")}) + OR EXISTS (SELECT 1 FROM links hl WHERE hl.from_page_id = ${p}.id AND ${has('hl.context')}) + OR EXISTS (SELECT 1 FROM facts hf WHERE hf.source_id = ${p}.source_id AND (hf.source_markdown_slug = ${p}.slug OR (hf.source_markdown_slug IS NULL AND hf.entity_slug = ${p}.slug)) + AND ${has("coalesce(hf.fact, '') || ' ' || coalesce(hf.context, '') || ' ' || coalesce(hf.value::text, '')")}))`; +} diff --git a/src/core/secret-store/store.ts b/src/core/secret-store/store.ts index 865fd283273..6943eff5fc8 100644 --- a/src/core/secret-store/store.ts +++ b/src/core/secret-store/store.ts @@ -13,6 +13,8 @@ import { createCipheriv, createDecipheriv, createHmac, randomBytes } from 'node:crypto'; import type { BrainEngine } from '../engine.ts'; import { opError } from '../ops/contract.ts'; +import { pageHoldsSql } from './marker-sql.ts'; +import { readSegmentedBody } from '../page-body/ingest.ts'; import { createAuditWriter } from '../audit/audit-writer.ts'; import { currentKey, keyById, keyIdOf, macKeyOf, SECRET_STORE_KEY_ENV, storeHost, keyringDir } from './keyring.ts'; @@ -218,14 +220,17 @@ export async function storeSnapshot(engine: BrainEngine): Promise<{ entries: Bac /** * Writes backed-up entries the store does not hold (by id, and never over a row that holds the same value, so a local - * row changed since the backup stays as it is), with the occurrences of the entries it wrote. An occurrence on a page - * (a slug and no commit) comes back only while that page exists in the source, live or soft-deleted; an entry whose - * every occurrence was on pages this brain does not hold is not written (`skipped_no_page`): the page was purged, or is - * not synced yet, and a restore cannot tell which, so it never brings back an original a page purge removed. Sync the - * pages, then run the same restore again; it adds what it skipped. An - * occurrence's page_id is the id of the page that holds its slug in the source now, never the backed-up number (a - * rebuilt brain numbers its pages in another order, and the purge cascade trusts page_id); entries of a source this - * brain no longer has are skipped. + * row changed since the backup stays as it is), with the occurrences of the entries it wrote or already holds. A place + * on a page (a slug and no commit) comes back only when the page at that slug holds the entry's marker (its segments + * read when its body is stored in segments; locked FOR SHARE, and the place takes that checked page's id only while it + * still holds the slug), so a restore never ties an original to a page that merely took its old slug. An + * entry recorded only on pages is written only while one of those pages holds its marker, and an entry whose places + * all failed to land (its page purged while the restore ran) is taken back out; otherwise it is not written + * (`skipped_no_page`): the page was purged, is not synced yet, or was renamed before the backup named it by its + * current slug, and a restore cannot tell which, so it never brings back an original a page purge removed. Sync the + * pages, then run the same restore again; it adds what it skipped. An occurrence's page_id is the id of the page that + * holds its slug now, never the backed-up number (a rebuilt brain numbers its pages in another order, and the purge + * cascade trusts page_id); entries of a source this brain no longer has are skipped. */ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntryRow[], occurrences: BackupOccurrenceRow[]): Promise<{ entries: number; occurrences: number; skipped_no_page: number }> { let written = 0, occ = 0, skippedNoPage = 0; @@ -235,34 +240,62 @@ export async function insertBackupRows(engine: BrainEngine, entries: BackupEntry await engine.transaction(async tx => { for (const row of entries) { const own = byEntry.get(row.id) ?? []; - const pageSlugs = [...new Set(own.filter(onPage).map(o => o.slug as string))]; const anchored = own.length === 0 || own.some(o => !onPage(o)); - const inserted = await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) + const holding = await holdingSlugs(tx, row.source_id, [...new Set(own.filter(onPage).map(o => o.slug as string))], row.id); + const inserted = anchored || holding.size ? await tx.executeRaw<{ id: string }>(`INSERT INTO secret_store (id,source_id,rule,ciphertext,nonce,tag,key_id,key_host,value_mac,status,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz,$12::timestamptz WHERE EXISTS (SELECT 1 FROM sources WHERE id=$2) - AND ($13::boolean OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($14::text[]))) ON CONFLICT DO NOTHING RETURNING id`, - [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at, anchored, pageSlugs]); + [row.id, row.source_id, row.rule, row.ciphertext, row.nonce, row.tag, row.key_id, row.key_host, row.value_mac, row.status, row.created_at, row.updated_at]) : []; if (inserted.length) written++; else { - const [held] = await tx.executeRaw<{ same: boolean | null; paged: boolean }>(`SELECT h.same, EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug = ANY($4::text[])) AS paged - FROM (SELECT 1) one LEFT JOIN (SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1) h ON true`, [row.id, row.source_id, row.value_mac, pageSlugs]); - if (held!.same === null && !anchored && !held!.paged) skippedNoPage++; - if (!held!.same) continue; + const [held] = await tx.executeRaw<{ same: boolean }>('SELECT (source_id=$2 AND value_mac=$3) AS same FROM secret_store WHERE id=$1', [row.id, row.source_id, row.value_mac]); + if (!held && !anchored && !holding.size) skippedNoPage++; + if (!held?.same) continue; } for (const o of own) { occ += (await tx.executeRaw(`INSERT INTO secret_store_occurrence (entry_id,source_id,page_id,slug,field,origin,commit_sha,path,line,pre_field_sha256,created_by,created_at) - SELECT $1,$2,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz - WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.source_id=$2 AND p.slug=$3)) + SELECT $1,$2,COALESCE($12::bigint,(SELECT id FROM pages WHERE source_id=$2 AND slug=$3)),$3,$4,$5,$6,$7,$8,$9,$10,$11::timestamptz + WHERE ($6::text IS NOT NULL OR $3::text IS NULL OR EXISTS (SELECT 1 FROM pages p WHERE p.id=$12::bigint AND p.source_id=$2 AND p.slug=$3)) AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence x WHERE x.entry_id=$1 AND x.source_id=$2 AND x.slug IS NOT DISTINCT FROM $3 AND x.field=$4 AND x.commit_sha IS NOT DISTINCT FROM $6 AND x.path IS NOT DISTINCT FROM $7 AND x.line IS NOT DISTINCT FROM $8::integer AND x.origin=$5 AND x.pre_field_sha256 IS NOT DISTINCT FROM $9 AND x.created_by=$10 AND date_trunc('milliseconds', x.created_at) = $11::timestamptz) RETURNING 1`, - [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at])).length; + [o.entry_id, o.source_id, o.slug, o.field, o.origin, o.commit_sha, o.path, o.line, o.pre_field_sha256, o.created_by, o.created_at, o.slug === null ? null : holding.get(o.slug) ?? null])).length; + } + if (!inserted.length || anchored) continue; + if ((await tx.executeRaw('DELETE FROM secret_store s WHERE s.id=$1 AND NOT EXISTS (SELECT 1 FROM secret_store_occurrence o WHERE o.entry_id=s.id) RETURNING 1', [row.id])).length) { + written--; + skippedNoPage++; } } }); return { entries: written, occurrences: occ, skipped_no_page: skippedNoPage }; } +/** + * The backed-up slugs whose page in the source holds entry `id`'s marker now: pageHoldsSql for every store SQL reads, + * and for a page whose body is stored in segments, its segments read in order (a marker split across two is found). + */ +async function holdingSlugs(tx: BrainEngine, sourceId: string, slugs: string[], id: string): Promise> { + const out = new Map(); + if (!slugs.length) return out; + const rows = await tx.executeRaw<{ id: number | string; slug: string; segmented: boolean; holds: boolean }>( + `SELECT p.id, p.slug, p.body_storage = 'segmented' AS segmented, ${pageHoldsSql('p', '$3')} AS holds FROM pages p WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) FOR SHARE OF p`, + [sourceId, slugs, id]); + const holds = (text: string) => [...text.matchAll(/]+)>/g)].some((m) => m[1] === id); + for (const page of rows) { + if (page.holds) { out.set(page.slug, Number(page.id)); continue; } + if (!page.segmented) continue; + const decoder = new TextDecoder(); + let carry = ''; + for await (const part of readSegmentedBody(tx, Number(page.id), sourceId)) { + const text = carry + decoder.decode(part.bytes, { stream: true }); + if (holds(text)) { out.set(page.slug, Number(page.id)); break; } + carry = text.slice(-96); + } + } + return out; +} + /** * The purge cascade: a page purged for good takes its sealed originals with it. Removes the page's occurrences (those * recorded on the page itself, not the ones a publish recorded on a commit), then every entry those occurrences pointed diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts index 045cfc6f689..5a12feb3d04 100644 --- a/src/mcp/surface.ts +++ b/src/mcp/surface.ts @@ -283,6 +283,7 @@ export const STARTER_CALLABLE_PARAMS: Readonly