Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: Wakeshift PR 1 core (client, config, events, drain, ops, migration)

garrytan34c4d7be8206
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index bfd01a71ee..d041afa9a1 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2874 ratchet +5 #7191: findPages/countPagesBy signatures and type imports (SQL in engine-sql/page-lookup.ts); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +9 GBRA-177: TakesListOpts.oldestFirst/sinceOnOrBefore/ungradedFirst for the grade_takes window (interface fields cannot move; SQL in engine-sql/takes.ts): 2832 + 9; +6 GBRA-156: TransactionOptions.pipelineFirst (the declaration goes out with BEGIN behind a transaction-mode pooler; predicate in persistence/protocol.ts); interface fields cannot move; +1 GBRA-161 PR 2: deprecation notes on insertFacts({ deleteForPageFirst }), deleteFactsForPage and expireFact (interface docs cannot move); +7 GBRA-156: TransactionOptions.pipelineEarly (search read bodies go out behind BEGIN; predicate in postgres-engine/search-settings.ts); interface fields cannot move; +2 GBRA-156: TransactionOptions.readOnly (search read transactions open BEGIN READ ONLY; 2858 measured); grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); re-summed at the Wave B PR 4 merge with v0.60.452.0 (2866 measured); re-summed at the memory train #8481 merge with v0.60.576.0 (2874 measured)
src/core/import-file.ts 2088 ratchet +2 #7880: importFromContent's holdNoncanonicalPrivate option (interface field; the hold is screenImportContent's); +2 #7848: importFromFile holds a non-canonical private request (predicate and hold in persistence/visibility-request.ts); +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection); merge v0.60.332.0: #7172 and master growth compose at 2075; +7 GBRA-283 B3a (#8523): the three file import entry points re-enter an embedded engine's scope (needsEngineScope in core/engine-scope.ts), importFromContent runs its screened body in that scope as a closure, and the deferred embed resumes the import's scope; re-summed at the memory train #8481 merge with v0.60.576.0 (2088 measured)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 248 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured)
+src/core/operations.ts 249 ratchet +1 #7168: graphRankOperations import (ops/graph-rank.ts; spread shares the orphans line); peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import; +1 GBRA-156: whois import (ops/whois.ts; spread shares the chunks line); +1 GST-359 D: qmMemoryOperations import (ops/qm-memory.ts; spread shares the memory line); re-summed at the train R merge with v0.60.574.0: 246 + 1; re-summed at the memory train #8481 merge with v0.60.576.0 (248 measured); +1 Wakeshift PR 1: wakeshiftOperations import (ops/wakeshift.ts; its spread shares the jobs line)
src/core/pglite-engine.ts 3103 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.ts); +4 GBRA-283 B1 (#8455): initSchema seeds an engine opened from settings with settings.embedding and refuses a mismatch, and its open skips the snapshot fast path (logic in embedded-engine.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +2 #7159: the frontmatter where clause in searchKeyword and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); +2 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity with an orFallback rank parameter like Postgres (logic in search/keyword-or-rarity.ts; engine methods cannot move); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3097 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move)
src/core/postgres-engine.ts 3178 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.ts); +6 GBRA-283 B1 (#8455): an engine opened from settings routes its direct URL and statement-description cache from its settings, and initSchema seeds settings.embedding and refuses a mismatch (logic in embedded-engine.ts; engine methods cannot move); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +3 #7159: the frontmatter where clause in the two keyword typesClause sites and its import (SQL in search/frontmatter-where.ts; engine methods cannot move); GBRA-156 retrieval wave (#7201) composed with #7194 at the merge: re-summed (3114 measured); +2 warm CLI socket (#7218): connectedDatabaseUrl getter (the URL the engine connected with, bound into the socket identity), composed over the GBRA-156 retrieval wave (3116 measured); +1 GBRA-133 PR 2b: transactionOn hands the outermost transaction its commit checks (page-state/transactions.ts withCommitChecks), composed with the warm CLI socket at the merge (3117 measured); +18 GBRA-156: the private readTransaction helper behind withScopedReadTransaction and jitOffRead answers a top-level read before its COMMIT settles (engine methods cannot move; 3135 measured); +1 GBRA-156: transactionOn and runUnsafe hold a per-search connection slot (import of search/connection-budget.ts; 3136 measured); +2 GBRA-156: transactionOn passes TransactionOptions.pipelineFirst to the pool begin as { first } (driver gate in vendor/postgres index.js begin); an engine method cannot move; composed with the warm CLI socket and GBRA-133 PR 2b at the master v0.60.344.0 merge (3119 measured); GBRA-151 #7183/#7187/#7188 re-summed at the v0.60.402.0 merge (3135 measured); +2 #7183 (GBRA-151) at the v0.60.412.0 merge: read-write-transactions import and transactionOn wraps its connection in readWriteTransactions (logic in postgres-engine/read-write-transactions.ts; engine methods cannot move): 3135 + 2; +7 GBRA-156: transactionOn opens readOnly transactions as BEGIN READ ONLY and a top-level read inherits its request signal, runUnsafe refuses an aborted request (logic in request-signal.ts; engine methods cannot move): 3137 + 7; +3 GBRA-156 keyword OR rarity: the import and the searchKeyword OR retry through rankOrFallbackByRarity (logic in search/keyword-or-rarity.ts; engine methods cannot move); +2 wave-b PR 4 merged with #7218 (both sides added imports); re-summed at the Wave B PR 4 merge with v0.60.452.0 (3155 measured); +2 GBRA-283 Wave A (#8460): the ENGINE_ROOT import and field (engine identity for per-engine caches; class fields cannot move); +7 GBRA-283 B1 review: the instance pool passes settings connection fields explicitly, initSchema reads the embedding identity again under the schema lock, and reconnect ends the superseded manager (engine methods cannot move); re-summed at the train R merge with v0.60.574.0: 3170 + 4; +4 #6318: withScopedReadTransaction runs a bounded preparation's read under its deadline (read-deadline.ts; reserved-connection envelope runDeadlineRead in postgres-engine/bounded-statement.ts) and adds statement_timeout to the transaction settings (engine methods cannot move): re-summed at the 0.60.583.0 merge: 3174 + 4
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
diff --git a/src/commands/jobs/work.ts b/src/commands/jobs/work.ts
index ddd48db5c5..d53549ace5 100644
--- a/src/commands/jobs/work.ts
+++ b/src/commands/jobs/work.ts
@@ -12,6 +12,7 @@ import type { BrainEngine } from '../../core/engine.ts';
import { loadConfig } from '../../core/config.ts';
import { startPersistenceConsumer } from '../../core/persistence/service.ts';
import { describeLanePolicy, resolveLanePolicy } from '../../core/minions/lanes.ts';
+import { drainWakesUntilIdle } from '../../core/wakeshift/drain.ts';
export async function maybeRunWorkerStartupRecovery(
queue: MinionQueue,
@@ -55,6 +56,8 @@ export async function runJobsWork({ args, engine, queue }: JobsCommandContext):
const queueName = parseFlag(args, '--queue') ?? 'default';
if (engine.kind === 'pglite') {
await drainPgliteQueue(engine, queue, queueName, registerBuiltinHandlers);
+ // Wakeshift (plan D8): deliver the wakes this drain's jobs owe before the process exits; a no-op while off.
+ await drainWakesUntilIdle(engine).catch(e => console.error(`[gbrain jobs] wake drain failed: ${e instanceof Error ? e.message : String(e)}`));
return;
}
const concurrency = resolveWorkerConcurrency(args);
diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.ts
index 5d4e5915fa..5451d359d0 100644
--- a/src/commands/serve-http-mcp.ts
+++ b/src/commands/serve-http-mcp.ts
@@ -77,6 +77,8 @@ interface McpRequestState {
actorHeader: string | undefined;
/** GST-359 D: the x-qm-audience header (QM's channel audience, wave 2); any request carrying it is refused before any work. */
audienceHeader: string | undefined;
+ /** Wakeshift: the request's User-Agent, which tells it some agent programs apart. Shape only. */
+ userAgent: string | undefined;
}
export function mountMcp(app: Express, ctx: ServeHttpContext): void {
@@ -188,7 +190,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {
surface === 'full' && authInfo.allowedOperations == null ? undefined : new Set(mcpOperations.map(o => o.name));
const thinClient = isGbrainThinClient(req.get(GBRAIN_CLIENT_HEADER));
const state: McpRequestState = { authInfo, agentName, startTime, mcpOperations, surface, surfaceCeiling, surfaceAllowedOps, resultRows, thinClient,
- onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER) };
+ onBehalfOfHeader: req.get(ON_BEHALF_OF_HEADER), actorHeader: req.get(ACTOR_HEADER), audienceHeader: req.get(QM_AUDIENCE_HEADER), userAgent: req.get('user-agent') };
const server = createMcpRequestServer(ctx, state, writeback);
await serveMcpRequest(server, req, res);
}
@@ -371,10 +373,12 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
// 'tools/list'. Pre-existing string-shaped rows are normalized by
// migration v41 in src/core/migrate.ts.
const safeParamsSummary = summarizeMcpParams(name, params);
+ // Wakeshift's session_key is a conversation credential: never logged, even under --log-full-params.
+ const fullParams = params && typeof params === 'object' && 'session_key' in params ? { ...params, session_key: '[redacted]' } : params;
const logParamsObj: unknown = logFullParams
- ? (params || null)
+ ? (fullParams || null)
: (safeParamsSummary || null);
- const broadcastParams = logFullParams ? (params || {}) : safeParamsSummary;
+ const broadcastParams = logFullParams ? (fullParams || {}) : safeParamsSummary;
// v0.31 (D12 / eE1): refactor the inlined op.handler call to go through
// src/mcp/dispatch.ts so HTTP MCP shares the same dispatch path as
@@ -438,6 +442,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques
...(sessionId ? { sessionId } : {}),
...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}),
onBehalfOf: { header: state.onBehalfOfHeader, requestMeta: (request.params as { _meta?: unknown })._meta },
+ mcpCaller: { client: authInfo.clientName, userAgent: state.userAgent, meta: (request.params as { _meta?: Record<string, unknown> })._meta },
actor: { header: state.actorHeader, audience: state.audienceHeader },
takesHoldersAllowList: tokenAllowList,
sourceId: tokenSourceId,
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 1f46f9e082..5a6f98ca23 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -251,6 +251,8 @@ async function serveBrain(
// verifyAccessToken with legacy access_tokens fallback (so v0.22.7 callers
// that used `gbrain auth create` keep working unchanged).
const isHttp = args.includes('--http');
+ // Wakeshift (docs/guides/wakeshift.md): the 5 s wake drainer for stdio and HTTP alike; a no-op tick while reporting back is off.
+ (await import('../core/wakeshift/drain.ts')).startWakeDrain(engine);
// MEMORY_VERBS v1: tool-surface mode. stdio: GBRAIN_SURFACE > --surface >
// config `mcp_surface` > 'full'; --http ignores GBRAIN_SURFACE (an HTTP
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index dbf85164b5..c734e1195f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -844,6 +844,12 @@ export const CODES = {
verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },
visibility_noncanonical: { class: 'caller', summary: "A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable.", why: "Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture, ingest_capture, brainstorm --save and sources reconcile refuse the same request as visibility_not_applied.", docs: 'docs/guides/write-refusals.md#visibility_noncanonical', suggestion: 'Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again.' },
visibility_not_applied: { class: 'caller', reasons: ['noncanonical_value', 'not_kept'], summary: "A page write asked for visibility: private, but the page would have stayed world-readable, so nothing was written.", why: "A write that reports success while the page stays world-readable leaves the caller believing it is hidden. Page privacy reads only the exact lowercase key and value visibility: private (#7841). When the frontmatter is unreadable or ambiguous, the write is refused invalid_frontmatter instead.", docs: 'docs/guides/write-refusals.md#visibility_not_applied', suggestion: 'Read the page and its revision, write visibility: private on its own frontmatter line (lowercase key and value), then submit again with a new request_id.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Read-only: shows the page as it is now, with its revision.', requires_exclusive: false } },
+ wakeshift_key_invalid: { class: 'caller', actor: 'user', reasons: ['format', 'checksum', 'legacy', 'file_too_open', 'missing'], summary: "The Wakeshift key is missing, mistyped, in an older format, or in a key file other users can read, so reporting back was not turned on.", why: "A Wakeshift key is an Ed25519 private key (wst_ followed by 50 base58 characters whose last four bytes are a checksum). gbrain reads it from WAKESHIFT_API_KEY or ~/.gbrain/wakeshift.key, which must be readable by its owner only; it never stores the key in the database or prints it.", docs: 'docs/guides/wakeshift.md#the-key', suggestion: 'Ask the user to create a key in their Wakeshift console and put it in ~/.gbrain/wakeshift.key (chmod 600) or WAKESHIFT_API_KEY in ~/.gbrain/.env, then run gbrain wakeshift enable again.' },
+ wakeshift_needs_conversation: { class: 'caller', summary: "watch_job wakes an MCP conversation, and a local CLI run has none to wake.", docs: 'docs/guides/wakeshift.md', suggestion: 'Run gbrain jobs wait <id> to block until the job finishes.' },
+ wakeshift_not_enabled: { class: 'caller', summary: "Reporting back through Wakeshift is off on this brain (the owner has not run gbrain wakeshift enable, or the key is missing).", why: "Wakeshift is off by default; only the brain owner turns it on, on the brain host, because it sends wake metadata to a third-party service.", docs: 'docs/guides/wakeshift.md', suggestion: 'Use wait_job (or gbrain jobs wait <id>) instead, or ask the brain owner to run gbrain wakeshift enable.' },
+ wakeshift_refused: { class: 'caller', summary: "Wakeshift refused the request; the reason carries its error code. Nothing was watched or sent.", why: "Wakeshift checks each request (the signed key, the event and its arguments, the conversation's session key). A refusal other than a rate limit does not go away on retry.", docs: 'docs/guides/wakeshift.md#troubleshooting', suggestion: 'Call wait_job to wait without Wakeshift; the brain owner can run gbrain wakeshift test to check the key and the app.' },
+ wakeshift_shared_brain: { class: 'host_only', actor: 'user', summary: "gbrain wakeshift enable refused: this brain has live access members, and this release reports back only on brains that serve their owner alone.", why: "Every member of the brain owner's Wakeshift organization can read the wakes it sends, and Wakeshift's terms make the operator pass its Connector Terms to each member. Shared brains get a terms step in a later release; until then reporting back stays off there.", docs: 'docs/guides/wakeshift.md#who-it-is-for', suggestion: 'Leave reporting back off on this brain; agents can use wait_job or gbrain jobs wait <id>.' },
+ wakeshift_unavailable: { class: 'unavailable', retryable: true, summary: "Wakeshift could not be reached or answered with a server error or rate limit; nothing was watched.", why: "gbrain makes one request with a 10 s timeout and never retries inside a tool call, so a slow or down Wakeshift never holds the call.", docs: 'docs/guides/wakeshift.md#troubleshooting', suggestion: 'Retry in a minute, or call wait_job to wait without Wakeshift.' },
withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },
withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },
withdrawal_mirror_pending: { class: 'retryable', summary: "A page's Git or embedding work is waiting because its withdrawal mirror is queued or running again (for example after retry-effects).", why: "Git and embedding work behind a withdrawal mirror touches only the pages the mirror recorded rewriting (GBRA-130 A-12); while the mirror runs, the effect worker releases the work and picks it up once the mirror settles.", suggestion: 'Nothing needs resubmitting; read the effects with gbrain sources writer status <source> --json and wait for the mirror to finish.' },
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index a1d6d101d6..a0ee43215b 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -95,6 +95,7 @@ import { jobRefusal, refusedJobResult } from './refusal.ts';
import { readFileSync } from 'fs';
import { parseRssFromProcStatus } from './proc-rss.ts';
import { withEngineScope } from '../engine-scope.ts';
+import { startWakeDrain } from '../wakeshift/drain.ts';
export { parseRssFromProcStatus };
@@ -201,6 +202,7 @@ export class MinionWorker extends EventEmitter {
private pausedByMarkerAnnounced = false;
/** The idle poll wait a sync-queue wake ends early (minions/idle-wait.ts). */
readonly idleWaiter = new IdleWaiter();
+ private wakeDrain: { stop(): void } | null = null;
private inFlight = new Map<number, InFlightJob>();
private executions = new Map<string, OwnedExecution>();
private pendingClaim: { lockToken: string; promise: Promise<MinionJob | null> } | null = null;
@@ -527,6 +529,7 @@ export class MinionWorker extends EventEmitter {
// run; stop() disables it so embedding hosts / test suites that cycle
// start()/stop() don't leak a ~50Hz native sampling timer per instance.
try { this.eldHistogram?.enable(); } catch { /* fail-open */ }
+ this.wakeDrain ??= startWakeDrain(this.engine); // Wakeshift: the 5 s wake drainer (wakeshift/drain.ts), a no-op tick while off
// Graceful shutdown. Fires shutdownAbort so handlers subscribed to
// `ctx.shutdownSignal` (currently: shell handler) can run their own cleanup
@@ -1045,6 +1048,7 @@ export class MinionWorker extends EventEmitter {
stop(): void {
this.running = false;
this.idleWaiter.wake('stop');
+ this.wakeDrain?.stop(); this.wakeDrain = null;
try { this.eldHistogram?.disable(); } catch { /* fail-open */ }
}
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index d5d3e68d93..1696485200 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -82,7 +82,7 @@ const OP_AREAS: Record<string, string> = {
file_list: 'files', file_upload: 'files', file_url: 'files', file_register: 'files', file_verify: 'files',
// jobs (Minions + agent lane)
submit_job: 'jobs', get_job: 'jobs', wait_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',
- retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs',
+ retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs', watch_job: 'jobs', list_watches: 'jobs', unwatch: 'jobs',
resume_job: 'jobs', replay_job: 'jobs', send_job_message: 'jobs',
submit_agent: 'jobs', get_agent_job: 'jobs',
// takes + think
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 2d532d7a6d..a542507ca0 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -131,6 +131,7 @@ import { pageBatchOperations } from './ops/page-batch.ts';
import { pageUploadOperations } from './ops/page-upload.ts';
import { feedbackOperations } from './ops/feedback.ts';
import { trustOperations } from './ops/trust.ts';
+import { wakeshiftOperations } from './ops/wakeshift.ts';
import { findPagesOperations } from './ops/find-pages.ts';
// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`
@@ -184,8 +185,8 @@ export const operations: Operation[] = [
...filesOperations,
// Jobs (Minions: submit_job, get_job, list_jobs, cancel_job, retry_job,
// get_job_progress, pause_job, resume_job, replay_job, send_job_message)
- // + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts
- ...jobsOperations,
+ // + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts; Wakeshift watches (watch_job, list_watches, unwatch) — ops/wakeshift.ts
+ ...jobsOperations, ...wakeshiftOperations,
// Orphans (find_orphans) — ops/orphans.ts; rank_entities — ops/graph-rank.ts
...orphansOperations, ...graphRankOperations,
// v0.36.1.0 (T7) — Hindsight calibration wave (get_calibration_profile) —
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index f01004f4da..a98264bf57 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -531,6 +531,14 @@ export interface OperationContext {
* on callers that have no notice channel; producers call it optionally.
*/
emitNotice?: (n: Notice) => void;
+ /**
+ * Wakeshift (docs/guides/wakeshift.md): the MCP caller as the transport saw it, which Wakeshift uses to tell agent
+ * programs apart: `clientInfo.name` (stdio) or the OAuth `client_name` (HTTP), the HTTP User-Agent and the request's
+ * `_meta`. Set by the MCP transports only, never from tool arguments; shape only, never authority.
+ */
+ mcpCaller?: { client?: string; userAgent?: string; meta?: Record<string, unknown> };
+ /** Wakeshift: a handler's addition, rendered as the result's last text block plus `_meta` keys. A credential: never log it. */
+ emitToolTail?: (tail: { text?: string; meta?: Record<string, unknown> }) => void;
/**
* WP4 (D2): the SERVER surface ceiling for this transport (force-clamped),
* threaded by the MCP dispatch layer. Consumed by `request_tools`: the
@@ -838,7 +846,7 @@ export interface Operation {
* fail-closed call-time backstop; stdio (local pipe) bypasses publish
* gates entirely. Resolution lives in src/mcp/publish-gates.ts.
*/
- publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor' | 'mcp.publish_memory_settings';
+ publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor' | 'mcp.publish_memory_settings' | 'mcp.publish_wakeshift';
/**
* MEMORY_VERBS v1: marks the seven frozen protocol verbs (recall, remember,
* entity, synthesize, forget, context_pack, delta). `gbrain serve --surface
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
index a2044054fd..02e9b63e48 100644
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@ -82,7 +82,7 @@ import {
* `data->>'__owner_client_id'`. Missing identity → permission_denied
* (fail closed, mirroring get_agent_job).
*/
-function agentOwnerFence(ctx: OperationContext, opName: string): string | null {
+export function agentOwnerFence(ctx: OperationContext, opName: string): string | null {
if (ctx.remote === false) return null;
const scopes = ctx.auth?.scopes;
if (scopes && hasScope(scopes, 'admin')) return null;
@@ -108,7 +108,7 @@ function getJobFix(id: unknown, why: string): Action {
}
/** A1 frozen pair: a missing job keeps `error: invalid_params` and reports `code: not_found`. */
-function jobNotFound(message: string): OperationError {
+export function jobNotFound(message: string): OperationError {
return opError('not_found', message,
'No job with that id is visible to this caller (jobs owned by another client read as missing). List jobs to find the right id.',
{ legacy_error: 'invalid_params', fix: listJobsFix('Lists the jobs this caller can see, with their ids and status.') });
@@ -126,7 +126,7 @@ function jobStateError(id: unknown, message: string, need: string): OperationErr
* design (anti-enumeration): both throw the SAME error the unfenced path
* throws for a missing id.
*/
-async function assertJobOwned(ctx: OperationContext, id: number, owner: string): Promise<void> {
+export async function assertJobOwned(ctx: OperationContext, id: number, owner: string): Promise<void> {
const rows = await ctx.engine.executeRaw<{ id: number }>(
`SELECT id FROM minion_jobs WHERE id = $1 AND data->>'__owner_client_id' = $2 AND ${jobActorSql(3)}`,
[id, owner, ...callerJobActor()],
diff --git a/src/core/ops/wakeshift.ts b/src/core/ops/wakeshift.ts
new file mode 100644
index 0000000000..b515c23242
--- /dev/null
+++ b/src/core/ops/wakeshift.ts
@@ -0,0 +1,224 @@
+/**
+ * Report-back watches over Wakeshift (plan D6, D7): `watch_job`,
+ * `list_watches`, `unwatch`. Listed only while the owner has run
+ * `gbrain wakeshift enable` and a usable key is on the host (publish gate
+ * `mcp.publish_wakeshift`, file plane plus key presence; no DB plane, so no
+ * remote caller can flip it). `watch_job` runs the get_job owner fence first,
+ * so a foreign id reads exactly like a missing one and nothing is sent. A
+ * watch belongs to the principal that made it; list and unwatch touch only
+ * that principal's rows. What leaves the machine: docs/guides/wakeshift.md.
+ * Never import from '../operations.ts' here (cycle).
+ */
+import { opError, type Operation, type OperationContext, type OperationError } from './contract.ts';
+import { readFix } from './op-fix.ts';
+import { agentOwnerFence, assertJobOwned, jobNotFound } from './jobs.ts';
+import { memberIdentityFor } from '../access/caller.ts';
+import { WakeshiftError, type WakeshiftCall } from '../wakeshift/client.ts';
+import { wakeshiftBrainKey, wakeshiftRuntime, wakeshiftSecret, wakeshiftUserId } from '../wakeshift/config.ts';
+import { JOB_FINISHED } from '../wakeshift/events.ts';
+import { drainWakes, endAtWakeshift } from '../wakeshift/drain.ts';
+
+const WATCH_TTL = '7d';
+const TERMINAL = new Set(['completed', 'failed', 'dead', 'cancelled']);
+const REDACTION = { exempt: 'watch bookkeeping: job ids, states and times, never retrieved brain text' } as const;
+
+/** The three arguments Wakeshift asks a subscribing tool to take (its HTTP API, "The caller"). */
+const CALLER_PARAMS = {
+ session_key: { type: 'string', description: "This conversation's session_key, from an earlier result (a secret token, or a handle such as claude-code#2). Keep it to this conversation; don't share or log it." },
+ harness: { type: 'string', description: "The program you're running in: codex, claude-code, cursor (local CLI or IDE), cursor-cloud (Cursor cloud agent), grok-bot, copilot-cli, opencode, antigravity, openclaw (even when it runs your turns in Codex), hermes, chatgpt, or your program's name if it isn't listed" },
+ conversation_id: { type: 'string', description: 'Your own ID for this conversation, if your program gives you one. Cursor and Grok Bot: the output of `printenv CURSOR_CONVERSATION_ID`. Codex and Antigravity send it automatically; others leave it empty' },
+} as const;
+
+function waitFix(id: number) {
+ return readFix('Waits for the job without Wakeshift (at most 55 s a call; call again while terminal is false).',
+ { argv: ['gbrain', 'jobs', 'wait', String(id)], mcp: { tool: 'wait_job', arguments: { id } } });
+}
+
+function notEnabled(): OperationError {
+ return opError('wakeshift_not_enabled', 'Reporting back through Wakeshift is off on this brain.',
+ 'Use wait_job instead, or ask the brain owner to run gbrain wakeshift enable on the brain host.');
+}
+
+export interface WatchPrincipal { kind: 'oauth_client' | 'legacy_token' | 'local_stdio'; id: string; member: string | null }
+
+/** Who is watching: the verified credential (bound member when it has one), else the local stdio pipe. */
+export async function watchPrincipal(ctx: OperationContext): Promise<WatchPrincipal | null> {
+ const base = ctx.auth
+ ? (ctx.auth.principal ?? (ctx.auth.clientId ? { kind: 'oauth_client' as const, id: ctx.auth.clientId } : null))
+ : ctx.transport === 'stdio' ? { kind: 'local_stdio' as const, id: 'local' } : null;
+ if (!base) return null;
+ const identity = await memberIdentityFor(ctx.engine, { ...(ctx.auth ? { member: ctx.auth.member } : {}), principal: base });
+ return { ...base, member: identity.find(i => i.startsWith('member:'))?.slice('member:'.length) ?? null };
+}
+
+const principalKey = (p: WatchPrincipal) => (p.member ? `member:${p.member}` : `${p.kind}:${p.id}`);
+
+function optString(v: unknown, max: number): string | undefined {
+ return typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined;
+}
+
+function wakeshiftFailure(e: WakeshiftError, id: number): OperationError {
+ const fix = waitFix(id);
+ if (e.code === 'other_client') {
+ return opError('wakeshift_refused', 'Wakeshift refused the session_key: it belongs to a conversation in another program.',
+ 'Call watch_job again without session_key.', { reason: e.code, fix });
+ }
+ if (e.status === 0 || e.status === 429 || e.status >= 500) {
+ return opError('wakeshift_unavailable', `Wakeshift could not take the watch (${e.code}); nothing was watched.`,
+ `Retry watch_job in a minute, or call wait_job ${id} to wait without it.`, { reason: e.code, fix });
+ }
+ return opError('wakeshift_refused', `Wakeshift refused the watch (${e.code}): ${e.message}`,
+ `Call wait_job ${id} to wait without Wakeshift; the brain owner can check the setup with gbrain wakeshift test.`, { reason: e.code, fix });
+}
+
+interface WatchRow { id: number; event: string; target: string; state: string; attempts: number; last_error: string | null; created_at: Date | string; expires_at: Date | string }
+
+function publicWatch(r: WatchRow) {
+ return { watch: Number(r.id), event: r.event, job: Number(r.target), state: r.state, attempts: r.attempts, last_error: r.last_error, created_at: r.created_at, expires_at: r.expires_at };
+}
+
+const watch_job: Operation = {
+ name: 'watch_job',
+ mutating: true,
+ idempotent: true,
+ writeInference: 'non_content',
+ outputRedaction: REDACTION,
+ description: 'This tool notifies you: it has gbrain wake this conversation through Wakeshift when job id finishes '
+ + '(completed, failed, dead or cancelled), so you can stop polling. Call it right after submitting a long job, then end your turn '
+ + 'or keep working. The wake names the job and says to call get_job for the result; it carries no page text. '
+ + 'Agent-scoped tokens watch only jobs they own. If no wake arrives, call wait_job.',
+ params: {
+ id: { type: 'number', required: true, description: 'Job ID (from submit_job, submit_agent or list_jobs).' },
+ ...CALLER_PARAMS,
+ },
+ scope: 'admin',
+ agentCallable: true,
+ publishGateKey: 'mcp.publish_wakeshift',
+ cliHints: { hidden: true },
+ handler: async (ctx, p) => {
+ const id = p.id as number;
+ if (!Number.isSafeInteger(id) || id <= 0) {
+ throw opError('invalid_params', `watch_job: id must be a positive job id (got ${JSON.stringify(p.id)}).`, 'Pass the id submit_job or list_jobs returned.');
+ }
+ if (ctx.remote === false) {
+ throw opError('wakeshift_needs_conversation', 'watch_job wakes an MCP conversation; a CLI run has none to wake.',
+ `Run gbrain jobs wait ${id} to block until the job finishes.`, { fix: waitFix(id) });
+ }
+ const runtime = wakeshiftRuntime();
+ if (!runtime) throw notEnabled();
+ const owner = agentOwnerFence(ctx, 'watch_job');
+ if (owner !== null) await assertJobOwned(ctx, id, owner);
+ const [job] = await ctx.engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id = $1', [id]);
+ if (!job) throw jobNotFound(`Job not found: ${id}`);
+ const principal = await watchPrincipal(ctx);
+ if (!principal) throw notEnabled();
+ if (ctx.dryRun) return { dry_run: true, action: 'watch_job', job: id };
+
+ const user = wakeshiftUserId(wakeshiftSecret(), wakeshiftBrainKey(ctx.config), principalKey(principal));
+ const caller = ctx.mcpCaller;
+ const call: WakeshiftCall = {
+ user, tool: 'watch_job',
+ ...(optString(caller?.client, 200) ? { client: optString(caller?.client, 200) } : {}),
+ ...(caller?.meta && typeof caller.meta === 'object' ? { meta: caller.meta } : {}),
+ ...(optString(caller?.userAgent, 400) ? { user_agent: optString(caller?.userAgent, 400) } : {}),
+ ...(optString(p.session_key, 100) ? { session: optString(p.session_key, 100) } : {}),
+ ...(optString(p.harness, 100) ? { harness: optString(p.harness, 100) } : {}),
+ ...(optString(p.conversation_id, 200) ? { conversation: optString(p.conversation_id, 200) } : {}),
+ };
+ const args = { job: id };
+ let sub;
+ try {
+ sub = await runtime.api.subscribe({ call, name: JOB_FINISHED, arguments: args, ttl: WATCH_TTL, once: true, reason: `Watching gbrain job ${id}` });
+ } catch (e) {
+ if (e instanceof WakeshiftError) throw wakeshiftFailure(e, id);
+ throw e;
+ }
+ let rowId: number;
+ try {
+ const expires = sub.event_subscription.expires_at && !Number.isNaN(Date.parse(sub.event_subscription.expires_at))
+ ? sub.event_subscription.expires_at : new Date(Date.now() + 7 * 86_400_000).toISOString();
+ const [row] = await ctx.engine.executeRaw<{ id: number }>(
+ `INSERT INTO wake_subscriptions (event, target, principal_kind, principal_id, member_id, wake_user, ws_subscription_id, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz)
+ ON CONFLICT (wake_user, ws_subscription_id) WHERE state = 'open'
+ DO UPDATE SET expires_at = EXCLUDED.expires_at, updated_at = now()
+ RETURNING id`,
+ [JOB_FINISHED, String(id), principal.kind, principal.id, principal.member, user, String(sub.event_subscription.id), expires]);
+ rowId = Number(row!.id);
+ } catch (e) {
+ if (sub.event_subscription.created !== false) {
+ await runtime.api.unsubscribe({ call, name: JOB_FINISHED, arguments: args, reason: 'rolled_back' }).catch(() => {});
+ }
+ throw e;
+ }
+ const finished = TERMINAL.has(job.status);
+ if (finished) await drainWakes(ctx.engine, { ids: [rowId], api: runtime.api }).catch(() => {});
+ if (sub.addition && (sub.addition.text || sub.addition.meta)) ctx.emitToolTail?.({ text: sub.addition.text, meta: sub.addition.meta });
+ const recognized = sub.agent ? sub.agent.harness !== null || sub.agent.claimed !== null : true;
+ return {
+ watching: true, watch: rowId, job: id, event: JOB_FINISHED, status: job.status, already_finished: finished,
+ expires_in: WATCH_TTL,
+ ...(recognized ? {} : { wakeable: false, note: 'Wakeshift did not recognize this agent program, so it may not be able to wake you: call watch_job again with harness set to your program.' }),
+ fallback: `If no wake arrives, call wait_job ${id} (or run gbrain jobs wait ${id}).`,
+ };
+ },
+};
+
+async function ownRows(ctx: OperationContext, extra: string, params: unknown[]): Promise<WatchRow[]> {
+ const principal = await watchPrincipal(ctx);
+ if (!principal) return [];
+ return ctx.engine.executeRaw<WatchRow>(
+ `SELECT id, event, target, state, attempts, last_error, created_at, expires_at, wake_user, ws_subscription_id FROM wake_subscriptions
+ WHERE principal_kind = $1 AND principal_id = $2 ${extra} ORDER BY created_at DESC, id DESC LIMIT 50`,
+ [principal.kind, principal.id, ...params]);
+}
+
+const list_watches: Operation = {
+ name: 'list_watches',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: REDACTION,
+ description: 'List the jobs this connection is watching through Wakeshift (open watches, plus ones that ended in the last day) with their state: open, delivered, dead or ended.',
+ params: {},
+ scope: 'admin',
+ agentCallable: true,
+ publishGateKey: 'mcp.publish_wakeshift',
+ cliHints: { hidden: true },
+ handler: async (ctx) => {
+ if (!wakeshiftRuntime()) throw notEnabled();
+ const rows = await ownRows(ctx, "AND (state = 'open' OR updated_at > now() - interval '1 day')", []);
+ return { watches: rows.map(publicWatch) };
+ },
+};
+
+const unwatch: Operation = {
+ name: 'unwatch',
+ mutating: true,
+ idempotent: true,
+ writeInference: 'non_content',
+ outputRedaction: REDACTION,
+ description: 'Stop watching a job: ends this connection\'s open Wakeshift watches on it, so no wake comes for it. Returns how many ended (0 when none was open).',
+ params: { job: { type: 'number', required: true, description: 'Job ID you passed to watch_job.' } },
+ scope: 'admin',
+ agentCallable: true,
+ publishGateKey: 'mcp.publish_wakeshift',
+ cliHints: { hidden: true },
+ handler: async (ctx, p) => {
+ const runtime = wakeshiftRuntime();
+ if (!runtime) throw notEnabled();
+ const job = p.job as number;
+ if (!Number.isSafeInteger(job) || job <= 0) throw opError('invalid_params', 'unwatch: job must be a positive job id.', 'Pass the job id you watched (list_watches shows them).');
+ if (ctx.dryRun) return { dry_run: true, action: 'unwatch', job };
+ const rows = await ownRows(ctx, "AND state = 'open' AND event = $3 AND target = $4", [JOB_FINISHED, String(job)]) as Array<WatchRow & { wake_user: string; ws_subscription_id: string }>;
+ let ended = 0;
+ for (const row of rows) {
+ const done = await ctx.engine.executeRaw(`UPDATE wake_subscriptions SET state = 'ended', last_error = 'unwatched', lease_until = NULL, updated_at = now() WHERE id = $1 AND state = 'open' RETURNING id`, [row.id]);
+ if (done.length === 0) continue;
+ ended++;
+ await endAtWakeshift(runtime.api, row);
+ }
+ return { job, ended };
+ },
+};
+
+export const wakeshiftOperations: Operation[] = [watch_job, list_watches, unwatch];
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index df044247f9..c794939689 100644
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@ -4,4 +4,4 @@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
-export const LATEST_SCHEMA_VERSION = 289;
+export const LATEST_SCHEMA_VERSION = 290;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 2e6879d2ad..9f437a9af7 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -290,6 +290,7 @@ import { v286 } from './v286-qm-actor-links.ts';
import { v287 } from './v287-multi-page-recovery-record.ts';
import { v288 } from './v288-decide-proposals-claim-pair-index.ts';
import { v289 } from './v289-page-change-reasons.ts';
+import { v290 } from './v290-wake-subscriptions.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -578,4 +579,5 @@ export const MIGRATIONS: Migration[] = [
v287,
v288,
v289,
+ v290,
];
diff --git a/src/core/schema-migrations/v290-wake-subscriptions.ts b/src/core/schema-migrations/v290-wake-subscriptions.ts
new file mode 100644
index 0000000000..c91c0e1d53
--- /dev/null
+++ b/src/core/schema-migrations/v290-wake-subscriptions.ts
@@ -0,0 +1,48 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Wakeshift PR 1 (plan D7): wake_subscriptions holds each watch an agent made
+// through watch_job: the event and target, the subscribing principal (kind,
+// id and its bound member, never sent anywhere), the hashed Wakeshift user
+// and Wakeshift's subscription id, and the drainer's delivery state (marker,
+// attempts, next attempt, a lease so two drainer hosts never emit the same
+// row, the last error code). Operational state, not brain content: a
+// repo-less brain gets it unchanged, and it stays empty unless the owner ran
+// gbrain wakeshift enable. Nothing is rewritten on upgrade. No schema.sql
+// mirror: like v282-v286, it exists only through migrations.
+export const v290: Migration = {
+ version: 290,
+ name: 'wake_subscriptions',
+ idempotent: true,
+ sql: `
+CREATE TABLE IF NOT EXISTS wake_subscriptions (
+ id BIGSERIAL PRIMARY KEY,
+ event TEXT NOT NULL CHECK (event ~ '^gbrain\\.[a-z][a-z0-9._]{0,47}$'),
+ target TEXT NOT NULL CHECK (length(target) BETWEEN 1 AND 128),
+ principal_kind TEXT NOT NULL CHECK (principal_kind IN ('oauth_client', 'legacy_token', 'local_stdio')),
+ principal_id TEXT NOT NULL,
+ member_id TEXT,
+ wake_user TEXT NOT NULL CHECK (wake_user ~ '^[0-9a-f]{32}$'),
+ ws_subscription_id TEXT NOT NULL CHECK (length(ws_subscription_id) BETWEEN 1 AND 200),
+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'delivered', 'dead', 'ended')),
+ delivered_marker TEXT,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ lease_until TIMESTAMPTZ,
+ last_error TEXT,
+ expires_at TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS wake_subscriptions_open_idx ON wake_subscriptions (next_attempt_at) WHERE state = 'open';
+CREATE INDEX IF NOT EXISTS wake_subscriptions_principal_idx ON wake_subscriptions (principal_kind, principal_id, created_at DESC);
+CREATE UNIQUE INDEX IF NOT EXISTS wake_subscriptions_open_unique ON wake_subscriptions (wake_user, ws_subscription_id) WHERE state = 'open';
+DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN
+ ALTER TABLE wake_subscriptions ENABLE ROW LEVEL SECURITY;
+ END IF;
+END $rls$;
+`,
+};
diff --git a/src/core/wakeshift/client.ts b/src/core/wakeshift/client.ts
new file mode 100644
index 0000000000..4e4ff9c0a9
--- /dev/null
+++ b/src/core/wakeshift/client.ts
@@ -0,0 +1,160 @@
+/**
+ * Wakeshift HTTP API client (plan D1): the five endpoints gbrain uses, with no
+ * SDK. A key is an Ed25519 seed (`wst_` + 50 base58 characters whose last 4
+ * bytes are the seed's CRC32); each request carries a fresh compact JWS signed
+ * with it (EdDSA, typ app+jwt, 2 minutes, unique jti), so the key itself never
+ * leaves the brain host. One `fetch` per call with a 10 s timeout and no
+ * internal retry: the drainer (drain.ts) owns the retry schedule.
+ * Docs: docs/guides/wakeshift.md; the API: https://wakeshift.ai/docs/http-api.
+ */
+import { createHash, createPrivateKey, createPublicKey, randomBytes, sign, type KeyObject } from 'node:crypto';
+
+export const WAKESHIFT_DEFAULT_URL = 'https://app.wakeshift.ai';
+export const WAKESHIFT_FETCH_TIMEOUT_MS = 10_000;
+const API_PATH = '/api/apps/v1';
+const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+const ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
+
+export interface WakeshiftKey {
+ privateKey: KeyObject;
+ /** First 16 bytes of SHA-256 of the 32-byte public key, base64url: names the key (and its app) without revealing it. */
+ kid: string;
+}
+
+export class WakeshiftKeyError extends Error {
+ constructor(readonly reason: 'format' | 'checksum' | 'legacy', message: string) { super(message); }
+}
+
+/** Non-2xx answers carry Wakeshift's code; status 0 is a network failure or the timeout. */
+export class WakeshiftError extends Error {
+ constructor(readonly status: number, readonly code: string, message: string, readonly retryAfterS?: number) { super(message); }
+}
+
+let crcTable: Uint32Array | null = null;
+export function crc32(buf: Uint8Array): number {
+ crcTable ??= Uint32Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+ });
+ let crc = 0xffffffff;
+ for (const b of buf) crc = crcTable[(crc ^ b) & 0xff]! ^ (crc >>> 8);
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+const b64u = (buf: Uint8Array | string) => Buffer.from(buf).toString('base64url');
+
+/** Parse a current-format key (`wst_` + 50 base58). Older `test_`/`live_` keys are refused: make a new key in the console. */
+export function parseWakeshiftKey(raw: string): WakeshiftKey {
+ const body = raw.trim().replace(/^wst_/, '');
+ if (/^(test|live)_/.test(body)) {
+ throw new WakeshiftKeyError('legacy', 'This is an older Wakeshift key format (test_ or live_), which gbrain does not accept. Create a new key in the Wakeshift console; current keys start with wst_.');
+ }
+ if (body.length !== 50 || body.includes('_')) throw new WakeshiftKeyError('format', 'A Wakeshift key is wst_ followed by 50 base58 characters.');
+ let n = 0n;
+ for (const ch of body) {
+ const d = B58.indexOf(ch);
+ if (d < 0) throw new WakeshiftKeyError('format', 'A Wakeshift key holds only base58 characters after wst_.');
+ n = n * 58n + BigInt(d);
+ }
+ if (n >= 1n << 288n) throw new WakeshiftKeyError('format', 'A Wakeshift key decodes to more than 36 bytes.');
+ const bytes = Buffer.from(n.toString(16).padStart(72, '0'), 'hex');
+ const seed = bytes.subarray(0, 32);
+ if (crc32(seed) !== bytes.readUInt32BE(32)) throw new WakeshiftKeyError('checksum', 'The Wakeshift key fails its checksum: it was mistyped or cut short. Copy it again.');
+ const privateKey = createPrivateKey({ key: Buffer.concat([ED25519_PKCS8_PREFIX, seed]), format: 'der', type: 'pkcs8' });
+ const spki = createPublicKey(privateKey).export({ format: 'der', type: 'spki' });
+ return { privateKey, kid: b64u(createHash('sha256').update(spki.subarray(spki.length - 32)).digest().subarray(0, 16)) };
+}
+
+/** Encode a 32-byte seed as a current-format key (tests and fixtures; gbrain never mints keys for anyone). */
+export function encodeWakeshiftKey(seed: Uint8Array): string {
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(seed));
+ let n = BigInt('0x' + Buffer.concat([Buffer.from(seed), crc]).toString('hex'));
+ let out = '';
+ while (n > 0n) { out = B58[Number(n % 58n)] + out; n /= 58n; }
+ return 'wst_' + out.padStart(50, B58[0]);
+}
+
+/** A fresh assertion: header {alg, typ, kid}, claims iss=sub=kid, aud <url>/api/apps, 120 s life, 16-byte jti. */
+export function wakeshiftAssertion(key: WakeshiftKey, url: string, nowS = Math.floor(Date.now() / 1000)): string {
+ const header = b64u(JSON.stringify({ alg: 'EdDSA', typ: 'app+jwt', kid: key.kid }));
+ const claims = b64u(JSON.stringify({ iss: key.kid, sub: key.kid, aud: `${url}/api/apps`, iat: nowS, exp: nowS + 120, jti: b64u(randomBytes(16)) }));
+ return `${header}.${claims}.${b64u(sign(null, Buffer.from(`${header}.${claims}`), key.privateKey))}`;
+}
+
+/** The console address: https, or http only on a loopback host (a local fake for tests). No trailing slash. */
+export function normalizeWakeshiftUrl(raw: string | undefined): string {
+ const url = new URL(raw?.trim() || WAKESHIFT_DEFAULT_URL);
+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) throw new Error(`wakeshift.url must be https (got ${url.protocol}//${url.host}).`);
+ return url.origin;
+}
+
+/** The caller of a conversation-bound call (Wakeshift "The caller"); every field is optional and passed on unchanged. */
+export interface WakeshiftCall {
+ user: string;
+ tool: string;
+ client?: string;
+ meta?: Record<string, unknown>;
+ user_agent?: string;
+ session?: string;
+ harness?: string;
+ conversation?: string;
+}
+
+export interface WakeshiftAddition { text?: string; meta?: Record<string, unknown> }
+export interface SubscribeResult {
+ event_subscription: { id: string; user: string; event: string; created: boolean; expires_at?: string };
+ session?: string;
+ addition?: WakeshiftAddition;
+ agent?: { harness: string | null; via: string | null; claimed: string | null };
+}
+export interface EmitResult { matched: number; duplicate: boolean; unmatched: unknown[]; ended: unknown[] }
+
+export interface WakeshiftApi {
+ getApp(): Promise<{ id: string; name: string; key: { key_id: string; name: string } }>;
+ mergeManifest(body: Record<string, unknown>): Promise<unknown>;
+ subscribe(body: { call: WakeshiftCall; name: string; arguments: Record<string, unknown>; ttl?: string; once?: boolean; reason?: string }): Promise<SubscribeResult>;
+ unsubscribe(body: { call: WakeshiftCall; name: string; arguments: Record<string, unknown>; reason?: string }): Promise<{ ended: boolean }>;
+ end(body: { user: string; id: string }): Promise<{ ended: boolean }>;
+ emit(body: { name: string; arguments: Record<string, unknown>; payload: Record<string, unknown>; text: string; id: string; to: unknown[] }): Promise<EmitResult>;
+}
+
+export function wakeshiftClient(key: WakeshiftKey, opts: { url?: string; fetch?: typeof fetch; timeoutMs?: number } = {}): WakeshiftApi {
+ const url = normalizeWakeshiftUrl(opts.url);
+ const doFetch = opts.fetch ?? fetch;
+ const request = async <T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T> => {
+ let res: Response;
+ try {
+ res = await doFetch(`${url}${API_PATH}${path}`, {
+ method,
+ headers: { authorization: `Bearer ${wakeshiftAssertion(key, url)}`, ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ signal: AbortSignal.timeout(opts.timeoutMs ?? WAKESHIFT_FETCH_TIMEOUT_MS),
+ });
+ } catch (e) {
+ const timeout = (e as Error)?.name === 'TimeoutError' || (e as Error)?.name === 'AbortError';
+ throw new WakeshiftError(0, timeout ? 'timeout' : 'network', timeout ? 'Wakeshift did not answer within 10 s.' : 'Wakeshift could not be reached.');
+ }
+ const text = await res.text().catch(() => '');
+ let json: unknown = null;
+ try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON body */ }
+ if (!res.ok) {
+ const err = (json as { error?: { code?: unknown; message?: unknown } } | null)?.error;
+ const retryAfter = Number(res.headers.get('retry-after'));
+ throw new WakeshiftError(res.status, typeof err?.code === 'string' ? err.code.slice(0, 64) : `http_${res.status}`,
+ typeof err?.message === 'string' ? err.message.slice(0, 300) : `Wakeshift answered HTTP ${res.status}.`,
+ Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter : undefined);
+ }
+ return json as T;
+ };
+ return {
+ getApp: () => request('GET', '/app'),
+ mergeManifest: body => request('POST', '/manifest/merge', body),
+ subscribe: body => request('POST', '/event-subscriptions', body),
+ unsubscribe: body => request('POST', '/event-subscriptions/unsubscribe', body),
+ end: body => request('POST', '/event-subscriptions/end', body),
+ emit: body => request('POST', '/events/emit', body),
+ };
+}
diff --git a/src/core/wakeshift/config.ts b/src/core/wakeshift/config.ts
new file mode 100644
index 0000000000..3979f0c156
--- /dev/null
+++ b/src/core/wakeshift/config.ts
@@ -0,0 +1,111 @@
+/**
+ * Wakeshift host configuration (plan D4, D6). Everything here is host-side
+ * state no MCP or HTTP operation writes:
+ *
+ * - `wakeshift.enabled` / `wakeshift.url` in the file plane (~/.gbrain/config.json), written only by the
+ * trusted local `gbrain wakeshift enable|disable`, so a remote caller can never turn reporting back on;
+ * - the key: WAKESHIFT_API_KEY (read once, then removed from this process's environment so child processes do
+ * not inherit it), else ~/.gbrain/wakeshift.key, which must be 0600 (a looser file is ignored and doctor says so);
+ * - the HMAC secret ~/.gbrain/wakeshift.secret (0600, random): the Wakeshift `user` is the first 32 hex of
+ * HMAC-SHA256 over (brain, principal), never an email, name or token.
+ *
+ * Off, or no usable key, means inert: no tools listed, no rows, no network.
+ */
+import { createHash, createHmac, randomBytes } from 'node:crypto';
+import { readFileSync, statSync, writeFileSync } from 'node:fs';
+import { gbrainPath, loadConfig, type GBrainConfig } from '../config.ts';
+import { normalizeWakeshiftUrl, parseWakeshiftKey, wakeshiftClient, type WakeshiftApi, type WakeshiftKey } from './client.ts';
+
+export const WAKESHIFT_KEY_ENV = 'WAKESHIFT_API_KEY';
+
+export const wakeshiftKeyFile = () => gbrainPath('wakeshift.key');
+export const wakeshiftSecretFile = () => gbrainPath('wakeshift.secret');
+
+export type KeyRead =
+ | { source: 'env' | 'file'; raw: string }
+ | { source: 'none' }
+ | { source: 'file_too_open'; mode: string };
+
+let envKey: string | null = null;
+
+/** Where the key comes from, without parsing it. The env value moves into this module the first time it is seen. */
+export function readWakeshiftKey(env: NodeJS.ProcessEnv = process.env): KeyRead {
+ const fromEnv = env[WAKESHIFT_KEY_ENV]?.trim();
+ if (fromEnv) {
+ if (env === process.env) { envKey = fromEnv; delete env[WAKESHIFT_KEY_ENV]; } else return { source: 'env', raw: fromEnv };
+ }
+ if (env === process.env && envKey) return { source: 'env', raw: envKey };
+ const file = wakeshiftKeyFile();
+ let mode: number;
+ try { mode = statSync(file).mode; } catch { return { source: 'none' }; }
+ if (mode & 0o077) return { source: 'file_too_open', mode: (mode & 0o777).toString(8).padStart(4, '0') };
+ try {
+ const raw = readFileSync(file, 'utf8').trim();
+ return raw ? { source: 'file', raw } : { source: 'none' };
+ } catch {
+ return { source: 'none' };
+ }
+}
+
+/** Test seam: forget a key taken from the environment. */
+export function resetWakeshiftEnvKeyForTests(): void { envKey = null; }
+
+export interface WakeshiftFileConfig { enabled?: boolean; url?: string }
+
+export function wakeshiftFileConfig(config: GBrainConfig | null | undefined): WakeshiftFileConfig {
+ const raw = (config as { wakeshift?: unknown } | null | undefined)?.wakeshift;
+ return raw && typeof raw === 'object' ? raw as WakeshiftFileConfig : {};
+}
+
+export interface WakeshiftRuntime { key: WakeshiftKey; url: string; api: WakeshiftApi }
+
+/**
+ * The live runtime when reporting back is on and the key parses, else null. Reads the file plane fresh (never a
+ * DB-merged snapshot), so `gbrain wakeshift disable` takes effect on the next call or tools/list.
+ */
+export function wakeshiftRuntime(opts: { config?: GBrainConfig | null; fetch?: typeof fetch } = {}): WakeshiftRuntime | null {
+ const file = wakeshiftFileConfig(opts.config === undefined ? loadConfig() : opts.config);
+ if (file.enabled !== true) return null;
+ const read = readWakeshiftKey();
+ if (read.source !== 'env' && read.source !== 'file') return null;
+ try {
+ const key = parseWakeshiftKey(read.raw);
+ const url = normalizeWakeshiftUrl(file.url);
+ return { key, url, api: wakeshiftClient(key, { url, ...(opts.fetch ? { fetch: opts.fetch } : {}) }) };
+ } catch {
+ return null;
+ }
+}
+
+/** The publish gate `mcp.publish_wakeshift`: the file plane says on and a usable key is present. No DB read. */
+export function wakeshiftPublished(): boolean {
+ try { return wakeshiftRuntime() !== null; } catch { return false; }
+}
+
+/** The local HMAC secret, created (0600, exclusive) on first use. */
+export function wakeshiftSecret(): Buffer {
+ const file = wakeshiftSecretFile();
+ const read = () => Buffer.from(readFileSync(file, 'utf8').trim(), 'hex');
+ try {
+ const s = read();
+ if (s.length >= 32) return s;
+ } catch { /* created below */ }
+ try {
+ writeFileSync(file, randomBytes(32).toString('hex') + '\n', { mode: 0o600, flag: 'wx' });
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ }
+ const s = read();
+ if (s.length < 32) throw new Error(`${file} is not a gbrain Wakeshift secret; remove it and retry.`);
+ return s;
+}
+
+/** Which brain: a hash of its database location (never the location), so two brains in one home map apart. */
+export function wakeshiftBrainKey(config: GBrainConfig | null | undefined): string {
+ return createHash('sha256').update(config?.database_url ?? config?.database_path ?? '').digest('hex').slice(0, 16);
+}
+
+/** The opaque Wakeshift `user` for a principal: first 32 hex of HMAC-SHA256(secret, brain \n principal). */
+export function wakeshiftUserId(secret: Buffer, brainKey: string, principal: string): string {
+ return createHmac('sha256', secret).update(`${brainKey}\n${principal}`).digest('hex').slice(0, 32);
+}
diff --git a/src/core/wakeshift/drain.ts b/src/core/wakeshift/drain.ts
new file mode 100644
index 0000000000..b2356c43ac
--- /dev/null
+++ b/src/core/wakeshift/drain.ts
@@ -0,0 +1,184 @@
+/**
+ * Wake delivery by pull reconciliation (plan D7). No outbox and no hook in the
+ * job queue: jobs reach a terminal state in many places and
+ * `remove_on_complete` deletes rows, so the drainer joins open watches to
+ * `minion_jobs` instead and emits when a job's terminal marker
+ * (`<finished_us>:<status>`, or `gone`) differs from what the watch
+ * delivered. It runs on a 5 s timer inside `gbrain serve` (stdio and HTTP) and
+ * the job worker, once more at the end of `gbrain jobs work`, and inside
+ * watch_job for a job that already finished.
+ *
+ * Bounded: at most 20 rows a tick; a lease (conditional UPDATE) so two hosts
+ * never emit one row; 5 attempts backing off 30 s, 2 m, 8 m, 30 m (a 429 waits
+ * its Retry-After within the same cap); any other 4xx is final. A dead,
+ * revoked or expired watch is ended at Wakeshift once, so the conversation is
+ * told. Off or keyless: the tick returns before touching the database.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { memberIdentityFor } from '../access/caller.ts';
+import { WakeshiftError, type WakeshiftApi } from './client.ts';
+import { wakeshiftRuntime } from './config.ts';
+import { JOB_FINISHED, jobMarker, jobWake, wakeEmitId, type JobSnapshot } from './events.ts';
+
+export const WAKE_RETRY_SCHEDULE_S = [30, 120, 480, 1800] as const;
+export const WAKE_MAX_ATTEMPTS = 5;
+export const WAKE_DRAIN_BATCH = 20;
+export const WAKE_DRAIN_TICK_MS = 5_000;
+const LEASE_S = 60;
+const TERMINAL = `('completed', 'failed', 'dead', 'cancelled')`;
+
+export interface WakeRow {
+ id: number;
+ event: string;
+ target: string;
+ principal_kind: 'oauth_client' | 'legacy_token' | 'local_stdio';
+ principal_id: string;
+ member_id: string | null;
+ wake_user: string;
+ ws_subscription_id: string;
+ attempts: number;
+ job_id: number | null;
+ job_name: string | null;
+ job_status: string | null;
+ started_at: Date | string | null;
+ finished_at: Date | string | null;
+ finished_us: string | null;
+}
+
+export interface DrainReport { delivered: number; retried: number; dead: number; ended: number; skipped?: 'off' }
+
+const CANDIDATES_SQL = (byId: boolean) => `
+SELECT w.id, w.event, w.target, w.principal_kind, w.principal_id, w.member_id, w.wake_user, w.ws_subscription_id, w.attempts,
+ j.id AS job_id, j.name AS job_name, j.status AS job_status, j.started_at, j.finished_at,
+ (floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text AS finished_us
+ FROM wake_subscriptions w
+ LEFT JOIN minion_jobs j ON w.event = '${JOB_FINISHED}' AND j.id = CASE WHEN w.target ~ '^[0-9]{1,18}$' THEN w.target::bigint END
+ WHERE w.state = 'open' AND w.next_attempt_at <= now() AND (w.lease_until IS NULL OR w.lease_until < now())
+ AND (j.id IS NULL OR j.status IN ${TERMINAL})
+ AND w.delivered_marker IS DISTINCT FROM CASE WHEN j.id IS NULL THEN 'gone' ELSE
+ (floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text || ':' || j.status END
+ ${byId ? 'AND w.id = ANY($1::bigint[])' : ''}
+ ORDER BY w.next_attempt_at, w.id
+ LIMIT ${WAKE_DRAIN_BATCH}`;
+
+async function claim(engine: BrainEngine, id: number): Promise<boolean> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `UPDATE wake_subscriptions SET lease_until = now() + interval '${LEASE_S} seconds', updated_at = now()
+ WHERE id = $1 AND state = 'open' AND (lease_until IS NULL OR lease_until < now()) RETURNING id`, [id]);
+ return rows.length > 0;
+}
+
+async function settle(engine: BrainEngine, id: number, state: 'open' | 'delivered' | 'dead' | 'ended', fields: { marker?: string; attempts?: number; delayS?: number; error?: string | null }): Promise<void> {
+ await engine.executeRaw(
+ `UPDATE wake_subscriptions SET state = $2, lease_until = NULL, updated_at = now(),
+ delivered_marker = COALESCE($3, delivered_marker), attempts = COALESCE($4, attempts),
+ next_attempt_at = CASE WHEN $5::int IS NULL THEN next_attempt_at ELSE now() + make_interval(secs => $5::int) END,
+ last_error = $6
+ WHERE id = $1`, [id, state, fields.marker ?? null, fields.attempts ?? null, fields.delayS ?? null, fields.error ?? null]);
+}
+
+/** The subscribing credential still exists and, when it was bound to a member, that member is still live. */
+export async function principalLive(engine: BrainEngine, row: Pick<WakeRow, 'principal_kind' | 'principal_id' | 'member_id'>): Promise<boolean> {
+ if (row.principal_kind === 'oauth_client') {
+ const live = await engine.executeRaw('SELECT 1 FROM oauth_clients WHERE client_id = $1 AND deleted_at IS NULL', [row.principal_id]);
+ if (live.length === 0) return false;
+ } else if (row.principal_kind === 'legacy_token') {
+ const live = await engine.executeRaw('SELECT 1 FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL', [row.principal_id]);
+ if (live.length === 0) return false;
+ }
+ if (!row.member_id) return true;
+ const identity = await memberIdentityFor(engine, { principal: { kind: row.principal_kind, id: row.principal_id } });
+ return identity.includes(`member:${row.member_id}`);
+}
+
+/** End a watch at Wakeshift once (best effort: the conversation is told; a failure leaves Wakeshift's own ttl to end it). */
+export async function endAtWakeshift(api: WakeshiftApi, row: Pick<WakeRow, 'wake_user' | 'ws_subscription_id'>): Promise<boolean> {
+ try { return (await api.end({ user: row.wake_user, id: row.ws_subscription_id })).ended === true; } catch { return false; }
+}
+
+function jobOf(row: WakeRow): JobSnapshot | null {
+ return row.job_id == null ? null : { id: Number(row.job_id), name: row.job_name, status: row.job_status, started_at: row.started_at, finished_at: row.finished_at, finished_us: row.finished_us };
+}
+
+async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, report: DrainReport): Promise<void> {
+ if (!(await claim(engine, row.id))) return;
+ try {
+ if (!(await principalLive(engine, row))) {
+ await endAtWakeshift(api, row);
+ await settle(engine, row.id, 'ended', { error: 'principal_revoked' });
+ report.ended++;
+ return;
+ }
+ const job = jobOf(row);
+ const marker = jobMarker(job);
+ const { payload, text } = jobWake(Number(row.target), job);
+ try {
+ await api.emit({
+ name: row.event, arguments: { job: Number(row.target) }, payload, text,
+ id: wakeEmitId(row.event, row.target, marker, row.id),
+ to: [{ user: row.wake_user, subscription: row.ws_subscription_id }],
+ });
+ await settle(engine, row.id, 'delivered', { marker, error: null });
+ report.delivered++;
+ } catch (e) {
+ const err = e instanceof WakeshiftError ? e : new WakeshiftError(0, 'network', String(e));
+ const attempts = row.attempts + 1;
+ const retryable = err.status === 0 || err.status === 429 || err.status >= 500;
+ if (!retryable || attempts >= WAKE_MAX_ATTEMPTS) {
+ await endAtWakeshift(api, row);
+ await settle(engine, row.id, 'dead', { attempts, error: err.code });
+ report.dead++;
+ return;
+ }
+ const cap = WAKE_RETRY_SCHEDULE_S[WAKE_RETRY_SCHEDULE_S.length - 1];
+ const base = WAKE_RETRY_SCHEDULE_S[attempts - 1] ?? cap;
+ const delayS = err.status === 429 && err.retryAfterS !== undefined ? Math.min(cap, Math.max(1, Math.ceil(err.retryAfterS))) : base;
+ await settle(engine, row.id, 'open', { attempts, delayS, error: err.code });
+ report.retried++;
+ }
+ } catch (e) {
+ await settle(engine, row.id, 'open', { error: 'drain_error' }).catch(() => {});
+ throw e;
+ }
+}
+
+/**
+ * One reconciliation pass: ends expired watches, then delivers up to 20 due ones (only `ids` when given). Returns
+ * `skipped: 'off'` without a query when reporting back is off or keyless. `api` is a test seam.
+ */
+export async function drainWakes(engine: BrainEngine, opts: { ids?: number[]; api?: WakeshiftApi } = {}): Promise<DrainReport> {
+ const report: DrainReport = { delivered: 0, retried: 0, dead: 0, ended: 0 };
+ const api = opts.api ?? wakeshiftRuntime()?.api;
+ if (!api) return { ...report, skipped: 'off' };
+ const expired = await engine.executeRaw<{ id: number; wake_user: string; ws_subscription_id: string }>(
+ `UPDATE wake_subscriptions SET state = 'ended', last_error = 'expired', updated_at = now()
+ WHERE state = 'open' AND expires_at < now() RETURNING id, wake_user, ws_subscription_id`);
+ report.ended += expired.length;
+ const rows = await engine.executeRaw<WakeRow>(CANDIDATES_SQL(opts.ids !== undefined), opts.ids !== undefined ? [opts.ids] : []);
+ for (const row of rows) await deliver(engine, api, row, report);
+ return report;
+}
+
+/** Passes until one has nothing left to settle (at most 10): the final pass of a process about to exit (`gbrain jobs work`). */
+export async function drainWakesUntilIdle(engine: BrainEngine): Promise<DrainReport> {
+ const total: DrainReport = { delivered: 0, retried: 0, dead: 0, ended: 0 };
+ for (let i = 0; i < 10; i++) {
+ const r = await drainWakes(engine);
+ if (r.skipped) return { ...total, skipped: r.skipped };
+ total.delivered += r.delivered; total.retried += r.retried; total.dead += r.dead; total.ended += r.ended;
+ if (r.delivered + r.dead + r.ended === 0) break;
+ }
+ return total;
+}
+
+/** The 5 s drainer timer for a long-lived process (serve, worker). Never throws, never keeps the process alive. */
+export function startWakeDrain(engine: BrainEngine, opts: { intervalMs?: number; onError?: (e: unknown) => void } = {}): { stop(): void } {
+ let running = false;
+ const timer = setInterval(() => {
+ if (running) return;
+ running = true;
+ drainWakes(engine).catch(e => opts.onError?.(e)).finally(() => { running = false; });
+ }, opts.intervalMs ?? WAKE_DRAIN_TICK_MS);
+ timer.unref?.();
+ return { stop: () => clearInterval(timer) };
+}
diff --git a/src/core/wakeshift/events.ts b/src/core/wakeshift/events.ts
new file mode 100644
index 0000000000..6dc0417d9e
--- /dev/null
+++ b/src/core/wakeshift/events.ts
@@ -0,0 +1,96 @@
+/**
+ * The events gbrain offers Wakeshift (plan D2, D3). PR 1 ships one:
+ * `gbrain.job.finished`, a minion job reaching completed, failed, dead or
+ * cancelled. Every event is personal (only the named subscription gets an
+ * occurrence) and deleted on delivery. The payload is a pointer: ids, status,
+ * kind, times and the exact next call. Never page text, titles or slugs, so a
+ * wake cannot widen readable_by, folder rules or private pages; the agent's
+ * follow-up read goes through gbrain's own access checks.
+ */
+export const JOB_FINISHED = 'gbrain.job.finished';
+
+const JOB_PAYLOAD = {
+ type: 'object',
+ properties: {
+ job: { type: 'integer', minimum: 1 },
+ name: { type: 'string', maxLength: 100 },
+ status: { type: 'string', enum: ['completed', 'failed', 'dead', 'cancelled', 'gone'] },
+ started_at: { type: ['string', 'null'] },
+ finished_at: { type: ['string', 'null'] },
+ duration_ms: { type: ['integer', 'null'], minimum: 0 },
+ next: { type: 'string', maxLength: 200 },
+ },
+ required: ['job', 'status', 'next'],
+ additionalProperties: false,
+} as const;
+
+/** The manifest `gbrain wakeshift enable` merges (POST /manifest/merge); topic as the SDK would build it. */
+export function wakeshiftManifest(): { events: Record<string, unknown>[] } {
+ return {
+ events: [{
+ name: JOB_FINISHED,
+ title: 'gbrain job finished',
+ description: 'A gbrain background job you are watching reached completed, failed, dead or cancelled. The payload is a pointer: call get_job with the id for the result.',
+ arguments: { type: 'object', properties: { job: { type: 'integer', minimum: 1 } }, required: ['job'], additionalProperties: false },
+ payload: JOB_PAYLOAD,
+ topic: `ev/${JOB_FINISHED}/{job}`,
+ personal: true,
+ delete_on_delivery: true,
+ }],
+ };
+}
+
+export interface JobSnapshot {
+ id: number;
+ name: string | null;
+ status: string | null;
+ started_at: Date | string | null;
+ finished_at: Date | string | null;
+ /** finished_at in microseconds since the epoch (terminal-events.ts ordering), null when the row is gone. */
+ finished_us: string | null;
+}
+
+const PHRASE: Record<string, string> = {
+ completed: 'finished ok', failed: 'failed', dead: 'is dead (out of attempts)', cancelled: 'was cancelled', gone: 'finished; its details are gone',
+};
+
+function iso(v: Date | string | null): string | null {
+ if (v == null) return null;
+ const d = v instanceof Date ? v : new Date(v);
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
+}
+
+export function formatDuration(ms: number): string {
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s}s`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m${String(s % 60).padStart(2, '0')}s`;
+ return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`;
+}
+
+/** The job's terminal marker `<finished_us>:<status>` (`gone` when the row was removed). */
+export function jobMarker(job: JobSnapshot | null): string {
+ return job?.status ? `${job.finished_us ?? '0'}:${job.status}` : 'gone';
+}
+
+/** Emit id: `<event>:<target>:<marker>:<watch row id>`, so two watchers and a re-run job never collide. */
+export function wakeEmitId(event: string, target: string, marker: string, rowId: number | string): string {
+ return `${event}:${target}:${marker}:${rowId}`;
+}
+
+/** Payload and the line the agent reads first, for a watched job (or its removed row). */
+export function jobWake(jobId: number, job: JobSnapshot | null): { payload: Record<string, unknown>; text: string } {
+ const status = job?.status ?? 'gone';
+ const started = iso(job?.started_at ?? null);
+ const finished = iso(job?.finished_at ?? null);
+ const duration = started && finished ? Math.max(0, Date.parse(finished) - Date.parse(started)) : null;
+ const next = status === 'gone' ? `list_jobs (job ${jobId} was removed after it finished)` : `get_job ${jobId}`;
+ const kind = job?.name ? ` (${job.name.slice(0, 100)})` : '';
+ const took = duration != null ? ` in ${formatDuration(duration)}` : '';
+ return {
+ payload: { job: jobId, ...(job?.name ? { name: job.name.slice(0, 100) } : {}), status, started_at: started, finished_at: finished, duration_ms: duration, next },
+ text: status === 'gone'
+ ? `gbrain: job ${jobId} ${PHRASE.gone}. Call list_jobs to see recent jobs.`
+ : `gbrain: job ${jobId}${kind} ${PHRASE[status] ?? status}${took}. Call get_job ${jobId} for the result.`,
+ };
+}
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 3fce62c0a3..3e5c4a952e 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -175,6 +175,8 @@ export interface ToolResult {
}
export interface DispatchOpts {
+ /** Wakeshift: the MCP caller as the transport saw it (OperationContext.mcpCaller); never from tool arguments. */
+ mcpCaller?: OperationContext['mcpCaller'];
/** GST-359 C1: the x-qm-actor header the HTTP transport read (a trusted system names the person); stdio never sets it. */
actor?: ActorChannels;
/**
@@ -808,6 +810,14 @@ function attachResponseMeta(out: ToolResult, responseMeta: Record<string, unknow
out._meta = { ...(out._meta ?? {}), degraded: stamp };
}
+type ToolTail = Parameters<NonNullable<OperationContext['emitToolTail']>>[0];
+
+/** Wakeshift's addition: its text as the LAST text block, its meta merged into `_meta` (a conversation credential: never logged). */
+function appendToolTail(out: ToolResult, tail: ToolTail): void {
+ if (tail.text) out.content.push({ type: 'text', text: tail.text });
+ if (tail.meta && typeof tail.meta === 'object') out._meta = { ...(out._meta ?? {}), ...tail.meta };
+}
+
/** The one error result path: toAgentError → exactly one content block. */
export function errorResult(e: unknown, opts: DispatchOpts, extra: { op?: string; mutating?: boolean; idempotent?: boolean; notices?: Notice[] } = {}): ToolResult {
const carried = !!extra.notices?.length && e instanceof OperationError;
@@ -916,6 +926,7 @@ export function buildOperationContext(
...(opts.admissionOrigin ? { admissionOrigin: opts.admissionOrigin } : {}),
...(opts.resultRows ? { resultRows: opts.resultRows } : {}),
...(opts.thinClient ? { thinClient: true } : {}),
+ ...(opts.mcpCaller ? { mcpCaller: opts.mcpCaller } : {}),
isCallable: (opName: string) => (render ??= dispatchRenderContext(opts)).isCallable(opName),
auth: opts.auth,
};
@@ -1203,6 +1214,8 @@ async function dispatchResolvedCall(
// failure renders the envelope's `notices` key (one block).
const notices: Notice[] = [];
ctx.emitNotice = (n) => { if (n) notices.push(n); };
+ let tail: ToolTail | undefined;
+ ctx.emitToolTail = (t) => { tail = t; };
try {
if (ctx.remote !== false && op.requiredScopes?.length) {
@@ -1321,6 +1334,7 @@ async function dispatchResolvedCall(
if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };
if (failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${failure}; degrading to no hook keys`);
}
+ if (tail) appendToolTail(out, tail);
// Large pages: the egress backstop measures the final frame; a read over the connection's cap is refused whole, never cut.
const over = op.mutating ? null : await frameOverCap(out, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });
if (over) return errorResult(resultTooLargeError(name, safeParams, over), opts, { op: name, mutating: false, idempotent: op.idempotent === true });
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index b663b36c60..c03d466fcd 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -569,6 +569,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
takesHoldersAllowList: auth.takesHoldersAllowList,
sourceId: auth.sourceId,
...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },
+ mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta }, // Wakeshift; shape only
actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope
// to the operator-granted sources via sourceScopeOpts.
auth: auth.auth,
diff --git a/src/mcp/publish-gates.ts b/src/mcp/publish-gates.ts
index 3f113c9e83..e07a35938f 100644
--- a/src/mcp/publish-gates.ts
+++ b/src/mcp/publish-gates.ts
@@ -21,11 +21,12 @@ import type { BrainEngine } from '../core/engine.ts';
import type { GBrainConfig } from '../core/config.ts';
import type { OperationMeta } from '../core/ops/contract.ts';
import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
+import { wakeshiftPublished } from '../core/wakeshift/config.ts';
export type PublishGateKey = NonNullable<OperationMeta['publishGateKey']>;
-/** Every config key an operation's publish gate reads; `config get` resolves these DB-first like the gate (#5358). */
-export const PUBLISH_GATE_KEYS: ReadonlySet<PublishGateKey> = new Set(OPERATION_MANIFEST.flatMap(op => (op.publishGateKey ? [op.publishGateKey] : [])));
+/** Every config key a DB-first publish gate reads; `config get` resolves these DB-first like the gate (#5358). Wakeshift's has no config key. */
+export const PUBLISH_GATE_KEYS: ReadonlySet<PublishGateKey> = new Set(OPERATION_MANIFEST.flatMap(op => (op.publishGateKey && op.publishGateKey !== 'mcp.publish_wakeshift' ? [op.publishGateKey] : [])));
/**
* Gates that default ON for the owner's stdio pipe when neither plane sets
@@ -41,6 +42,8 @@ export async function readPublishGate(
key: PublishGateKey,
transport?: string,
): Promise<boolean> {
+ // Wakeshift: the host file plane (`gbrain wakeshift enable`) plus a usable key, never the DB plane a remote writer reaches.
+ if (key === 'mcp.publish_wakeshift') return wakeshiftPublished();
let dbVal: string | null = null;
let readFailed = false;
try {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 5309ba62c3..aa0221010b 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -496,6 +496,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
transport: 'stdio', inboundFrameBytes: MCP_STDIO_MAX_MESSAGE_BYTES,
takesHoldersAllowList: ['world'],
...(sessionId ? { sessionId } : {}), ...(hotMemoryOffIn(request.params) ? { hotMemoryOff: true } : {}), onBehalfOf: { requestMeta: request.params?._meta },
+ mcpCaller: { client: server?.getClientVersion()?.name, meta: request.params?._meta },
sourceId: sourceScope.sourceId,
...(sourceScope.localFederatedSourceIds
? { localFederatedSourceIds: sourceScope.localFederatedSourceIds }