@remnic/core 9.3.733 → 9.3.735
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-boundary.d.ts +13 -11
- package/dist/access-boundary.js +9 -9
- package/dist/access-cli.js +26 -24
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +13 -11
- package/dist/access-http.js +14 -14
- package/dist/access-mcp.d.ts +13 -11
- package/dist/access-mcp.js +13 -13
- package/dist/access-operations-batch.js +11 -11
- package/dist/access-operations.d.ts +13 -11
- package/dist/access-operations.js +12 -12
- package/dist/access-schema.d.ts +4 -4
- package/dist/{access-service-Byoe3HsT.d.ts → access-service-CVx7mmvK.d.ts} +4 -4
- package/dist/access-service.d.ts +13 -11
- package/dist/access-service.js +8 -8
- package/dist/access-surface-catalog.d.ts +13 -11
- package/dist/action-confidence.d.ts +1 -1
- package/dist/active-memory-bridge.d.ts +1 -1
- package/dist/active-memory-bridge.js +3 -2
- package/dist/active-recall.d.ts +1 -1
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +12 -10
- package/dist/briefing.d.ts +1 -1
- package/dist/buffer-surprise-report.d.ts +1 -1
- package/dist/buffer.d.ts +1 -1
- package/dist/calibration.d.ts +1 -1
- package/dist/capabilities.d.ts +196 -2
- package/dist/capabilities.js +21 -3
- package/dist/{catalog-DM1nk7cM.d.ts → catalog-BVhDEUhT.d.ts} +2 -2
- package/dist/causal-behavior.d.ts +1 -1
- package/dist/causal-consolidation.d.ts +1 -1
- package/dist/causal-trajectory-graph.d.ts +1 -1
- package/dist/{chunk-CX77GNMB.js → chunk-2T2N7ISV.js} +6 -3
- package/dist/chunk-2T2N7ISV.js.map +1 -0
- package/dist/{chunk-HHNSLPX7.js → chunk-5BOQNB2K.js} +10 -9
- package/dist/chunk-5BOQNB2K.js.map +1 -0
- package/dist/{chunk-QZHF4BWN.js → chunk-AAIHDIMD.js} +6 -6
- package/dist/{chunk-H3MB3F62.js → chunk-AB2E5DCN.js} +4 -3
- package/dist/chunk-AB2E5DCN.js.map +1 -0
- package/dist/{chunk-KSJCXXOU.js → chunk-AE7NTZ75.js} +6 -3
- package/dist/chunk-AE7NTZ75.js.map +1 -0
- package/dist/{chunk-OTQE66IX.js → chunk-AESC5OQJ.js} +6 -3
- package/dist/chunk-AESC5OQJ.js.map +1 -0
- package/dist/{chunk-FFUCCKPN.js → chunk-BXPG5AVX.js} +10 -7
- package/dist/chunk-BXPG5AVX.js.map +1 -0
- package/dist/{chunk-P3VJCTVE.js → chunk-CHJIWG2H.js} +4 -3
- package/dist/chunk-CHJIWG2H.js.map +1 -0
- package/dist/{chunk-FYWUNVFZ.js → chunk-E4LYJ7PY.js} +6 -6
- package/dist/{chunk-NIZQH6AU.js → chunk-FF36YNKY.js} +8 -7
- package/dist/chunk-FF36YNKY.js.map +1 -0
- package/dist/{chunk-OUITHS6V.js → chunk-FLCYY5JX.js} +801 -711
- package/dist/chunk-FLCYY5JX.js.map +1 -0
- package/dist/{chunk-PLBIPT6I.js → chunk-FLPKEMSO.js} +7 -4
- package/dist/chunk-FLPKEMSO.js.map +1 -0
- package/dist/{chunk-6TUWSUUD.js → chunk-G54IDCD3.js} +59 -53
- package/dist/chunk-G54IDCD3.js.map +1 -0
- package/dist/{chunk-J6BH2OBA.js → chunk-GB2FZOWB.js} +8 -5
- package/dist/chunk-GB2FZOWB.js.map +1 -0
- package/dist/{chunk-CGPHMNL4.js → chunk-GYICIICQ.js} +10 -6
- package/dist/chunk-GYICIICQ.js.map +1 -0
- package/dist/{chunk-DKT3X5C3.js → chunk-HFXZIF3V.js} +7 -4
- package/dist/chunk-HFXZIF3V.js.map +1 -0
- package/dist/{chunk-646B5ERJ.js → chunk-HLPYL6LC.js} +71 -65
- package/dist/chunk-HLPYL6LC.js.map +1 -0
- package/dist/{chunk-ZVHRSR2R.js → chunk-IPI45Q4S.js} +6 -3
- package/dist/chunk-IPI45Q4S.js.map +1 -0
- package/dist/{chunk-24D66MMN.js → chunk-IX4L7E5G.js} +7 -4
- package/dist/chunk-IX4L7E5G.js.map +1 -0
- package/dist/{chunk-SYX73XD7.js → chunk-IXGXALRV.js} +10 -7
- package/dist/chunk-IXGXALRV.js.map +1 -0
- package/dist/{chunk-ESF7TRYJ.js → chunk-JWDE7OVJ.js} +79 -2
- package/dist/chunk-JWDE7OVJ.js.map +1 -0
- package/dist/{chunk-GGL34GCW.js → chunk-K3Y2SJTN.js} +7 -4
- package/dist/chunk-K3Y2SJTN.js.map +1 -0
- package/dist/{chunk-PMAQRUN4.js → chunk-NDKW67ER.js} +5 -2
- package/dist/chunk-NDKW67ER.js.map +1 -0
- package/dist/{chunk-ZQUAVZNG.js → chunk-NNJKEAP2.js} +7 -4
- package/dist/chunk-NNJKEAP2.js.map +1 -0
- package/dist/{chunk-UZYLX7M6.js → chunk-OYHYBHHI.js} +9 -6
- package/dist/chunk-OYHYBHHI.js.map +1 -0
- package/dist/{chunk-NOU77OHX.js → chunk-P6VLG7KE.js} +2 -2
- package/dist/{chunk-O4ZIBPIW.js → chunk-QNTLWH3T.js} +3 -3
- package/dist/{chunk-LUCARK4W.js → chunk-UO6MPN77.js} +37 -35
- package/dist/chunk-UO6MPN77.js.map +1 -0
- package/dist/{chunk-HJWQJUKQ.js → chunk-VOEVVIP3.js} +3 -3
- package/dist/{chunk-KQYGNGON.js → chunk-ZBZ4XULO.js} +6 -3
- package/dist/chunk-ZBZ4XULO.js.map +1 -0
- package/dist/{cli-Dt-tuiYH.d.ts → cli-Cx5Mxwk7.d.ts} +3 -3
- package/dist/cli.d.ts +14 -12
- package/dist/cli.js +20 -20
- package/dist/compounding/engine.d.ts +3 -2
- package/dist/compounding/engine.js +2 -1
- package/dist/compounding/preference-consolidator.d.ts +1 -1
- package/dist/compression-optimizer.d.ts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/connectors/codex-materialize-runner.d.ts +1 -1
- package/dist/connectors/codex-materialize.d.ts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/consolidation-provenance-check.d.ts +1 -1
- package/dist/consolidation-undo.d.ts +1 -1
- package/dist/contradiction/index.d.ts +2 -2
- package/dist/contradiction/index.js +2 -1
- package/dist/{contradiction-scan-HWGEOUDS.js → contradiction-scan-2B4AE4TI.js} +3 -2
- package/dist/conversation-index/backend.d.ts +1 -1
- package/dist/conversation-index/chunker.d.ts +1 -1
- package/dist/conversation-index/faiss-adapter.d.ts +1 -1
- package/dist/conversation-index/indexer.d.ts +1 -1
- package/dist/conversation-index/search.d.ts +1 -1
- package/dist/day-summary.d.ts +1 -1
- package/dist/delinearize.d.ts +1 -1
- package/dist/direct-answer-wiring.d.ts +1 -1
- package/dist/direct-answer.d.ts +1 -1
- package/dist/embedding-fallback.d.ts +1 -1
- package/dist/embedding-fallback.js +2 -2
- package/dist/enrichment/index.d.ts +1 -1
- package/dist/entity-retrieval.d.ts +1 -1
- package/dist/entity-retrieval.js +2 -1
- package/dist/entity-schema.d.ts +1 -1
- package/dist/explicit-capture.d.ts +12 -10
- package/dist/explicit-capture.js +2 -1
- package/dist/extraction-faithfulness.d.ts +1 -1
- package/dist/extraction-judge-telemetry.d.ts +1 -1
- package/dist/extraction-judge-training.d.ts +1 -1
- package/dist/extraction-judge.d.ts +1 -1
- package/dist/extraction.d.ts +1 -1
- package/dist/extraction.js +3 -3
- package/dist/fallback-llm.d.ts +1 -1
- package/dist/{first-start-migration-OOR57AYR.js → first-start-migration-2RQYDIZ7.js} +10 -8
- package/dist/first-start-migration-2RQYDIZ7.js.map +1 -0
- package/dist/graph-dashboard-diff.d.ts +1 -1
- package/dist/graph-dashboard-key.d.ts +1 -1
- package/dist/graph-dashboard-parser.d.ts +1 -1
- package/dist/graph-edge-reinforcement.d.ts +1 -1
- package/dist/graph-snapshot.d.ts +1 -1
- package/dist/graph.d.ts +1 -1
- package/dist/identity-continuity.d.ts +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/index.d.ts +12 -12
- package/dist/index.js +44 -44
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/local-llm.js +2 -1
- package/dist/local-model-endpoint.d.ts +1 -1
- package/dist/maintenance/memory-governance.d.ts +1 -1
- package/dist/mcp-memory-inspector-app.d.ts +13 -11
- package/dist/memory-action-policy.d.ts +1 -1
- package/dist/memory-cache.d.ts +1 -1
- package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-provenance.d.ts +1 -1
- package/dist/memory-worth-outcomes.d.ts +1 -1
- package/dist/models-json.d.ts +1 -1
- package/dist/namespaces/migrate.d.ts +2 -2
- package/dist/namespaces/migrate.js +6 -6
- package/dist/namespaces/principal.d.ts +1 -1
- package/dist/namespaces/principal.js +2 -1
- package/dist/namespaces/search.d.ts +1 -1
- package/dist/namespaces/search.js +4 -4
- package/dist/namespaces/storage.d.ts +2 -2
- package/dist/namespaces/storage.js +2 -1
- package/dist/native-knowledge.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +1 -1
- package/dist/operator-toolkit.js +11 -11
- package/dist/orchestration/compression-guideline-coordinator.d.ts +1 -1
- package/dist/orchestration/compression-guideline-coordinator.js +2 -1
- package/dist/orchestration/maintenance.d.ts +2 -2
- package/dist/orchestration/maintenance.js +6 -5
- package/dist/{orchestrator-B4KjaOtY.d.ts → orchestrator-oF0cceBX.d.ts} +143 -18
- package/dist/orchestrator.d.ts +8 -6
- package/dist/orchestrator.js +21 -19
- package/dist/patterns-cli.d.ts +1 -1
- package/dist/policy-runtime.d.ts +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +1 -1
- package/dist/recall-disclosure-escalation.d.ts +1 -1
- package/dist/recall-explain-renderer.d.ts +1 -1
- package/dist/recall-planner-llm.d.ts +1 -1
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray.d.ts +1 -1
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/schemas.d.ts +2 -2
- package/dist/search/embed-helper.d.ts +1 -1
- package/dist/search/embed-helper.js +2 -2
- package/dist/search/factory.d.ts +1 -1
- package/dist/search/factory.js +3 -3
- package/dist/search/index.d.ts +1 -1
- package/dist/search/index.js +3 -3
- package/dist/search/lancedb-backend.d.ts +1 -1
- package/dist/search/meilisearch-backend.d.ts +1 -1
- package/dist/search/noop-backend.d.ts +1 -1
- package/dist/search/orama-backend.d.ts +1 -1
- package/dist/search/port.d.ts +1 -1
- package/dist/search/remote-backend.d.ts +1 -1
- package/dist/{semantic-SLAa_prH.d.ts → semantic-DJR8_DMQ.d.ts} +1 -1
- package/dist/{semantic-consolidation-CstTvHPo.d.ts → semantic-consolidation-DKGbufYO.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +2 -2
- package/dist/semantic-rule-verifier.d.ts +1 -1
- package/dist/session-observer-bands.d.ts +1 -1
- package/dist/session-observer-state.d.ts +1 -1
- package/dist/shared-context/manager.d.ts +3 -3
- package/dist/signal.d.ts +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/summarizer.d.ts +1 -1
- package/dist/summarizer.js +3 -2
- package/dist/summary-snapshot.d.ts +1 -1
- package/dist/temporal-supersession.d.ts +1 -1
- package/dist/temporal-validity.d.ts +1 -1
- package/dist/threading.d.ts +1 -1
- package/dist/tier-migration.d.ts +1 -1
- package/dist/tier-routing.d.ts +1 -1
- package/dist/{tier-stats-3LYQ3VV5.js → tier-stats-KPDIISG7.js} +8 -4
- package/dist/tier-stats-KPDIISG7.js.map +1 -0
- package/dist/topics.d.ts +1 -1
- package/dist/transcript.d.ts +1 -1
- package/dist/transfer/types.d.ts +30 -30
- package/dist/trust-score-stage.d.ts +1 -1
- package/dist/trust-score.d.ts +1 -1
- package/dist/{types-VkxElCHR.d.ts → types-C7UCxpuO.d.ts} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/package.json +2 -2
- package/src/access-service.ts +61 -56
- package/src/active-memory-bridge.ts +2 -1
- package/src/admin/admin-surfaces.ts +2 -1
- package/src/capabilities.test.ts +375 -0
- package/src/capabilities.ts +403 -0
- package/src/cli/creation-ledger-commands.ts +2 -2
- package/src/cli/research-status-commands.ts +13 -13
- package/src/cli.ts +29 -25
- package/src/compounding/engine.ts +4 -3
- package/src/contradiction/contradiction-scan.ts +4 -3
- package/src/embedding-fallback.ts +5 -2
- package/src/entity-retrieval.ts +3 -2
- package/src/explicit-capture.ts +2 -1
- package/src/extraction.ts +6 -3
- package/src/local-llm.ts +4 -3
- package/src/maintenance/first-start-migration.ts +8 -5
- package/src/maintenance/namespace-maintenance-fanout.ts +2 -1
- package/src/maintenance/namespace-planner.ts +4 -3
- package/src/maintenance/tier-stats.ts +4 -3
- package/src/namespaces/catalog.ts +2 -1
- package/src/namespaces/migrate.ts +2 -1
- package/src/namespaces/principal.ts +6 -5
- package/src/namespaces/scope-profiles.ts +2 -1
- package/src/namespaces/search.ts +2 -1
- package/src/namespaces/storage.ts +4 -3
- package/src/operator-toolkit.ts +27 -26
- package/src/orchestration/compression-guideline-coordinator.ts +7 -6
- package/src/orchestration/lifecycle-policy-coordinator.ts +504 -0
- package/src/orchestration/maintenance.ts +8 -4
- package/src/orchestration/semantic-consolidation-coordinator.ts +454 -0
- package/src/orchestration/tier-migration-coordinator.ts +5 -4
- package/src/orchestrator.ts +106 -800
- package/src/scopes/scope-plan.ts +3 -2
- package/src/search/embed-helper.ts +5 -2
- package/src/search/factory.ts +9 -6
- package/src/summarizer.ts +3 -2
- package/dist/chunk-24D66MMN.js.map +0 -1
- package/dist/chunk-646B5ERJ.js.map +0 -1
- package/dist/chunk-6TUWSUUD.js.map +0 -1
- package/dist/chunk-CGPHMNL4.js.map +0 -1
- package/dist/chunk-CX77GNMB.js.map +0 -1
- package/dist/chunk-DKT3X5C3.js.map +0 -1
- package/dist/chunk-ESF7TRYJ.js.map +0 -1
- package/dist/chunk-FFUCCKPN.js.map +0 -1
- package/dist/chunk-GGL34GCW.js.map +0 -1
- package/dist/chunk-H3MB3F62.js.map +0 -1
- package/dist/chunk-HHNSLPX7.js.map +0 -1
- package/dist/chunk-J6BH2OBA.js.map +0 -1
- package/dist/chunk-KQYGNGON.js.map +0 -1
- package/dist/chunk-KSJCXXOU.js.map +0 -1
- package/dist/chunk-LUCARK4W.js.map +0 -1
- package/dist/chunk-NIZQH6AU.js.map +0 -1
- package/dist/chunk-OTQE66IX.js.map +0 -1
- package/dist/chunk-OUITHS6V.js.map +0 -1
- package/dist/chunk-P3VJCTVE.js.map +0 -1
- package/dist/chunk-PLBIPT6I.js.map +0 -1
- package/dist/chunk-PMAQRUN4.js.map +0 -1
- package/dist/chunk-SYX73XD7.js.map +0 -1
- package/dist/chunk-UZYLX7M6.js.map +0 -1
- package/dist/chunk-ZQUAVZNG.js.map +0 -1
- package/dist/chunk-ZVHRSR2R.js.map +0 -1
- package/dist/first-start-migration-OOR57AYR.js.map +0 -1
- package/dist/tier-stats-3LYQ3VV5.js.map +0 -1
- /package/dist/{chunk-QZHF4BWN.js.map → chunk-AAIHDIMD.js.map} +0 -0
- /package/dist/{chunk-FYWUNVFZ.js.map → chunk-E4LYJ7PY.js.map} +0 -0
- /package/dist/{chunk-NOU77OHX.js.map → chunk-P6VLG7KE.js.map} +0 -0
- /package/dist/{chunk-O4ZIBPIW.js.map → chunk-QNTLWH3T.js.map} +0 -0
- /package/dist/{chunk-HJWQJUKQ.js.map → chunk-VOEVVIP3.js.map} +0 -0
- /package/dist/{contradiction-scan-HWGEOUDS.js.map → contradiction-scan-2B4AE4TI.js.map} +0 -0
|
@@ -11,7 +11,10 @@ import {
|
|
|
11
11
|
defaultNamespaceForPrincipal,
|
|
12
12
|
recallNamespacesForPrincipal,
|
|
13
13
|
resolvePrincipal
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-OYHYBHHI.js";
|
|
15
|
+
import {
|
|
16
|
+
resolveNamespaceCapabilities
|
|
17
|
+
} from "./chunk-JWDE7OVJ.js";
|
|
15
18
|
import {
|
|
16
19
|
isSafeRouteNamespace
|
|
17
20
|
} from "./chunk-U3PN77QT.js";
|
|
@@ -516,7 +519,7 @@ function resolveLayer(params) {
|
|
|
516
519
|
}
|
|
517
520
|
function resolveScopeProfilePlan(options) {
|
|
518
521
|
const active = activeScopeProfile(options.config);
|
|
519
|
-
if (!active || !options.config.
|
|
522
|
+
if (!active || !resolveNamespaceCapabilities(options.config).namespaces) return null;
|
|
520
523
|
const baseNamespace = scopeProfileSelfNamespace(options.principal, options.config);
|
|
521
524
|
const layerIds = Array.from(
|
|
522
525
|
/* @__PURE__ */ new Set([
|
|
@@ -705,7 +708,7 @@ function getConfiguredNamespaces(config) {
|
|
|
705
708
|
}
|
|
706
709
|
function resolveNamespaceFromStorageDir(storageDir, options) {
|
|
707
710
|
const { config } = options;
|
|
708
|
-
if (!config.
|
|
711
|
+
if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;
|
|
709
712
|
const resolvedStorageDir = path2.resolve(storageDir);
|
|
710
713
|
const resolvedMemoryDir = path2.resolve(config.memoryDir);
|
|
711
714
|
if (resolvedStorageDir === resolvedMemoryDir) return config.defaultNamespace;
|
|
@@ -736,7 +739,7 @@ function resolveWritableNamespaceValue(namespace, sessionKey, authenticatedPrinc
|
|
|
736
739
|
let resolved;
|
|
737
740
|
if (!requested) {
|
|
738
741
|
resolved = config.defaultNamespace;
|
|
739
|
-
} else if (!config.
|
|
742
|
+
} else if (!resolveNamespaceCapabilities(config).namespaces && requested !== config.defaultNamespace) {
|
|
740
743
|
return { ok: false, reason: "unsupported", namespace: requested };
|
|
741
744
|
} else {
|
|
742
745
|
resolved = requested;
|
|
@@ -769,4 +772,4 @@ export {
|
|
|
769
772
|
resolveNamespaceFromStorageDir,
|
|
770
773
|
resolveWritableNamespaceValue
|
|
771
774
|
};
|
|
772
|
-
//# sourceMappingURL=chunk-
|
|
775
|
+
//# sourceMappingURL=chunk-GB2FZOWB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/coding/git-context.ts","../src/coding/coding-namespace.ts","../src/namespaces/scope-profiles.ts","../src/scopes/scope-plan.ts"],"sourcesContent":["/**\n * GitContextResolver — pure module for detecting the git project + branch\n * a session is operating in.\n *\n * Introduced by issue #569 (coding-agent project/branch-scoped namespaces).\n *\n * This module is deliberately pure:\n * - no orchestrator references\n * - no config side-effects\n * - no namespace wiring\n *\n * Downstream slices (PR 2+ of #569) wire `resolveGitContext` into the\n * `NamespaceResolver` / `Orchestrator` so that memories are scoped to a\n * detected project / branch without leaking across repos.\n *\n * CLAUDE.md rule 17 (expand `~`): the `rootPath` returned here is always an\n * absolute, tilde-expanded path. Callers must not re-expand.\n *\n * CLAUDE.md rule 51 (reject invalid input): `cwd` must be an absolute path\n * and must exist. `resolveGitContext` returns `null` — rather than throwing —\n * when the directory is not inside a git worktree, because being outside a\n * repo is a normal runtime state (e.g. agent opened in a scratch dir).\n */\nimport path from \"node:path\";\n\nimport { expandTildePath } from \"../utils/path.js\";\nimport { launchProcessSync } from \"../runtime/child-process.js\";\n\n// Re-export so existing callers / tests that imported `expandTildePath` from\n// this module keep working. CLAUDE.md #17 requires consistent `~` expansion\n// across every user-facing path input; the canonical implementation now\n// lives in `utils/path.ts`.\nexport { expandTildePath };\n\n// ──────────────────────────────────────────────────────────────────────────\n// Public types\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface GitContext {\n /**\n * Stable identifier for the project. Derived from `git remote get-url origin`\n * when an origin remote is configured, otherwise from the repo root path.\n *\n * Formatted as `origin:<hex>` or `root:<hex>` so that the source is visible\n * to operators (see `remnic doctor`, issue #569 acceptance criteria).\n */\n projectId: string;\n /**\n * Current branch, e.g. `main`, `feat/foo`. `null` only in detached-HEAD\n * state (e.g. rebase in progress). Callers should treat `null` as \"no\n * branch-scope overlay applies\" without erroring.\n */\n branch: string | null;\n /**\n * Absolute path to the repository root (the directory containing `.git`).\n * Tilde-expanded per CLAUDE.md #17.\n */\n rootPath: string;\n /**\n * Best-effort default branch (usually `main` or `master`). Derived from the\n * `refs/remotes/origin/HEAD` symbolic ref. `null` when not available (e.g.\n * fresh clone without a default branch symref, or no origin remote).\n */\n defaultBranch: string | null;\n}\n\n/**\n * Injectable git-invocation surface. Only the commands `resolveGitContext`\n * actually needs are exposed. Tests inject a mock implementation to avoid\n * spawning a real git process.\n */\nexport interface GitInvoker {\n /**\n * Run `git <args>` with `cwd` as the working directory. Must return\n * `{ stdout, exitCode }` with `stdout` trimmed by the caller as needed.\n * Implementations should NOT throw for non-zero exit codes — they should\n * return the exit code so the resolver can decide how to recover.\n */\n (cwd: string, args: string[]): { stdout: string; exitCode: number };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Default git invoker — spawns real `git` via the shared child-process helper\n// ──────────────────────────────────────────────────────────────────────────\n\nconst DEFAULT_GIT_TIMEOUT_MS = 2_000;\n\nexport function defaultGitInvoker(): GitInvoker {\n return (cwd: string, args: string[]) => {\n const result = launchProcessSync(\"git\", args, {\n cwd,\n encoding: \"utf-8\",\n timeout: DEFAULT_GIT_TIMEOUT_MS,\n shell: false,\n });\n if (result.error) {\n // Spawn failure (git not on PATH, timeout, etc.). Surface as non-zero.\n return { stdout: \"\", exitCode: 127 };\n }\n return {\n stdout: typeof result.stdout === \"string\" ? result.stdout : \"\",\n exitCode: typeof result.status === \"number\" ? result.status : 1,\n };\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Stable hashing\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Non-cryptographic stable hash. Used only to derive a deterministic\n * `projectId` from either the origin URL or the root path. The hash does not\n * need to be collision-resistant against adversarial input — it is purely a\n * namespace discriminator.\n *\n * Uses FNV-1a 32-bit so we don't pull in `node:crypto` for a simple bucket\n * key. Output is lowercase hex, zero-padded to 8 characters.\n */\nexport function stableHash(input: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Origin URL normalization\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a git remote URL so that equivalent SSH / HTTPS forms of the\n * same repo produce the same `projectId`. Handles:\n * - `git@github.com:foo/bar.git` → `github.com/foo/bar`\n * - `https://github.com/foo/bar` → `github.com/foo/bar`\n * - `https://github.com/foo/bar.git` → `github.com/foo/bar`\n * - `ssh://git@github.com/foo/bar` → `github.com/foo/bar`\n * - `ssh://git@github.com:2222/foo/bar` → `github.com/foo/bar` (port stripped)\n *\n * Case-insensitive (remote hostnames and most repo paths on major forges are\n * case-insensitive in practice).\n */\nexport function normalizeOriginUrl(rawUrl: string): string {\n let url = rawUrl.trim();\n if (!url) return \"\";\n\n // Strip trailing `.git` case-insensitively — the whole result is\n // lowercased at the end, so `.GIT` / `.Git` must be treated the same as\n // `.git`. Previously the `.endsWith(\".git\")` check let `.GIT` leak\n // through and appear in the output.\n if (/\\.git$/i.test(url)) url = url.slice(0, -4);\n\n // Windows drive-letter local path (e.g. `C:/repos/app`): detect here\n // so the scp matcher below can accept single-character SSH host aliases\n // (`h:foo/bar` from `.ssh/config`). A drive letter is exactly one ASCII\n // letter followed by `:/` or `:\\`; SSH aliases never have a slash\n // immediately after the colon.\n if (/^[A-Za-z]:[\\\\/]/.test(url)) {\n return url.toLowerCase();\n }\n\n // Protocol-prefixed: ssh://, https://, http://, git://, file://\n // Must be tried FIRST so that scp-style detection below doesn't\n // incorrectly swallow an ssh:// URL that happens to contain `:port/`.\n //\n // Matches:\n // 1: host — bracketed IPv6 `[2001:db8::1]`, plain host with no `:` / `/`,\n // OR empty (for `file:///path` which has no host component).\n // 2: port (optional) — preserved in the output so two repos on the same\n // host under different ports get distinct project namespaces.\n // Losing the port risked false-coalescing separate repos on custom\n // SSH mesh setups.\n // 3: path (optional)\n const protoMatch =\n /^[a-z][a-z0-9+.-]*:\\/\\/(?:[^@/]+@)?(\\[[^\\]]+\\]|[^/:]*)(?::(\\d+))?(\\/.*)?$/i.exec(url);\n if (protoMatch) {\n let host = protoMatch[1] ?? \"\";\n // Detect IPv6 via the bracketed input form BEFORE stripping brackets,\n // so that when we later re-attach a port we can preserve the\n // `[host]:port` boundary. Without the brackets, `host:2222` is\n // ambiguous with a longer bare IPv6 address like `2001:db8::1:2222`.\n const wasBracketed =\n host.startsWith(\"[\") && host.endsWith(\"]\");\n if (wasBracketed) host = host.slice(1, -1);\n const port = protoMatch[2];\n const repoPath = (protoMatch[3] ?? \"\").replace(/^\\/+/, \"\");\n const hostPort = port\n ? wasBracketed\n ? `[${host}]:${port}`\n : `${host}:${port}`\n : host;\n // For protocols without a host component (file:///path), fall back to\n // a stable prefix so distinct local paths don't collapse to \"/path\".\n const prefix = hostPort.length > 0 ? hostPort : \"localhost\";\n return `${prefix}/${repoPath}`.toLowerCase();\n }\n\n // scp-like syntax: [user@]host:path. Protocol-prefixed URLs (`scheme://`)\n // are handled above, so the scp branch below guards against them: a\n // matched `host` of `scheme` followed by a path starting with `//` is\n // a protocol URL that fell through and must NOT be parsed here.\n // `user@` is optional — git also accepts userless scp forms like\n // `host:org/repo`. Valid scp paths may start with digits (e.g.\n // `git@host:123/repo.git`), so no numeric guard is needed: port-bearing\n // URLs have the `://` prefix and match the protocol branch above before\n // reaching here.\n //\n // Windows drive letters were filtered above, so single-character SSH\n // host aliases (`h:foo/bar`) are accepted here.\n //\n // Bracketed IPv6 (`[2001:db8::1]`) is supported: the host alternative\n // matches the bracketed literal up to `]` without splitting on internal\n // `:`. Brackets are stripped in the normalised form so the scp and\n // `ssh://` forms of the same IPv6 remote produce identical projectIds.\n const scpMatch =\n /^(?:([^@\\s/]+)@)?(\\[[^\\]]+\\]|[^:@\\s/]+):(.+)$/.exec(url);\n if (scpMatch) {\n let host = scpMatch[2] ?? \"\";\n if (host.startsWith(\"[\") && host.endsWith(\"]\")) host = host.slice(1, -1);\n const repoPath = scpMatch[3] ?? \"\";\n // Reject protocol-like leftovers (e.g. `file:///path` where the scp\n // regex greedily matched `file` as host and `///path` as path).\n if (repoPath.startsWith(\"//\")) {\n return url.toLowerCase();\n }\n return `${host}/${repoPath.replace(/^\\/+/, \"\")}`.toLowerCase();\n }\n\n // Fallback: use raw lowercased\n return url.toLowerCase();\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Resolver\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface ResolveGitContextOptions {\n /** Inject a git invoker (tests). Defaults to spawning real `git`. */\n invoker?: GitInvoker;\n}\n\n/**\n * Detect the git project + branch for `cwd`.\n *\n * Returns `null` when:\n * - `cwd` is not an absolute path (invalid input, CLAUDE.md #51)\n * - `cwd` is not inside a git worktree\n * - `git` is not available on PATH\n *\n * Never throws.\n */\nexport async function resolveGitContext(\n cwd: string,\n options: ResolveGitContextOptions = {},\n): Promise<GitContext | null> {\n // Wrap the whole body so the documented \"Never throws\" contract is\n // enforced. Possible throw sites include:\n // - `expandTildePath` → `resolveHomeDir()` → `os.homedir()` when HOME\n // is unset (e.g. minimal containers)\n // - a custom `options.invoker` that raises instead of returning a\n // non-zero exitCode\n // - any future helper added to this chain\n // All of those map to \"not in a repo\" / `null`.\n try {\n // Validate input: must be a non-empty string.\n if (typeof cwd !== \"string\" || cwd.length === 0) return null;\n\n // Expand `~` per CLAUDE.md #17, then require absolute path.\n const expanded = expandTildePath(cwd);\n if (!path.isAbsolute(expanded)) return null;\n\n const invoker = options.invoker ?? defaultGitInvoker();\n\n // 1. Locate the repo root.\n const topLevel = invoker(expanded, [\"rev-parse\", \"--show-toplevel\"]);\n if (topLevel.exitCode !== 0) return null;\n const rootPath = topLevel.stdout.trim();\n if (!rootPath) return null;\n\n // 2. Current branch. `--abbrev-ref HEAD` returns `HEAD` in detached\n // state, which we normalize to `null`. On a fresh `git init` the\n // HEAD ref is unborn and `--abbrev-ref HEAD` fails, but\n // `symbolic-ref HEAD` still returns the target branch. Fall back\n // so newly-initialized repos get a sensible branch name.\n const branchResult = invoker(rootPath, [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n let branch: string | null = null;\n if (branchResult.exitCode === 0) {\n const raw = branchResult.stdout.trim();\n branch = raw && raw !== \"HEAD\" ? raw : null;\n } else {\n const unbornRef = invoker(rootPath, [\"symbolic-ref\", \"--quiet\", \"HEAD\"]);\n if (unbornRef.exitCode === 0) {\n const raw = unbornRef.stdout.trim();\n const prefix = \"refs/heads/\";\n if (raw.startsWith(prefix)) {\n const candidate = raw.slice(prefix.length);\n if (candidate) branch = candidate;\n }\n }\n }\n\n // 3. Origin URL — optional. Used to derive a stable `projectId`.\n const originResult = invoker(rootPath, [\"remote\", \"get-url\", \"origin\"]);\n let projectId: string;\n if (originResult.exitCode === 0) {\n const normalized = normalizeOriginUrl(originResult.stdout);\n projectId = normalized ? `origin:${stableHash(normalized)}` : `root:${stableHash(rootPath)}`;\n } else {\n projectId = `root:${stableHash(rootPath)}`;\n }\n\n // 4. Default branch — best effort.\n const headRef = invoker(rootPath, [\"symbolic-ref\", \"--quiet\", \"refs/remotes/origin/HEAD\"]);\n let defaultBranch: string | null = null;\n if (headRef.exitCode === 0) {\n const raw = headRef.stdout.trim();\n const prefix = \"refs/remotes/origin/\";\n if (raw.startsWith(prefix)) {\n const candidate = raw.slice(prefix.length);\n if (candidate) defaultBranch = candidate;\n }\n }\n\n return {\n projectId,\n branch,\n rootPath,\n defaultBranch,\n };\n } catch {\n // Never throws — any unexpected error falls back to \"not in a repo\".\n return null;\n }\n}\n","/**\n * Coding-agent namespace overlay (issue #569 PR 2 + PR 3).\n *\n * Given a `CodingContext` (from `resolveGitContext`) and a `CodingModeConfig`,\n * returns the namespace that recall + write paths should use — or `null` when\n * no overlay should apply (coding mode disabled, no context supplied, or\n * feature flags off).\n *\n * PR 2 ships the project overlay. PR 3 will add the branch overlay; the\n * function here already handles both flags so the schema / types / plumbing\n * don't have to change a second time when branch-scope lands.\n *\n * Pure function — no orchestrator, no config side-effects. Callers keep rule\n * 42 (read + write through same namespace layer) by consulting the same\n * function on both paths.\n */\n\nimport type { CodingContext, CodingModeConfig } from \"../types.js\";\nimport { stableHash } from \"./git-context.js\";\n\nexport interface CodingNamespaceOverlay {\n /**\n * Effective namespace to use for this session's memory operations. When\n * `branchScope` is on, takes the form `project:<id>/branch:<b>`; otherwise\n * `project:<id>`.\n */\n namespace: string;\n /**\n * Read fallbacks — additional namespaces a caller should include in recall\n * so that, for example, a branch-scoped session still sees project-level\n * memories that were written before the branch scope was enabled.\n *\n * Writes MUST go to `namespace` only; these are read-side only.\n *\n * Introduced to carry PR 3's branch→project fallback; PR 2 returns an empty\n * array here.\n */\n readFallbacks: string[];\n /**\n * `\"project\"` when only project scope applies, `\"branch\"` when branch scope\n * is also layered on. Used for diagnostics (`remnic doctor`) and logging.\n */\n scope: \"project\" | \"branch\";\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Sanitization\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize a projectId / branch fragment so the resulting namespace passes\n * the router's `isSafeRouteNamespace` check (`[A-Za-z0-9._-]{1,64}`).\n *\n * Namespaces are used as filesystem directory names and must not contain\n * path separators (`/`, `\\`) or colons — so both `:` and `/` collapse to `-`.\n * The project-id format `origin:<8hex>` and branch names like `feat/x` both\n * flow through this helper before hitting the storage layer.\n *\n * NOT a security boundary — projectIds come from `resolveGitContext` (known\n * hex), and branch names come from local git. This defends against corrupt\n * input only.\n */\n/**\n * Single-pass sanitization — each input character is visited exactly once.\n * Rewriting as an explicit loop (instead of chained `replace()` calls with\n * greedy quantifiers) closes the polynomial-backtracking surface that\n * CodeQL flagged on patterns like `-+` and `^-+|-+$`.\n */\nexport function sanitizeFragment(input: string): string {\n if (typeof input !== \"string\") return \"\";\n const trimmed = input.trim().toLowerCase();\n let out = \"\";\n let prevIsDash = true; // suppress leading dashes\n for (let i = 0; i < trimmed.length; i += 1) {\n const c = trimmed[i]!;\n const cc = trimmed.charCodeAt(i);\n const isSafe =\n (cc >= 48 && cc <= 57) /* 0-9 */ ||\n (cc >= 97 && cc <= 122) /* a-z */ ||\n cc === 46 /* . */ ||\n cc === 95 /* _ */;\n if (isSafe) {\n out += c;\n prevIsDash = false;\n } else if (!prevIsDash) {\n out += \"-\";\n prevIsDash = true;\n }\n }\n // Strip a single trailing dash introduced by the final run of unsafe chars.\n if (out.endsWith(\"-\")) out = out.slice(0, -1);\n return out;\n}\n\n/**\n * Cap to the router's per-namespace upper bound.\n *\n * Raw truncation alone would collapse distinct long inputs that differ near\n * the end (e.g. two `feat/...` branches with different suffixes) into the\n * same namespace — silently mixing recall/write state across branches or\n * projects. When truncation is needed, we append a short deterministic\n * hash suffix (`-<8hex>`) derived from the FULL pre-truncated value so\n * collisions only happen under true hash collisions, not simple prefix\n * overlap.\n *\n * The tail is trimmed to leave room for the separator and 8-char hash and\n * any trailing `-` introduced by the slice is stripped so the final\n * character before `-<hash>` is always alphanumeric or `.`/`_`.\n */\nconst MAX_NAMESPACE_LEN = 64;\nconst HASH_SUFFIX_LEN = 9; // \"-\" + 8 hex chars\n\nfunction capLength(value: string): string {\n if (value.length <= MAX_NAMESPACE_LEN) return value;\n // Reuse the FNV-1a 32-bit hash from git-context — one canonical\n // implementation, one set of edge-case fixes. Uses Math.imul for\n // correct 32-bit wrap-around, which plain `*` would not guarantee\n // for the largest intermediate products.\n const hash = stableHash(value);\n // Trim trailing '-' with a linear, non-backtracking loop. A regex\n // like `-+$` is linear too, but an explicit loop keeps CodeQL happy\n // about polynomial backtracking warnings when several `\\-+` patterns\n // appear in the same module.\n let end = MAX_NAMESPACE_LEN - HASH_SUFFIX_LEN;\n while (end > 0 && value.charCodeAt(end - 1) === 45 /* '-' */) end -= 1;\n return `${value.slice(0, end)}-${hash}`;\n}\n\n/**\n * Produce the project-scope namespace name. Exported for tests and for\n * `remnic doctor` to render. Guaranteed to satisfy `isSafeRouteNamespace`:\n * no `/`, no `:`, lowercase only, length-capped to 64 chars.\n */\nexport function projectNamespaceName(projectId: string): string {\n const frag = sanitizeFragment(projectId);\n return capLength(`project-${frag || \"unknown\"}`);\n}\n\nexport function projectTagProjectId(projectTag: string): string {\n const trimmed = projectTag.trim();\n const frag = sanitizeFragment(trimmed);\n const disambig = trimmed.length > 0 && frag !== trimmed;\n const suffix = disambig ? `-${stableHash(trimmed)}` : \"\";\n return `tag:${frag || \"unknown\"}${suffix}`;\n}\n\n/**\n * Preserve case when sanitizing a principal-derived base namespace. The\n * router's `isSafeRouteNamespace` check accepts `[A-Za-z0-9._-]{1,64}`, so\n * upper-case characters in the principal name are safe and MUST be kept to\n * avoid colliding two otherwise-distinct principals (e.g. `Alice` vs\n * `alice`) into the same combined namespace.\n *\n * Otherwise identical to `sanitizeFragment`: single-pass, linear, no\n * polynomial-backtracking quantifiers, unsafe chars collapse to `-` with\n * leading/trailing dashes suppressed.\n */\nfunction sanitizeBaseFragment(input: string): string {\n if (typeof input !== \"string\") return \"\";\n const trimmed = input.trim();\n let out = \"\";\n let prevIsDash = true;\n for (let i = 0; i < trimmed.length; i += 1) {\n const c = trimmed[i]!;\n const cc = trimmed.charCodeAt(i);\n const isSafe =\n (cc >= 48 && cc <= 57) /* 0-9 */ ||\n (cc >= 65 && cc <= 90) /* A-Z */ ||\n (cc >= 97 && cc <= 122) /* a-z */ ||\n cc === 46 /* . */ ||\n cc === 95 /* _ */;\n if (isSafe) {\n out += c;\n prevIsDash = false;\n } else if (!prevIsDash) {\n out += \"-\";\n prevIsDash = true;\n }\n }\n if (out.endsWith(\"-\")) out = out.slice(0, -1);\n return out;\n}\n\n/**\n * Combine a principal-derived base namespace (e.g. `default`, `alice`) with a\n * coding-agent overlay namespace (e.g. `project-origin-abcd1234`). The result\n * is a single safe-route token that preserves principal isolation (CLAUDE.md\n * rule 42: read + write must resolve through the same namespace layer — and\n * here, through the same principal-scoped prefix) while layering project or\n * project/branch scope on top.\n *\n * Multiple principals working in the same repo thus get distinct namespaces:\n *\n * alice + project-origin-ab12 → alice-project-origin-ab12\n * bob + project-origin-ab12 → bob-project-origin-ab12\n * Alice + project-origin-ab12 → Alice-project-origin-ab12 (distinct)\n *\n * The base fragment preserves case so `Alice` and `alice` remain distinct;\n * the overlay fragment is still lowercase-sanitized because it derives from\n * deterministic, pre-lowercased git hashes.\n *\n * Output is re-capped through `capLength` so a very long base + overlay\n * combination still fits inside `isSafeRouteNamespace` (≤ 64 chars). The\n * deterministic hash suffix on truncation keeps distinct inputs distinct.\n */\nexport function combineNamespaces(base: string, overlay: string): string {\n const baseFrag = sanitizeBaseFragment(base);\n const overlayFrag = sanitizeFragment(overlay);\n if (!baseFrag) return capLength(overlayFrag || \"unknown\");\n if (!overlayFrag) return capLength(baseFrag);\n return capLength(`${baseFrag}-${overlayFrag}`);\n}\n\n/**\n * Produce the branch-scope namespace name. Format:\n * `project-<id>-branch-<name>[-<hash>]`. Uses `-` as the structural separator\n * rather than `/` or `:` so the result is a single safe route-namespace\n * token that can be used directly as a filesystem directory.\n *\n * Two failure modes must not collapse distinct branches to one namespace:\n *\n * 1. Sanitization is lossy (`feat/x` and `feat-x` both sanitize to\n * `feat-x`; `Feature` and `feature` both sanitize to `feature`). When\n * sanitization rewrote any character, we append a short hash of the\n * RAW branch so distinct inputs stay distinct.\n * 2. Truncation is applied when the total exceeds 64 chars. In that\n * mode `capLength` appends its own hash of the full pre-truncated\n * value.\n *\n * Long branches that also sanitize may receive both kinds of hashes — that\n * is acceptable: the router only requires the result be unique and\n * deterministic, and the two hashes derive from different domains so they\n * don't conflict.\n */\nexport function branchNamespaceName(projectId: string, branch: string): string {\n const projectFrag = sanitizeFragment(projectId);\n const trimmedBranch = branch.trim();\n const branchFrag = sanitizeFragment(trimmedBranch);\n // Lossy-sanitization disambiguator: append hash of the raw (trimmed)\n // branch when sanitization actually changed the string. Preserves\n // distinctness across `feat/x` vs `feat-x` and `Feature` vs `feature`.\n // The comparison uses the raw trimmed value (NOT `.toLowerCase()`) so\n // case-only variants are treated as lossy and receive their own hash.\n // Empty / already-safe-lowercase inputs get no hash so the common case\n // stays readable.\n const disambig = trimmedBranch.length > 0 && branchFrag !== trimmedBranch;\n const base = `project-${projectFrag || \"unknown\"}-branch-${branchFrag || \"unknown\"}`;\n const suffixed = disambig ? `${base}-${stableHash(trimmedBranch)}` : base;\n return capLength(suffixed);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Overlay resolver\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Compute the namespace overlay for a session.\n *\n * Returns `null` when no overlay applies — callers should then use their\n * existing `defaultNamespaceForPrincipal(...)` result unchanged. This keeps\n * CLAUDE.md #30 (escape hatch): setting `codingMode.projectScope: false`\n * exactly restores pre-#569 behaviour at every call site.\n *\n * @param codingContext — git context from the connector\n * @param config — coding mode flags (projectScope, branchScope, globalFallback)\n * @param defaultNamespace — retained for call-site compatibility; no longer\n * used. The global fallback is expressed as an empty-string sentinel in\n * `readFallbacks`, which `combineNamespaces(principal, \"\")` resolves to the\n * principal's own namespace at the call site.\n */\nexport function resolveCodingNamespaceOverlay(\n codingContext: CodingContext | null | undefined,\n config: Pick<CodingModeConfig, \"projectScope\" | \"branchScope\" | \"globalFallback\">,\n defaultNamespace?: string,\n): CodingNamespaceOverlay | null {\n // No context supplied (session isn't in a git repo, or connector didn't\n // attach one) → no overlay.\n if (!codingContext) return null;\n\n // Project scope disabled → no overlay at all. Branch scope depends on\n // project scope being on; there is no branch-only mode.\n if (!config.projectScope) return null;\n\n // Require a non-empty projectId — defensive.\n const projectId = typeof codingContext.projectId === \"string\" ? codingContext.projectId.trim() : \"\";\n if (!projectId) return null;\n\n const projectNs = projectNamespaceName(projectId);\n\n // Root/global namespace fallback: when `globalFallback` is true, include\n // the principal's self namespace in readFallbacks so cross-project knowledge\n // remains visible. CLAUDE.md #30: the gate is `globalFallback` — set to\n // false for strict project isolation.\n //\n // The fallback value is \"\" (empty string), NOT the defaultNamespace name.\n // The orchestrator passes each fallback through combineNamespaces(principal, fallback),\n // and combineNamespaces(base, \"\") returns base unchanged — yielding the\n // principal's own namespace. Using the actual namespace name (e.g., \"default\")\n // would produce \"default-default\" after combination, missing the target.\n const includeRoot = config.globalFallback === true;\n\n // Branch-scope layering (PR 3):\n // - only when config.branchScope is explicitly true\n // - only when we actually have a branch (null in detached HEAD)\n // - project namespace becomes a read fallback so project-level memories\n // remain visible from any branch (deliberate asymmetry — branch writes\n // don't leak up, but project reads leak down).\n // - when globalFallback is on, the root namespace is also appended so\n // globally useful memories surface in every branch.\n if (config.branchScope && typeof codingContext.branch === \"string\" && codingContext.branch.length > 0) {\n const branchNs = branchNamespaceName(projectId, codingContext.branch);\n const fallbacks = [projectNs];\n if (includeRoot) fallbacks.push(\"\");\n return {\n namespace: branchNs,\n readFallbacks: fallbacks,\n scope: \"branch\",\n };\n }\n\n return {\n namespace: projectNs,\n readFallbacks: includeRoot ? [\"\"] : [],\n scope: \"project\",\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Diagnostics (issue #569 PR 3 + PR 8)\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface CodingScopeDescription {\n /** \"none\" when no overlay is active; otherwise the resolved scope level. */\n scope: \"none\" | \"project\" | \"branch\";\n /** Project id (raw, not sanitized) when a context is attached. */\n projectId: string | null;\n /** Branch name (raw, not sanitized) when available. */\n branch: string | null;\n /** Effective namespace writes route to. `null` when no overlay applies. */\n effectiveNamespace: string | null;\n /** Read fallbacks included in recall (non-empty only when branch-scope is on). */\n readFallbacks: string[];\n /**\n * Why no overlay applies, when `scope === \"none\"`. One of:\n * - `\"no-context\"` — connector didn't attach a CodingContext\n * - `\"disabled\"` — codingMode.projectScope is false\n * - `\"empty-project\"` — codingContext.projectId was empty/whitespace\n */\n disabledReason: \"no-context\" | \"disabled\" | \"empty-project\" | null;\n}\n\n/**\n * Human-readable description of the coding-agent scope that currently applies\n * for a session. Consumed by `remnic doctor` (PR 8) and by logs to surface\n * why recall routes where it does.\n *\n * Pure — callers pass the coding context + config they already have.\n */\nexport function describeCodingScope(\n codingContext: CodingContext | null | undefined,\n config: Pick<CodingModeConfig, \"projectScope\" | \"branchScope\" | \"globalFallback\">,\n defaultNamespace?: string,\n): CodingScopeDescription {\n const projectId = codingContext?.projectId ?? null;\n const branch = codingContext?.branch ?? null;\n\n if (!codingContext) {\n return {\n scope: \"none\",\n projectId: null,\n branch: null,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"no-context\",\n };\n }\n if (!config.projectScope) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"disabled\",\n };\n }\n const trimmedId = typeof projectId === \"string\" ? projectId.trim() : \"\";\n if (!trimmedId) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"empty-project\",\n };\n }\n\n const overlay = resolveCodingNamespaceOverlay(codingContext, config, defaultNamespace);\n // Unreachable in practice given the guards above, but keep the return\n // shape consistent if the resolver grows new null branches later.\n if (!overlay) {\n return {\n scope: \"none\",\n projectId,\n branch,\n effectiveNamespace: null,\n readFallbacks: [],\n disabledReason: \"disabled\",\n };\n }\n return {\n scope: overlay.scope,\n projectId,\n branch,\n effectiveNamespace: overlay.namespace,\n readFallbacks: overlay.readFallbacks,\n disabledReason: null,\n };\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// LCM session-key namespacing (#1495)\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Reserved structural sentinel for the namespaced LCM `session_id` encoding\n * (#1495 P1). U+001F (UNIT SEPARATOR) is a C0 control character that CANNOT\n * occur in a route namespace (`isSafeRouteNamespace` ⇒ `[A-Za-z0-9._-]{1,64}`,\n * see routing/engine.ts) and does not occur in any legitimate session key, so\n * it is an unforgeable structural marker for the namespace boundary.\n *\n * SECURITY — why this is unforgeable (the #1495 P1 fix):\n * The LCM archive is keyed by the `session_id` STRING (exact `session_id = ?`\n * and prefix `session_id LIKE '<prefix>%'`), NOT physically partitioned by\n * namespace. The previous encoding `${namespace}:${sessionKey}` shared the SAME\n * string space as a raw default-store key, so a caller authorized for the\n * `default` store could pass a raw `sessionKey` equal to another namespace's\n * encoded key (`\"<overlay-ns>:<victim-session>\"`) and exact-match the victim's\n * rows — a cross-tenant read leak.\n *\n * The new encoding makes the namespaced and default key-spaces PROVABLY\n * DISJOINT:\n * - Overlay key = `\\x1f<namespace>\\x1f<sessionKey>` — always begins with\n * `\\x1f` followed by a NON-`\\x1f` character (the namespace is non-empty and\n * `\\x1f`-free). The leading `\\x1f<namespace>\\x1f` is an unambiguous,\n * injective frame: the namespace cannot contain `\\x1f`, so the second `\\x1f`\n * terminates it without any escaping of the (raw) session key.\n * - Default key = the raw `sessionKey`, UNLESS it already begins with the\n * sentinel, in which case it is escaped to begin with `\\x1f\\x1f` (see\n * `escapeDefaultLcmKey`). A default key therefore NEVER matches the overlay\n * frame `\\x1f<non-\\x1f>…`.\n * Hence no caller-controlled raw `sessionKey` (default path) can reproduce an\n * overlay key, closing the forgery for BOTH the exact-`session_id` match and the\n * `sessionPrefix` LIKE match (an overlay prefix `\\x1f<ns>\\x1f<rawPrefix>` stays a\n * valid LIKE-prefix of the overlay full keys, and a default prefix can only\n * LIKE-match default keys).\n *\n * Existing default-store rows need NO migration: legitimate session keys never\n * contain `\\x1f`, so `escapeDefaultLcmKey` is a no-op for them and they remain\n * byte-for-byte their raw form. The namespaced encoding is NEW in this\n * unreleased PR, so changing its shape costs nothing.\n */\nconst LCM_NS_SENTINEL = \"\\u001f\";\n\n/**\n * Make a default-store (raw) LCM key disjoint from the namespaced key-space.\n *\n * Namespaced overlay keys always begin with `\\x1f` followed by a non-`\\x1f`\n * namespace character. A raw default key collides with that frame ONLY if it\n * begins with `\\x1f`. Legitimate session keys never contain `\\x1f`, so this is a\n * pure no-op for them; a forged key that begins with `\\x1f` is escaped to begin\n * with `\\x1f\\x1f`, which can never equal an overlay key (whose second character\n * is a `[A-Za-z0-9._-]` namespace char, never `\\x1f`).\n */\nfunction escapeDefaultLcmKey(sessionKey: string): string {\n return sessionKey.startsWith(LCM_NS_SENTINEL)\n ? `${LCM_NS_SENTINEL}${sessionKey}`\n : sessionKey;\n}\n\n/**\n * Build the LCM/structured-history `session_id` that a write-producing surface\n * archives under, and that a same-session reader must search under, so reads\n * and writes never drift (#1495, CLAUDE.md rule 42).\n *\n * The LCM archive filters strictly by the `session_id` string, so the writer's\n * archival key and the reader's lookup key MUST agree byte-for-byte. The\n * encoding frames the namespace with the reserved {@link LCM_NS_SENTINEL}\n * (`\\x1f<namespace>\\x1f<sessionKey>`) whenever that namespace diverges from the\n * single-store default; otherwise it passes the (escaped) raw `sessionKey` so\n * single-user / no-overlay deployments keep pre-#1495 behavior exactly. The two\n * key-spaces are provably disjoint, so a caller-controlled raw `sessionKey`\n * cannot forge another namespace's encoded id (see the {@link LCM_NS_SENTINEL}\n * doc comment for the full security rationale).\n *\n * `observe`, compaction flush/record, and the orchestrator recall readers all\n * route through this one helper so a project-scoped (cwd/projectTag) or\n * explicit-namespace session reads its own compressed-history / structured /\n * targeted-fact evidence instead of missing it.\n */\nexport function lcmSessionKeyForNamespace(\n namespace: string | undefined,\n sessionKey: string | undefined,\n defaultNamespace: string,\n): string | undefined {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return sessionKey;\n if (\n typeof namespace === \"string\" &&\n namespace.length > 0 &&\n namespace !== defaultNamespace\n ) {\n // Namespaced (overlay / explicit) key: frame the namespace with the reserved\n // sentinel so the boundary is unambiguous AND unforgeable from the default\n // key-space. The namespace is guaranteed `\\x1f`-free by `isSafeRouteNamespace`.\n return `${LCM_NS_SENTINEL}${namespace}${LCM_NS_SENTINEL}${sessionKey}`;\n }\n // Default store: raw sessionKey, escaped only if it would otherwise intrude on\n // the namespaced key-space (no-op for every legitimate key).\n return escapeDefaultLcmKey(sessionKey);\n}\n\n/**\n * Map an ORDERED, read-authorized namespace set (the SAME set normal QMD/file\n * recall searches) to the ordered set of LCM `session_id`s a same-session reader\n * must query (#1505 thread \"Include coding fallback namespaces in LCM reads\").\n *\n * The LCM archive filters strictly by `session_id`, and `observe` archives each\n * turn under `${effectiveNamespace}:${sessionKey}` for the namespace that was\n * effective when it was written. A branch-scoped session that overlays\n * `${base-project-*-branch-*}` only sees rows written under THAT namespace if it\n * reads a single overlay key — but normal recall ALSO searches the\n * `codingOverlay.readFallbacks` (project / root) namespaces, so rows archived at\n * project/root scope are surfaced by QMD/file recall yet MISSED by a single-key\n * LCM read. Deriving the LCM read keys from the SAME `recallNamespaces` set keeps\n * the LCM read path from diverging: every namespace recall is authorized to read\n * (read-auth gate already applied upstream in `recallNamespaces`) contributes one\n * LCM key, ordered primary-overlay-first then fallbacks. Unreadable namespaces\n * are never in `recallNamespaces`, so they are never searched here either (no\n * cross-tenant read leak).\n *\n * Single-user / no-overlay recall passes a single-namespace set that collapses to\n * the raw `sessionKey`, so the result is `[sessionKey]` — byte-for-byte the\n * pre-#1505 single-key behavior.\n *\n * SESSIONLESS recall (`sessionKey === undefined`): returns `[undefined]` so the\n * caller issues ONE archive-wide LCM read with no exact `session_id` filter —\n * byte-for-byte the pre-#1505 sessionless behavior. It must NOT substitute the\n * literal `\"default\"` session id (codex P2 \"Preserve unscoped LCM searches\n * without a session key\"): that would filter to a session literally named\n * `default`, silently dropping the explicit-cue / targeted / focused / response /\n * event LCM sections for every recall that omits a session key.\n *\n * The result is deduped while preserving first-seen order so the caller can query\n * keys in priority order and short-circuit on the first hit without re-querying an\n * identical key (e.g. when two namespaces both collapse to the default store).\n */\nexport function lcmReadSessionIdsForNamespaces(\n namespaces: readonly string[],\n sessionKey: string | undefined,\n defaultNamespace: string,\n): Array<string | undefined> {\n // Sessionless ⇒ a single archive-wide read (no `session_id` filter). NEVER the\n // literal \"default\" session id (codex P2).\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) {\n return [undefined];\n }\n const out: string[] = [];\n const seen = new Set<string>();\n for (const namespace of namespaces) {\n const key =\n lcmSessionKeyForNamespace(namespace, sessionKey, defaultNamespace) ??\n sessionKey;\n if (!seen.has(key)) {\n seen.add(key);\n out.push(key);\n }\n }\n return out;\n}\n","import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport { createHash } from \"node:crypto\";\n\nimport { combineNamespaces, type CodingNamespaceOverlay } from \"../coding/coding-namespace.js\";\nimport { stableHash } from \"../coding/git-context.js\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport type {\n CodingContext,\n PluginConfig,\n ScopeProfileConfig,\n ScopeProfileLayerId,\n ScopeProfilePromotionTarget,\n ScopeTeamConfig,\n} from \"../types.js\";\nimport { canReadNamespace, canWriteNamespace, defaultNamespaceForPrincipal } from \"./principal.js\";\n\ntype ScopeProfileCodingOverlay = Pick<CodingNamespaceOverlay, \"namespace\" | \"readFallbacks\">;\n\nexport interface ScopeProfileLayerResolution {\n id: ScopeProfileLayerId;\n kind: \"user-project\" | \"team-project\" | \"user-global\" | \"server-shared\";\n namespace?: string;\n readable: boolean;\n writable: boolean;\n promotable: boolean;\n reason: string;\n}\n\nexport interface ScopeProfilePromotionResolution {\n target: ScopeProfilePromotionTarget;\n namespace?: string;\n authorized: boolean;\n reason: string;\n}\n\nexport interface ResolvedScopeProfilePlan {\n profileId: string;\n profile: ScopeProfileConfig;\n baseNamespace: string;\n writeLayer: ScopeProfileLayerId;\n writeNamespace: string;\n readNamespaces: string[];\n layers: ScopeProfileLayerResolution[];\n promotionTargets: ScopeProfilePromotionResolution[];\n warnings: string[];\n}\n\nexport interface ResolveScopeProfilePlanOptions {\n config: PluginConfig;\n principal?: string;\n codingContext?: CodingContext | null;\n codingOverlay?: ScopeProfileCodingOverlay | null;\n}\n\nfunction activeScopeProfile(config: PluginConfig): { profileId: string; profile: ScopeProfileConfig } | null {\n const profileId = config.defaultScopeProfile;\n if (!profileId) return null;\n const profile = (config.scopeProfiles ?? {})[profileId];\n return profile ? { profileId, profile } : null;\n}\n\nfunction principalListed(list: string[], principal: string | undefined): boolean {\n if (!principal) return false;\n return list.includes(principal) || list.includes(\"*\");\n}\n\nfunction derivedScopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string | null {\n if (!principal || principal === config.defaultNamespace || principal === config.sharedNamespace) return null;\n if (isSafeRouteNamespace(principal)) return principal;\n return \"principal-\" + createHash(\"sha256\").update(principal).digest(\"hex\").slice(0, 54);\n}\n\nfunction scopeProfileSelfNamespace(principal: string | undefined, config: PluginConfig): string {\n const existing = defaultNamespaceForPrincipal(principal, config);\n if (existing !== config.defaultNamespace) return existing;\n return derivedScopeProfileSelfNamespace(principal, config) ?? existing;\n}\n\nfunction hasExplicitNamespacePolicy(namespace: string, config: PluginConfig): boolean {\n return (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);\n}\n\nfunction isScopeProfileImplicitSelfNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n const derived = derivedScopeProfileSelfNamespace(principal, config);\n return Boolean(\n derived &&\n namespace === derived &&\n namespace !== config.defaultNamespace &&\n namespace !== config.sharedNamespace &&\n isSafeRouteNamespace(namespace) &&\n !hasExplicitNamespacePolicy(namespace, config),\n );\n}\n\nfunction canReadScopeProfileNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n return isScopeProfileImplicitSelfNamespace(principal, namespace, config) || canReadNamespace(principal, namespace, config);\n}\n\nfunction canWriteScopeProfileNamespace(\n principal: string | undefined,\n namespace: string,\n config: PluginConfig,\n): boolean {\n return isScopeProfileImplicitSelfNamespace(principal, namespace, config) || canWriteNamespace(principal, namespace, config);\n}\n\nfunction resolveTeam(\n config: PluginConfig,\n profile: ScopeProfileConfig,\n principal: string | undefined,\n): { teamId: string; team: ScopeTeamConfig } | null {\n const configuredTeamId = profile.teamProject?.teamId;\n if (configuredTeamId) {\n const configured = (config.teams ?? {})[configuredTeamId];\n return configured ? { teamId: configuredTeamId, team: configured } : null;\n }\n const readableTeams = Object.entries(config.teams ?? {}).filter(([, team]) =>\n principalListed(team.principals, principal) || principalListed(team.read, principal),\n );\n const needsWritableTeam = profile.writeDefault === \"teamProject\" || profile.readOrder.includes(\"teamProject\");\n if (needsWritableTeam) {\n const writableTeam = readableTeams.find(([, team]) => principalListed(team.write, principal));\n if (writableTeam) return { teamId: writableTeam[0], team: writableTeam[1] };\n }\n const needsPromotableTeam =\n profile.promotionTargets.includes(\"teamProject\") || profile.autoPromote.targets.includes(\"teamProject\");\n if (needsPromotableTeam) {\n const promotableTeam = readableTeams.find(\n ([, team]) => principalListed(team.promote, principal) || principalListed(team.write, principal),\n );\n if (promotableTeam) return { teamId: promotableTeam[0], team: promotableTeam[1] };\n }\n const firstReadableTeam = readableTeams[0];\n return firstReadableTeam\n ? { teamId: firstReadableTeam[0], team: firstReadableTeam[1] }\n : null;\n}\n\nfunction renderTeamProjectNamespace(params: {\n template: string;\n teamId: string;\n principal: string | undefined;\n codingContext: CodingContext;\n codingOverlay: ScopeProfileCodingOverlay;\n}): { namespace: string; unknownPlaceholders: string[] } {\n const replacements: Record<string, string> = {\n teamId: params.teamId,\n principal: params.principal ?? \"anonymous\",\n projectId: params.codingContext.projectId,\n projectHash: stableHash(params.codingContext.projectId),\n projectNamespace: params.codingOverlay.namespace,\n };\n const unknownPlaceholders: string[] = [];\n const namespace = params.template.replace(/\\{([A-Za-z][A-Za-z0-9]*)\\}/g, (match, key: string) => {\n const replacement = replacements[key];\n if (replacement !== undefined) return replacement;\n if (!unknownPlaceholders.includes(key)) unknownPlaceholders.push(key);\n return match;\n });\n return { namespace, unknownPlaceholders };\n}\n\nfunction resolveLayer(params: {\n id: ScopeProfileLayerId;\n config: PluginConfig;\n profile: ScopeProfileConfig;\n principal: string | undefined;\n baseNamespace: string;\n codingContext: CodingContext | null | undefined;\n codingOverlay: ScopeProfileCodingOverlay | null | undefined;\n}): ScopeProfileLayerResolution {\n const { id, config, profile, principal, baseNamespace, codingContext, codingOverlay } = params;\n if (id === \"userGlobal\") {\n return {\n id,\n kind: \"user-global\",\n namespace: baseNamespace,\n readable: canReadScopeProfileNamespace(principal, baseNamespace, config),\n writable: canWriteScopeProfileNamespace(principal, baseNamespace, config),\n promotable: canWriteScopeProfileNamespace(principal, baseNamespace, config),\n reason: \"principal self/global namespace\",\n };\n }\n if (id === \"serverShared\") {\n return {\n id,\n kind: \"server-shared\",\n namespace: config.sharedNamespace,\n readable: canReadNamespace(principal, config.sharedNamespace, config),\n writable: canWriteNamespace(principal, config.sharedNamespace, config),\n promotable: canWriteNamespace(principal, config.sharedNamespace, config),\n reason: \"configured shared namespace\",\n };\n }\n if (id === \"userProject\") {\n if (!codingContext || !codingOverlay) {\n return {\n id,\n kind: \"user-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"missing project context\",\n };\n }\n const namespace = combineNamespaces(baseNamespace, codingOverlay.namespace);\n const explicitProjectPolicy = hasExplicitNamespacePolicy(namespace, config);\n const baseReadable = canReadScopeProfileNamespace(principal, baseNamespace, config);\n const baseWritable = canWriteScopeProfileNamespace(principal, baseNamespace, config);\n const projectReadable = explicitProjectPolicy\n ? canReadNamespace(principal, namespace, config)\n : baseReadable;\n const projectWritable = explicitProjectPolicy\n ? canWriteNamespace(principal, namespace, config)\n : baseWritable;\n return {\n id,\n kind: \"user-project\",\n namespace,\n readable: projectReadable,\n writable: projectWritable,\n promotable: projectWritable,\n reason: explicitProjectPolicy\n ? \"explicit user-project namespace policy\"\n : baseReadable || baseWritable\n ? \"principal project namespace derived from coding context\"\n : \"principal base namespace is not authorized\",\n };\n }\n const team = resolveTeam(config, profile, principal);\n if (!team) {\n return {\n id,\n kind: \"team-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"no authorized team mapping\",\n };\n }\n if (!codingContext || !codingOverlay) {\n return {\n id,\n kind: \"team-project\",\n readable: false,\n writable: false,\n promotable: false,\n reason: \"missing project context\",\n };\n }\n const template =\n profile.teamProject?.namespaceTemplate ??\n team.team.projectNamespaceTemplate ??\n \"team-{teamId}-project-{projectHash}\";\n const renderedNamespace = renderTeamProjectNamespace({\n template,\n teamId: team.teamId,\n principal,\n codingContext,\n codingOverlay,\n });\n const namespace = renderedNamespace.namespace.trim();\n if (renderedNamespace.unknownPlaceholders.length > 0) {\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: false,\n writable: false,\n promotable: false,\n reason: `unknown team-project namespace template placeholder(s): ${renderedNamespace.unknownPlaceholders.join(\", \")}`,\n };\n }\n if (!namespace || !isSafeRouteNamespace(namespace)) {\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: false,\n writable: false,\n promotable: false,\n reason: \"team-project namespace template resolved to an unsafe namespace\",\n };\n }\n const teamReadable = principalListed(team.team.read, principal) || principalListed(team.team.principals, principal);\n const teamWritable = principalListed(team.team.write, principal);\n const teamPromotable = principalListed(team.team.promote, principal) || principalListed(team.team.write, principal);\n const userProjectSuffix = `-${codingOverlay.namespace}`;\n const userProjectBase = namespace.endsWith(userProjectSuffix)\n ? namespace.slice(0, -userProjectSuffix.length)\n : \"\";\n const dynamicUserProjectCollision =\n userProjectBase.length > 0 &&\n (userProjectBase === config.defaultNamespace ||\n userProjectBase === config.sharedNamespace ||\n (config.namespacePolicies ?? []).some((policy) => policy.name === userProjectBase));\n const protectedNamespace =\n namespace === config.defaultNamespace ||\n namespace === config.sharedNamespace ||\n dynamicUserProjectCollision ||\n (config.namespacePolicies ?? []).some((policy) => policy.name === namespace);\n const policyReadable = !protectedNamespace || canReadNamespace(principal, namespace, config);\n const policyWritable = !protectedNamespace || canWriteNamespace(principal, namespace, config);\n const policyBlocked = protectedNamespace && (!policyReadable || !policyWritable);\n return {\n id,\n kind: \"team-project\",\n namespace,\n readable: teamReadable && policyReadable,\n writable: teamWritable && policyWritable,\n promotable: teamPromotable && policyWritable,\n reason: policyBlocked\n ? \"team-project namespace collides with a protected namespace policy\"\n : \"trusted team-project namespace derived from team and project config\",\n };\n}\n\nexport function resolveScopeProfilePlan(\n options: ResolveScopeProfilePlanOptions,\n): ResolvedScopeProfilePlan | null {\n const active = activeScopeProfile(options.config);\n if (!active || !resolveNamespaceCapabilities(options.config).namespaces) return null;\n\n const baseNamespace = scopeProfileSelfNamespace(options.principal, options.config);\n const layerIds = Array.from(\n new Set<ScopeProfileLayerId>([\n ...active.profile.readOrder,\n active.profile.writeDefault,\n \"userGlobal\",\n ...active.profile.promotionTargets.filter((target): target is ScopeProfileLayerId =>\n [\"userProject\", \"teamProject\", \"userGlobal\", \"serverShared\"].includes(target),\n ),\n ]),\n );\n const layerMap = new Map<ScopeProfileLayerId, ScopeProfileLayerResolution>();\n for (const id of layerIds) {\n layerMap.set(\n id,\n resolveLayer({\n id,\n config: options.config,\n profile: active.profile,\n principal: options.principal,\n baseNamespace,\n codingContext: options.codingContext,\n codingOverlay: options.codingOverlay,\n }),\n );\n }\n\n const readNamespaces: string[] = [];\n for (const id of active.profile.readOrder) {\n const layer = layerMap.get(id);\n if (layer?.readable && layer.namespace && !readNamespaces.includes(layer.namespace)) {\n readNamespaces.push(layer.namespace);\n }\n }\n\n const preferredWriteLayer = layerMap.get(active.profile.writeDefault);\n const readableWriteLayers = active.profile.readOrder\n .map((id) => layerMap.get(id))\n .filter(\n (layer): layer is ScopeProfileLayerResolution =>\n Boolean(layer?.writable && layer.namespace && readNamespaces.includes(layer.namespace)),\n );\n const fallbackWriteLayer =\n preferredWriteLayer?.writable &&\n preferredWriteLayer.namespace &&\n readNamespaces.includes(preferredWriteLayer.namespace)\n ? preferredWriteLayer\n : readableWriteLayers[0];\n const warnings: string[] = [];\n if (!fallbackWriteLayer?.namespace) {\n warnings.push(`scope profile ${active.profileId} has no writable layer inside the profile read stack; writes disabled`);\n } else if (fallbackWriteLayer.id !== active.profile.writeDefault) {\n warnings.push(\n `scope profile ${active.profileId} writeDefault ${active.profile.writeDefault} unavailable: ${preferredWriteLayer?.reason ?? \"not resolved\"}`,\n );\n }\n\n const promotionTargets = active.profile.promotionTargets.map((target) => {\n const layer = layerMap.get(target as ScopeProfileLayerId);\n if (!layer) {\n return {\n target,\n authorized: false,\n reason: \"promotion target did not resolve to a profile layer\",\n };\n }\n return {\n target,\n namespace: layer.namespace,\n authorized: layer.promotable && Boolean(layer.namespace),\n reason: layer.reason,\n };\n });\n\n return {\n profileId: active.profileId,\n profile: active.profile,\n baseNamespace,\n writeLayer: fallbackWriteLayer?.id ?? active.profile.writeDefault,\n writeNamespace: fallbackWriteLayer?.namespace ?? \"\",\n readNamespaces,\n layers: [...layerMap.values()],\n promotionTargets,\n warnings,\n };\n}\n\nexport function expandScopeProfileReadNamespaces(options: {\n profilePlan: ResolvedScopeProfilePlan;\n principalSelfNamespace: string;\n config: PluginConfig;\n principal?: string;\n codingOverlay?: ScopeProfileCodingOverlay | null;\n legacyRecallNamespaces?: string[];\n}): string[] {\n if (options.profilePlan.readNamespaces.length === 0) {\n return [];\n }\n const out = [...options.profilePlan.readNamespaces];\n const add = (namespace: string | undefined): void => {\n if (namespace && !out.includes(namespace)) out.push(namespace);\n };\n const userProjectReadable =\n options.profilePlan.profile.readOrder.includes(\"userProject\") &&\n options.profilePlan.layers.some(\n (layer) => layer.id === \"userProject\" && layer.readable && layer.namespace,\n );\n const userGlobalReadable =\n options.profilePlan.profile.readOrder.includes(\"userGlobal\") &&\n options.profilePlan.layers.some(\n (layer) => layer.id === \"userGlobal\" && layer.readable && layer.namespace,\n );\n if (userProjectReadable) {\n for (const fallback of options.codingOverlay?.readFallbacks ?? []) {\n if (fallback === \"\" && !userGlobalReadable) continue;\n const fallbackNamespace = combineNamespaces(options.principalSelfNamespace, fallback);\n if (\n !hasExplicitNamespacePolicy(fallbackNamespace, options.config) ||\n canReadScopeProfileNamespace(options.principal, fallbackNamespace, options.config)\n ) {\n add(fallbackNamespace);\n }\n }\n }\n return out;\n}\n","/**\n * ScopePlan resolver (issue #1521).\n *\n * A single pure function that resolves every namespace-bearing read/write path\n * to one {@link ScopePlan} value object. Consumers (recall tiers, QMD router,\n * LCM reads, maintenance) never call the ad-hoc resolution helpers directly —\n * they receive a resolved plan and read its fields.\n *\n * The resolver DELEGATES to the existing helpers (`resolvePrincipal`,\n * `recallNamespacesForPrincipal`, `resolveCodingNamespaceOverlay`,\n * `resolveScopeProfilePlan`, `expandScopeProfileReadNamespaces`,\n * `combineNamespaces`, `lcmReadSessionIdsForNamespaces`) — no logic rewrite.\n * The ad-hoc inline resolution that previously lived in the orchestrator's\n * `recallInternal` and `enqueueDirectAnswerObservation` paths is replaced by a\n * single call to {@link resolveScopePlan}, eliminating the duplicated\n * namespace-set construction that produced the largest share of #1519's review\n * threads (scope-profile recall paths missing `readFallbacks` appends).\n *\n * Migration tranches (issue #1521 step 4):\n * - recall tiers (this PR): the two orchestrator recall entry points consume\n * the plan instead of building `recallNamespaces`/`observationNamespaces`\n * inline;\n * - QMD router calls, LCM reads, maintenance: follow-up PRs.\n *\n * CLAUDE.md rules honoured (pitfalls from the issue):\n * - rule 42: read/write resolve through the same layer; the coding overlay is\n * COMBINED with the principal base via `combineNamespaces`;\n * - rule 39: feature gates identical across every path the plan feeds;\n * - rule 22/48: LCM keys derived through `lcmSessionKeyForNamespace` (via\n * `lcmReadSessionIdsForNamespaces`), never hardcoded `:`-joins; unscoped LCM\n * search stays suppressed when `namespacesEnabled`.\n */\n\nimport { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport {\n canReadNamespace,\n canWriteNamespace,\n defaultNamespaceForPrincipal,\n recallNamespacesForPrincipal,\n resolvePrincipal,\n} from \"../namespaces/principal.js\";\nimport {\n namespaceIdentityFromToken,\n namespaceIdentityToken,\n} from \"../namespaces/identity.js\";\nimport path from \"node:path\";\nimport type { ResolvedScopeProfilePlan } from \"../namespaces/scope-profiles.js\";\nimport {\n expandScopeProfileReadNamespaces,\n resolveScopeProfilePlan,\n} from \"../namespaces/scope-profiles.js\";\nimport {\n combineNamespaces,\n lcmReadSessionIdsForNamespaces,\n resolveCodingNamespaceOverlay,\n type CodingNamespaceOverlay,\n} from \"../coding/coding-namespace.js\";\nimport type { CodingContext, PluginConfig } from \"../types.js\";\n\n/**\n * A resolved scope plan: every namespace-bearing field a read or write path\n * needs, produced by ONE call to {@link resolveScopePlan}.\n *\n * Consumers read these fields directly — they never re-resolve namespaces.\n */\nexport interface ScopePlan {\n /**\n * Resolved principal under which the operation runs. `undefined` only when\n * `namespacesEnabled` is false (collapses to `\"default\"`) or no session key\n * was supplied in single-user mode.\n */\n readonly principal: string | undefined;\n\n /**\n * Explicit namespace override, trimmed, when the caller supplied one AND it\n * is readable by the principal. `undefined` when no override was given or the\n * override is not readable (the plan falls through to the coding/scope-profile\n * resolution in that case, mirroring the pre-existing observe-path behavior).\n */\n readonly namespaceOverride: string | undefined;\n\n /**\n * Resolved base (self) namespace — the effective namespace absent an explicit\n * override. This is the principal-self namespace, optionally substituted by a\n * scope-profile write layer or a coding overlay.\n *\n * Callers that persisted this as the `selfNamespace` / response namespace\n * read it here.\n */\n readonly baseNamespace: string;\n\n /**\n * Ordered, deduped read-namespace set. Includes the coding overlay fallbacks\n * (branch → project → root) combined with the principal base exactly once, so\n * the #1519 miss (scope-profile path omitted `readFallbacks` appends) cannot\n * recur — the fallback appends live in ONE place.\n */\n readonly readNamespaces: string[];\n\n /**\n * Coding overlay fallback namespaces combined with the principal base (rule\n * 42). Empty when no coding overlay applies. These are the SAME entries\n * appended into {@link readNamespaces} for the coding-overlay branch,\n * surfaced separately so consumers that need just the fallback set (e.g.\n * LCM read-key derivation) can read them without re-deriving.\n */\n readonly readFallbacks: string[];\n\n /**\n * LCM read namespace set. May differ from {@link readNamespaces} for\n * read-authorization reasons: when the principal self base is NOT in the\n * readable recall set, the overlay LCM keys collapse to the default store\n * (rule 42 read/write parity; rule 48 least-privilege) even though\n * {@link readNamespaces} still searches the overlay for QMD/file recall.\n */\n readonly lcmReadNamespaces: string[];\n\n /**\n * LCM read `session_id` set, encoded via\n * `lcmReadSessionIdsForNamespaces` (which delegates to\n * `lcmSessionKeyForNamespace`). Ordered and deduped; the primary overlay key\n * is first. Single-user / no-overlay recall collapses to `[sessionKey]` —\n * byte-for-byte the pre-#1495 behavior.\n *\n * Empty (`[]`) when a scope-profile plan is active and no `sessionKey` was\n * supplied (mirrors the pre-existing guard).\n */\n readonly lcmReadSessionIds: ReadonlyArray<string | undefined>;\n\n /**\n * Resolved coding overlay, or `null` when none applies (no coding context,\n * `codingMode.projectScope` false, `namespacesEnabled` false, or an explicit\n * readable namespace override is set).\n */\n readonly codingOverlay: { readonly namespace: string; readonly readFallbacks: readonly string[] } | null;\n\n /**\n * Resolved scope-profile plan, or `null` when no scope profile is active.\n * Consumers that branched on \"profile vs. non-profile\" read this directly.\n */\n readonly scopeProfilePlan: ResolvedScopeProfilePlan | null;\n}\n\n/**\n * Options for {@link resolveScopePlan}.\n */\nexport interface ResolveScopePlanOptions {\n /** Plugin config (namespace policies, coding mode, default namespace, …). */\n readonly config: PluginConfig;\n /** Session key (may derive the principal and/or coding context). */\n readonly sessionKey?: string;\n /**\n * Explicit namespace override (raw — the resolver trims it). When supplied\n * AND readable by the resolved principal, it wins over every other layer.\n */\n readonly namespace?: string;\n /**\n * Authenticated principal override. Access surfaces that already resolved\n * identity at the transport layer pass it here so namespace ACL decisions\n * use the same identity the surface authorized.\n */\n readonly principalOverride?: string;\n /**\n * Coding context for the session. Callers that track this on the orchestrator\n * pass `getCodingContextForSession(sessionKey)` here; the resolver never\n * reaches back into orchestrator state.\n */\n readonly codingContext?: CodingContext | null;\n /**\n * Whether namespace routing is enabled. Callers that have already read the\n * namespaces-enabled flag pass it here so the resolver does NOT re-read it\n * (keeps the scattered-read ratchet from growing, #1523).\n */\n readonly namespacesEnabled: boolean;\n}\n\n/**\n * Resolve a {@link ScopePlan} from the inputs by delegating to the existing\n * namespace-resolution helpers. Pure — no side effects, no orchestrator state.\n *\n * The caller is responsible for authorization checks that should THROW (e.g.\n * `namespacesEnabled && !principal`, or an unreadable explicit override in the\n * recall path). The resolver computes the plan; enforcement stays at the call\n * site so error semantics are unchanged.\n */\nexport function resolveScopePlan(options: ResolveScopePlanOptions): ScopePlan {\n const { config, sessionKey } = options;\n\n const namespaceOverride = options.namespace?.trim() || undefined;\n\n const principal =\n typeof options.principalOverride === \"string\" && options.principalOverride.length > 0\n ? options.principalOverride\n : resolvePrincipal(sessionKey, config);\n\n // A namespace override gates the overlay/scope-profile layers. When it is\n // readable it wins; when it is NOT readable the plan falls through to the\n // coding/scope-profile/legacy branches (mirrors the observe-path behavior\n // where an unreadable override does not throw but simply does not suppress\n // the overlay). The recall path validates readability and throws BEFORE\n // calling the resolver, so a reachable override is always readable there.\n const namespaceOverrideReadable =\n namespaceOverride !== undefined && canReadNamespace(principal, namespaceOverride, config);\n\n const readableRecallNamespaces = recallNamespacesForPrincipal(principal, config);\n\n // The orchestrator's `applyCodingRecallOverlay` gates on `namespacesEnabled`\n // (returning null when disabled), so the resolver must too — otherwise\n // single-store mode would produce apparent route separation with no actual\n // storage isolation (false-isolation trap, rule 39). The caller passes the\n // pre-read flag so the resolver does not add a scattered `config.*Enabled`\n // read (ratchet, #1523).\n const namespacesEnabled = options.namespacesEnabled;\n const codingOverlay: CodingNamespaceOverlay | null =\n namespaceOverrideReadable || !namespacesEnabled\n ? null\n : resolveCodingNamespaceOverlay(\n options.codingContext ?? null,\n config.codingMode,\n config.defaultNamespace,\n );\n\n const principalSelfNamespace = defaultNamespaceForPrincipal(principal, config);\n const codingSelfNamespace = codingOverlay\n ? combineNamespaces(principalSelfNamespace, codingOverlay.namespace)\n : null;\n\n const scopeProfilePlan = namespaceOverrideReadable\n ? null\n : resolveScopeProfilePlan({\n config,\n principal,\n codingContext: options.codingContext ?? null,\n codingOverlay,\n });\n\n const profileEffectiveNamespace =\n scopeProfilePlan?.writeNamespace || scopeProfilePlan?.readNamespaces[0];\n\n const baseNamespace = namespaceOverrideReadable\n ? namespaceOverride!\n : profileEffectiveNamespace ?? codingSelfNamespace ?? principalSelfNamespace;\n\n // ── Read namespace set ────────────────────────────────────────────────────\n let readNamespaces: string[];\n if (namespaceOverrideReadable) {\n readNamespaces = [namespaceOverride!];\n } else if (scopeProfilePlan) {\n readNamespaces = expandScopeProfileReadNamespaces({\n profilePlan: scopeProfilePlan,\n principalSelfNamespace: scopeProfilePlan.baseNamespace,\n config,\n principal,\n codingOverlay,\n legacyRecallNamespaces: readableRecallNamespaces,\n });\n } else if (codingOverlay && codingSelfNamespace) {\n // Substitute the principal's self namespace with the coding-scoped one, and\n // append any read fallbacks (branch → project, rule 42) combined with the\n // principal base so principal isolation is preserved on fallback entries.\n const mapped = readableRecallNamespaces.map((ns) =>\n ns === principalSelfNamespace ? codingSelfNamespace : ns,\n );\n const fallbackNs = codingOverlay.readFallbacks.map((fallback) =>\n combineNamespaces(principalSelfNamespace, fallback),\n );\n readNamespaces = Array.from(new Set<string>([...mapped, ...fallbackNs]));\n } else {\n readNamespaces = readableRecallNamespaces;\n }\n\n const readFallbacks = codingOverlay\n ? codingOverlay.readFallbacks.map((fb) => combineNamespaces(principalSelfNamespace, fb))\n : [];\n\n // ── LCM read namespace set ────────────────────────────────────────────────\n // The LCM overlay keys are `<principal>-project-*` sub-namespaces authorized\n // transitively by the principal SELF base. Include them ONLY when that base\n // is in the readable recall set (rule 42 / 48). When it is NOT readable, the\n // overlay rows are unauthorized for this reader, so the LCM read collapses to\n // the default store — exactly what QMD/file recall surfaces for such a\n // principal.\n const codingOverlaySelfReadable =\n codingOverlay !== null &&\n (scopeProfilePlan\n ? scopeProfilePlan.layers.some((layer) => layer.id === \"userProject\" && layer.readable)\n : readableRecallNamespaces.includes(principalSelfNamespace));\n\n let lcmReadNamespaces: string[];\n if (namespaceOverrideReadable) {\n lcmReadNamespaces = [namespaceOverride!];\n } else if (scopeProfilePlan) {\n // Scope profiles define a layered read stack; LCM-backed evidence uses the\n // same namespace set as QMD/file recall so team/global/shared observations\n // are not silently skipped.\n lcmReadNamespaces = readNamespaces;\n } else if (codingOverlay && codingSelfNamespace && codingOverlaySelfReadable) {\n const fallbackNs = codingOverlay.readFallbacks.map((fallback) =>\n combineNamespaces(principalSelfNamespace, fallback),\n );\n lcmReadNamespaces = [codingSelfNamespace, ...fallbackNs];\n } else {\n // No overlay, OR overlay present but self base unreadable → collapse to the\n // default store (raw sessionKey). No `<principal>-project-*` overlay key is\n // searched.\n lcmReadNamespaces = [config.defaultNamespace];\n }\n\n const lcmReadSessionIds =\n scopeProfilePlan && !sessionKey\n ? []\n : lcmReadSessionIdsForNamespaces(lcmReadNamespaces, sessionKey, config.defaultNamespace);\n\n return {\n principal,\n namespaceOverride: namespaceOverrideReadable ? namespaceOverride : undefined,\n baseNamespace,\n readNamespaces,\n readFallbacks,\n lcmReadNamespaces,\n lcmReadSessionIds,\n codingOverlay: codingOverlay\n ? { namespace: codingOverlay.namespace, readFallbacks: codingOverlay.readFallbacks }\n : null,\n scopeProfilePlan,\n };\n}\n\n// ────────────────────────────────────────────────────────────────────────────\n// Centralized namespace-resolution helpers (issue #1521 step 3–4)\n//\n// The three functions below consolidate the ad-hoc namespace-resolution logic\n// that was previously scattered across orchestrator.ts (namespaceFromStorageDir,\n// configuredNamespaces) and access-service.ts (resolveWritableNamespace). By\n// living in THIS module they are excluded from the adHocNamespaceResolutions\n// ratchet, and every consumer reaches them through a single well-known import\n// instead of reimplementing the derivation inline (#1519's failure mode).\n// ────────────────────────────────────────────────────────────────────────────\n\n/**\n * The configured namespace set: default + shared + every namespace-policy\n * name, trimmed and de-duplicated. Pure — reads only from `config`.\n *\n * Replaces the `configuredNamespaces()` private method that lived on both\n * `Orchestrator` and the maintenance namespace-planner (two copies of the\n * same logic).\n */\nexport function getConfiguredNamespaces(config: PluginConfig): string[] {\n return Array.from(\n new Set(\n [\n config.defaultNamespace,\n config.sharedNamespace,\n ...config.namespacePolicies.map((policy) => policy.name),\n ]\n .map((value) => value.trim())\n .filter(Boolean),\n ),\n );\n}\n\n/**\n * Options for {@link resolveNamespaceFromStorageDir}.\n */\nexport interface ResolveNamespaceFromStorageDirOptions {\n /** Plugin config (memoryDir, defaultNamespace, namespacesEnabled, …). */\n readonly config: PluginConfig;\n /**\n * Pre-computed configured-namespace set (from {@link getConfiguredNamespaces}).\n * Passed by the caller so this function does not re-derive it on every call.\n */\n readonly configuredNamespaces: readonly string[];\n /**\n * Catalog-owned dir→namespace hints (best-effort union of configured +\n * catalog-discovered). May be `undefined` when no catalog hints are loaded.\n */\n readonly hints?: ReadonlyMap<string, ReadonlySet<string>> | undefined;\n /**\n * Lazy catalog-hint loader. Called ONLY after the early returns (disabled,\n * memory root, no namespace segment, configured namespace) — matching the\n * original lazy behavior so an eager load does not mark hints as loaded\n * before the catalog file exists (codex P2).\n */\n readonly loadHints?: () => void;\n}\n\n/**\n * Derive the namespace a storage directory belongs to.\n *\n * Pure (no orchestrator state): the caller passes `config`, the configured set,\n * and any catalog hints. The logic is byte-identical to the private\n * `namespaceFromStorageDir` method that previously lived on `Orchestrator`\n * (including the token round-trip guard from codex round 6).\n */\nexport function resolveNamespaceFromStorageDir(\n storageDir: string,\n options: ResolveNamespaceFromStorageDirOptions,\n): string {\n const { config } = options;\n if (!resolveNamespaceCapabilities(config).namespaces) return config.defaultNamespace;\n const resolvedStorageDir = path.resolve(storageDir);\n const resolvedMemoryDir = path.resolve(config.memoryDir);\n if (resolvedStorageDir === resolvedMemoryDir) return config.defaultNamespace;\n const m = resolvedStorageDir.match(/[\\\\/]namespaces[\\\\/]([^\\\\/]+)$/);\n if (!m?.[1]) return config.defaultNamespace;\n const dirName = m[1];\n // Token-shaped raw names (codex P2 — NBsFz): a dir name might be a tokenized\n // identity OR a literal raw namespace name that merely LOOKS like a token.\n // A dir name that is itself a KNOWN namespace is preserved BEFORE decoding.\n if (options.configuredNamespaces.includes(dirName)) {\n return dirName;\n }\n // Load catalog hints ONLY after the early returns (codex P2: an eager load\n // before the catalog file exists would mark hints as loaded and skip later\n // catalog-derived rows).\n options.loadHints?.();\n const hints = options.hints;\n const hintedNamespaces = hints?.get(resolvedStorageDir);\n if (hintedNamespaces?.has(dirName)) {\n return dirName;\n }\n if (hintedNamespaces?.size === 1) {\n const [hintedNamespace] = hintedNamespaces;\n if (hintedNamespace) return hintedNamespace;\n }\n const decoded = namespaceIdentityFromToken(dirName);\n if (decoded && namespaceIdentityToken(decoded) === dirName) {\n return decoded;\n }\n return dirName;\n}\n\n/**\n * Result of resolving a writable namespace: either the authorized namespace\n * or a structured rejection. The caller decides how to surface the rejection\n * (e.g. as an `EngramAccessInputError` in the access-service layer), keeping\n * this module free of transport-specific error types.\n */\nexport type WritableNamespaceResult =\n | { readonly ok: true; readonly namespace: string }\n | { readonly ok: false; readonly reason: \"unsupported\" | \"not_writable\"; readonly namespace: string };\n\n/**\n * Resolve and authorize a writable namespace.\n *\n * Combines the three steps that `AccessService.resolveWritableNamespace`\n * performed inline: (1) resolve the namespace value (trim → default fallback →\n * validate against `namespacesEnabled`), (2) resolve the principal, (3) check\n * `canWriteNamespace`. Returns a structured result so this module stays free of\n * `EngramAccessInputError` (avoiding a circular dependency on access-service.ts).\n *\n * The caller throws `EngramAccessInputError` when `ok === false` — the access-\n * service wrapper does this in one place.\n */\nexport function resolveWritableNamespaceValue(\n namespace: string | undefined,\n sessionKey: string | undefined,\n authenticatedPrincipal: string | undefined,\n config: PluginConfig,\n): WritableNamespaceResult {\n const requested = namespace?.trim();\n let resolved: string;\n if (!requested) {\n resolved = config.defaultNamespace;\n } else if (\n !resolveNamespaceCapabilities(config).namespaces &&\n requested !== config.defaultNamespace\n ) {\n return { ok: false, reason: \"unsupported\", namespace: requested };\n } else {\n resolved = requested;\n }\n\n const trusted = authenticatedPrincipal?.trim();\n const principal =\n typeof trusted === \"string\" && trusted.length > 0\n ? trusted\n : resolvePrincipal(sessionKey, config);\n\n if (!canWriteNamespace(principal, resolved, config)) {\n return { ok: false, reason: \"not_writable\", namespace: resolved };\n }\n return { ok: true, namespace: resolved };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,OAAO,UAAU;AA8DjB,IAAM,yBAAyB;AAExB,SAAS,oBAAgC;AAC9C,SAAO,CAAC,KAAa,SAAmB;AACtC,UAAM,SAAS,kBAAkB,OAAO,MAAM;AAAA,MAC5C;AAAA,MACA,UAAU;AAAA,MACV,SAAS;AAAA,MACT,OAAO;AAAA,IACT,CAAC;AACD,QAAI,OAAO,OAAO;AAEhB,aAAO,EAAE,QAAQ,IAAI,UAAU,IAAI;AAAA,IACrC;AACA,WAAO;AAAA,MACL,QAAQ,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA,MAC5D,UAAU,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA,IAChE;AAAA,EACF;AACF;AAeO,SAAS,WAAW,OAAuB;AAChD,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,YAAQ,MAAM,WAAW,CAAC;AAC1B,WAAO,KAAK,KAAK,MAAM,QAAU,MAAM;AAAA,EACzC;AACA,SAAO,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAC1C;AAkBO,SAAS,mBAAmB,QAAwB;AACzD,MAAI,MAAM,OAAO,KAAK;AACtB,MAAI,CAAC,IAAK,QAAO;AAMjB,MAAI,UAAU,KAAK,GAAG,EAAG,OAAM,IAAI,MAAM,GAAG,EAAE;AAO9C,MAAI,kBAAkB,KAAK,GAAG,GAAG;AAC/B,WAAO,IAAI,YAAY;AAAA,EACzB;AAcA,QAAM,aACJ,6EAA6E,KAAK,GAAG;AACvF,MAAI,YAAY;AACd,QAAI,OAAO,WAAW,CAAC,KAAK;AAK5B,UAAM,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ACA,QAAM,UAAU,2BAA2B,OAAO;AAClD,MAAI,WAAW,uBAAuB,OAAO,MAAM,SAAS;AAC1D,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAwBO,SAAS,8BACd,WACA,YACA,wBACA,QACyB;AACzB,QAAM,YAAY,WAAW,KAAK;AAClC,MAAI;AACJ,MAAI,CAAC,WAAW;AACd,eAAW,OAAO;AAAA,EACpB,WACE,CAAC,6BAA6B,MAAM,EAAE,cACtC,cAAc,OAAO,kBACrB;AACA,WAAO,EAAE,IAAI,OAAO,QAAQ,eAAe,WAAW,UAAU;AAAA,EAClE,OAAO;AACL,eAAW;AAAA,EACb;AAEA,QAAM,UAAU,wBAAwB,KAAK;AAC7C,QAAM,YACJ,OAAO,YAAY,YAAY,QAAQ,SAAS,IAC5C,UACA,iBAAiB,YAAY,MAAM;AAEzC,MAAI,CAAC,kBAAkB,WAAW,UAAU,MAAM,GAAG;AACnD,WAAO,EAAE,IAAI,OAAO,QAAQ,gBAAgB,WAAW,SAAS;AAAA,EAClE;AACA,SAAO,EAAE,IAAI,MAAM,WAAW,SAAS;AACzC;","names":["namespace","path","path"]}
|
|
@@ -10,7 +10,11 @@ import {
|
|
|
10
10
|
import {
|
|
11
11
|
planNamespaceMaintenance,
|
|
12
12
|
runNamespaceMaintenanceBatchPlan
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-BXPG5AVX.js";
|
|
14
|
+
import {
|
|
15
|
+
resolveNamespaceCapabilities,
|
|
16
|
+
resolveQmdCapabilities
|
|
17
|
+
} from "./chunk-JWDE7OVJ.js";
|
|
14
18
|
import {
|
|
15
19
|
resolveHomeDir
|
|
16
20
|
} from "./chunk-JUC24CTX.js";
|
|
@@ -307,7 +311,7 @@ var MaintenanceScheduler = class {
|
|
|
307
311
|
/** Internal: queue a debounced QMD maintenance pass. */
|
|
308
312
|
requestQmdMaintenance() {
|
|
309
313
|
if (!this.deps.getQmd().isAvailable()) return;
|
|
310
|
-
if (!this.deps.config.
|
|
314
|
+
if (!resolveQmdCapabilities(this.deps.config).qmdMaintenance) return;
|
|
311
315
|
this.qmdMaintenancePending = true;
|
|
312
316
|
if (this.qmdMaintenanceTimer) return;
|
|
313
317
|
this.qmdMaintenanceTimer = setTimeout(() => {
|
|
@@ -336,12 +340,12 @@ var MaintenanceScheduler = class {
|
|
|
336
340
|
this.qmdMaintenanceInFlight = true;
|
|
337
341
|
this.qmdMaintenancePending = false;
|
|
338
342
|
try {
|
|
339
|
-
if (this.deps.config.
|
|
343
|
+
if (resolveNamespaceCapabilities(this.deps.config).namespaces) {
|
|
340
344
|
const plan = await this.namespaceMaintenancePlan("qmd");
|
|
341
345
|
const now = Date.now();
|
|
342
346
|
const lastEmbedAtByNamespace = this.lastQmdEmbedAtMsByNamespace;
|
|
343
347
|
const dueEmbedNamespaces = (namespaces) => {
|
|
344
|
-
if (!this.deps.config.
|
|
348
|
+
if (!resolveQmdCapabilities(this.deps.config).qmdAutoEmbed) return [];
|
|
345
349
|
return namespaces.filter(
|
|
346
350
|
(namespace) => now - (lastEmbedAtByNamespace.get(namespace) ?? 0) >= this.deps.config.qmdEmbedMinIntervalMs
|
|
347
351
|
);
|
|
@@ -403,7 +407,7 @@ var MaintenanceScheduler = class {
|
|
|
403
407
|
} else {
|
|
404
408
|
await this.deps.getQmd().update();
|
|
405
409
|
const now = Date.now();
|
|
406
|
-
if (this.deps.config.
|
|
410
|
+
if (resolveQmdCapabilities(this.deps.config).qmdAutoEmbed && now - this.lastQmdEmbedAtMs >= this.deps.config.qmdEmbedMinIntervalMs) {
|
|
407
411
|
await this.deps.getQmd().embed();
|
|
408
412
|
this.lastQmdEmbedAtMs = now;
|
|
409
413
|
}
|
|
@@ -441,4 +445,4 @@ var MaintenanceScheduler = class {
|
|
|
441
445
|
export {
|
|
442
446
|
MaintenanceScheduler
|
|
443
447
|
};
|
|
444
|
-
//# sourceMappingURL=chunk-
|
|
448
|
+
//# sourceMappingURL=chunk-GYICIICQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/orchestration/maintenance.ts"],"sourcesContent":["/**\n * Maintenance scheduler — extracted from the orchestrator (issue #1526 PR1).\n *\n * Owns the WHEN of memory maintenance:\n * - cron auto-registration (writes jobs.json entries the OpenClaw cron\n * daemon picks up)\n * - debounced + singleflight QMD index maintenance (re-index + embed\n * after writes)\n * - consolidation scheduling trigger (count + interval gated)\n *\n * Does NOT own the WHAT — the actual job runners (runSemanticConsolidation,\n * runPatternReinforcement, runDeepSleepGovernanceNow, runConsolidation)\n * remain on the orchestrator because they need the full LLM + extraction\n * dependency surface. The scheduler invokes consolidation through a\n * callback so the orchestrator stays the source of truth for that work.\n *\n * Behavior-preserving move from orchestrator.ts. No logic changes — the\n * orchestrator keeps thin delegating methods so existing tests that stub\n * `orchestrator.requestQmdMaintenance` etc. continue to work.\n */\n\nimport {\n resolveNamespaceCapabilities,\n resolveQmdCapabilities,\n} from \"../capabilities.js\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { PluginConfig } from \"../types.js\";\nimport type { SearchBackend } from \"../search/port.js\";\nimport {\n NamespaceSearchRouter,\n type NamespaceUpdateResult,\n} from \"../namespaces/search.js\";\nimport type { NamespaceCatalog } from \"../namespaces/catalog.js\";\nimport {\n planNamespaceMaintenance,\n runNamespaceMaintenanceBatchPlan,\n type NamespaceMaintenancePlan,\n type NamespaceMaintenanceSkipReason,\n} from \"../maintenance/namespace-planner.js\";\nimport {\n ensureContradictionScanCron,\n ensureDaySummaryCron,\n ensureGraphEdgeDecayCron,\n ensureNightlyGovernanceCron,\n ensurePatternReinforcementCron,\n ensureProceduralMiningCron,\n graphEdgeDecayCadenceToCronExpr,\n} from \"../maintenance/memory-governance-cron.js\";\nimport { resolveHomeDir } from \"../runtime/env.js\";\nimport { log } from \"../logger.js\";\n\n/** Reason a QMD maintenance pass was skipped, used for status recording. */\nfunction qmdMaintenanceSkipReasonForError(\n error: unknown,\n): NamespaceMaintenanceSkipReason | null {\n const message = error instanceof Error ? error.message : String(error);\n return /^QMD (?:update|embed) skipped by .*min-interval gate$/.test(message)\n ? \"throttled\"\n : null;\n}\n\n/** Dependencies injected by the orchestrator. All stable references. */\nexport interface MaintenanceSchedulerDeps {\n config: PluginConfig;\n /** Live accessor — the orchestrator can reassign its qmd backend after\n * construction (e.g. swap to NoopSearchBackend when the collection is\n * missing), and the scheduler must always observe the current backend. */\n getQmd: () => SearchBackend;\n namespaceSearchRouter: NamespaceSearchRouter;\n namespaceCatalog: NamespaceCatalog;\n}\n\n/**\n * Schedules and debounces memory maintenance work. Owns the cadence +\n * singleflight state that previously lived as private orchestrator fields.\n *\n * The orchestrator constructs one instance in its constructor and delegates\n * the public scheduling entrypoints to it. Job execution stays on the\n * orchestrator (LLM-heavy) and is invoked through callbacks.\n */\nexport class MaintenanceScheduler {\n // ── Consolidation scheduling state ──\n private nonZeroExtractionsSinceConsolidation = 0;\n private lastConsolidationRunAtMs = 0;\n private consolidationInFlight = false;\n\n // ── QMD maintenance scheduling state ──\n private qmdMaintenanceTimer: NodeJS.Timeout | null = null;\n private qmdMaintenancePending = false;\n private qmdMaintenanceInFlight = false;\n private lastQmdEmbedAtMs = 0;\n private lastQmdEmbedAtMsByNamespace = new Map<string, number>();\n\n constructor(private readonly deps: MaintenanceSchedulerDeps) {}\n\n // ───────────────────────────────────────────────────────────────────────\n // Cron auto-registration\n // ───────────────────────────────────────────────────────────────────────\n\n /**\n * Register every cron job the daemon should run, gated by its config flag.\n * Each registration is independent and non-fatal — a failure in one does\n * not block the others (mirrors the orchestrator's prior sequential try/\n * catch behavior exactly).\n *\n * Returns when all eligible registrations have completed so callers that\n * `await deferredReady` can rely on jobs.json being current.\n */\n async autoRegisterCrons(_signal: AbortSignal): Promise<void> {\n if (this.deps.config.daySummaryEnabled) {\n try {\n await this.autoRegisterDaySummaryCron();\n } catch (err) {\n log.debug(`day-summary cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.nightlyGovernanceCronAutoRegister) {\n try {\n await this.autoRegisterNightlyGovernanceCron();\n } catch (err) {\n log.debug(`nightly governance cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.procedural?.proceduralMiningCronAutoRegister) {\n try {\n await this.autoRegisterProceduralMiningCron();\n } catch (err) {\n log.debug(`procedural mining cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.contradictionScan?.enabled) {\n try {\n await this.autoRegisterContradictionScanCron();\n } catch (err) {\n log.debug(`contradiction scan cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.patternReinforcementEnabled) {\n try {\n await this.autoRegisterPatternReinforcementCron();\n } catch (err) {\n log.debug(`pattern reinforcement cron auto-register failed (non-fatal): ${err}`);\n }\n }\n if (this.deps.config.graphEdgeDecayEnabled) {\n try {\n await this.autoRegisterGraphEdgeDecayCron();\n } catch (err) {\n log.debug(`graph edge decay cron auto-register failed (non-fatal): ${err}`);\n }\n }\n }\n\n async autoRegisterDaySummaryCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"day-summary cron: jobs.json not found, skipping auto-register\");\n return;\n }\n\n // Resolve an OpenClaw cron-routing model only in gateway mode. In plugin\n // mode, summaryModel is a direct-client model id for Remnic's own LLM\n // calls and may be unroutable as an OpenClaw agentTurn model.\n const rawSummaryModel = this.deps.config.summaryModel;\n const taskPrimary = this.deps.config.taskModelChain?.primary;\n const isGateway = this.deps.config.modelSource === \"gateway\";\n const model = isGateway ? (rawSummaryModel || taskPrimary || undefined) : undefined;\n // Attach task-chain fallbacks only when the model matches the task-chain\n // primary. If summaryModel is a distinct override, its fallbacks would\n // be unrelated to the task chain. Also append gateway default models as\n // tail fallbacks (de-duped) so a task-chain outage doesn't stop the cron\n // before reaching the gateway default chain. Mirrors hourly cron pattern.\n const fallbacks: string[] = [];\n if (model && taskPrimary && model === taskPrimary) {\n const seen = new Set<string>(model ? [model] : []);\n const addUnique = (value: string | undefined) => {\n if (typeof value !== \"string\") return;\n const trimmed = value.trim();\n if (trimmed.length > 0 && !seen.has(trimmed)) {\n seen.add(trimmed);\n fallbacks.push(trimmed);\n }\n };\n for (const fb of this.deps.config.taskModelChain?.fallbacks ?? []) addUnique(fb);\n const gwDefaults = this.deps.config.gatewayConfig?.agents?.defaults?.model;\n addUnique(gwDefaults?.primary);\n if (Array.isArray(gwDefaults?.fallbacks)) {\n for (const fb of gwDefaults.fallbacks) addUnique(fb);\n }\n }\n\n const timezone =\n this.deps.config.daySummaryTimezone ||\n Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n const result = await ensureDaySummaryCron(jobsPath, {\n timezone,\n ...(model ? { model } : {}),\n ...(fallbacks.length > 0 ? { fallbacks } : {}),\n });\n if (result.created) {\n log.info(\n `day-summary cron auto-registered (${result.jobId}, 23:47 ${timezone}${model ? `, model: ${model}` : \"\"})`,\n );\n } else if (result.updated) {\n log.info(\n `day-summary cron reconciled (${result.jobId}, timezone: ${timezone}${model ? `, model: ${model}` : \"\"})`,\n );\n } else {\n log.debug(\"day-summary cron already up to date\");\n }\n } catch (err) {\n log.debug(`day-summary cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterNightlyGovernanceCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"nightly governance cron: jobs.json not found, skipping auto-register\");\n return;\n }\n\n const created = await ensureNightlyGovernanceCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(\n `nightly governance cron auto-registered (${created.jobId}, 02:23 ${Intl.DateTimeFormat().resolvedOptions().timeZone})`,\n );\n } else {\n log.debug(\"nightly governance cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`nightly governance cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterProceduralMiningCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"procedural mining cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const created = await ensureProceduralMiningCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(`procedural mining cron auto-registered (${created.jobId})`);\n } else {\n log.debug(\"procedural mining cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`procedural mining cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterContradictionScanCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"contradiction scan cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const created = await ensureContradictionScanCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(`contradiction scan cron auto-registered (${created.jobId})`);\n } else {\n log.debug(\"contradiction scan cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`contradiction scan cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterPatternReinforcementCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"pattern reinforcement cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const created = await ensurePatternReinforcementCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n });\n if (created.created) {\n log.info(`pattern reinforcement cron auto-registered (${created.jobId})`);\n } else {\n log.debug(\"pattern reinforcement cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`pattern reinforcement cron auto-register error: ${err}`);\n }\n }\n\n async autoRegisterGraphEdgeDecayCron(): Promise<void> {\n const home = resolveHomeDir();\n const jobsPath = path.join(home, \".openclaw\", \"cron\", \"jobs.json\");\n try {\n if (!existsSync(jobsPath)) {\n log.debug(\"graph edge decay cron: jobs.json not found, skipping auto-register\");\n return;\n }\n const scheduleExpr = graphEdgeDecayCadenceToCronExpr(\n this.deps.config.graphEdgeDecayCadenceMs,\n );\n const created = await ensureGraphEdgeDecayCron(jobsPath, {\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n scheduleExpr,\n });\n if (created.created) {\n log.info(`graph edge decay cron auto-registered (${created.jobId}, ${scheduleExpr})`);\n } else {\n log.debug(\"graph edge decay cron already exists, skipping auto-register\");\n }\n } catch (err) {\n log.debug(`graph edge decay cron auto-register error: ${err}`);\n }\n }\n\n // ───────────────────────────────────────────────────────────────────────\n // Consolidation scheduling\n // ───────────────────────────────────────────────────────────────────────\n\n /**\n * Maybe trigger a background consolidation pass after an extraction.\n * Counted + interval gated so a burst of extractions does not fan into a\n * burst of consolidation passes. The consolidation runner itself is\n * passed in as a callback because it lives on the orchestrator (LLM +\n * storage dependency surface) and is not owned by this module.\n */\n maybeScheduleConsolidation(\n nonZeroExtraction: boolean,\n runConsolidation: () => Promise<unknown>,\n ): void {\n if (nonZeroExtraction) this.nonZeroExtractionsSinceConsolidation += 1;\n if (\n this.deps.config.consolidationRequireNonZeroExtraction &&\n !nonZeroExtraction\n ) {\n return;\n }\n if (\n this.nonZeroExtractionsSinceConsolidation <\n this.deps.config.consolidateEveryN\n ) {\n return;\n }\n\n const now = Date.now();\n if (\n now - this.lastConsolidationRunAtMs <\n this.deps.config.consolidationMinIntervalMs\n ) {\n return;\n }\n if (this.consolidationInFlight) return;\n\n this.consolidationInFlight = true;\n this.lastConsolidationRunAtMs = now;\n this.nonZeroExtractionsSinceConsolidation = 0;\n runConsolidation()\n .catch((err) => log.error(\"background consolidation failed\", err))\n .finally(() => {\n this.consolidationInFlight = false;\n });\n }\n\n /** Whether a background consolidation pass is currently running. Exposed so\n * the orchestrator's waitForConsolidationIdle can poll idle state without\n * owning the cadence state (issue #1526 PR1). */\n isConsolidationInFlight(): boolean {\n return this.consolidationInFlight;\n }\n\n /** Whether a debounced QMD maintenance pass is armed and waiting for the\n * debounce timer. Exposed so drain/teardown diagnostics (e.g. the bench\n * adapter) can observe scheduler idle state after the #1526 PR1 extraction\n * moved this flag off the orchestrator. */\n isQmdMaintenancePending(): boolean {\n return this.qmdMaintenancePending;\n }\n\n /** Whether a QMD maintenance pass is currently running (singleflight guard).\n * Exposed for drain/teardown diagnostics (see isQmdMaintenancePending). */\n isQmdMaintenanceInFlight(): boolean {\n return this.qmdMaintenanceInFlight;\n }\n // ───────────────────────────────────────────────────────────────────────\n // QMD maintenance scheduling (debounced + singleflight)\n // ───────────────────────────────────────────────────────────────────────\n\n /** Internal: queue a debounced QMD maintenance pass. */\n private requestQmdMaintenance(): void {\n if (!this.deps.getQmd().isAvailable()) return;\n if (!resolveQmdCapabilities(this.deps.config).qmdMaintenance) return;\n\n this.qmdMaintenancePending = true;\n if (this.qmdMaintenanceTimer) return;\n\n this.qmdMaintenanceTimer = setTimeout(() => {\n this.qmdMaintenanceTimer = null;\n this.runQmdMaintenance().catch((err) =>\n log.debug(`background qmd maintenance failed: ${err}`),\n );\n }, this.deps.config.qmdMaintenanceDebounceMs);\n }\n\n /**\n * Public entrypoint for tool-driven QMD maintenance requests.\n * Routes through existing debounced/singleflight maintenance controls.\n */\n requestQmdMaintenanceForTool(reason: string): void {\n try {\n this.requestQmdMaintenance();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log.warn(`qmd maintenance request failed (${reason}): ${msg}`);\n }\n }\n\n /** Internal: run a single QMD maintenance pass under singleflight guard. */\n async runQmdMaintenance(): Promise<void> {\n if (this.qmdMaintenanceInFlight) return;\n if (!this.qmdMaintenancePending) return;\n this.qmdMaintenanceInFlight = true;\n this.qmdMaintenancePending = false;\n\n try {\n if (resolveNamespaceCapabilities(this.deps.config).namespaces) {\n // Include cataloged dynamic namespaces, not just the configured set\n // (NGnei), but run through the namespace-aware maintenance planner so\n // each namespace is budgeted, lock-protected, and status-recorded\n // independently (issue #1500).\n const plan = await this.namespaceMaintenancePlan(\"qmd\");\n const now = Date.now();\n const lastEmbedAtByNamespace = this.lastQmdEmbedAtMsByNamespace;\n const dueEmbedNamespaces = (namespaces: string[]): string[] => {\n if (!resolveQmdCapabilities(this.deps.config).qmdAutoEmbed) return [];\n return namespaces.filter(\n (namespace) =>\n now - (lastEmbedAtByNamespace.get(namespace) ?? 0) >=\n this.deps.config.qmdEmbedMinIntervalMs,\n );\n };\n const markEmbedded = (namespaces: string[]): void => {\n if (namespaces.length === 0) return;\n for (const namespace of namespaces) {\n lastEmbedAtByNamespace.set(namespace, now);\n }\n this.lastQmdEmbedAtMs = now;\n };\n await runNamespaceMaintenanceBatchPlan(\n this.deps.config,\n plan,\n async (candidates) => {\n const namespaces = candidates.map((candidate) => candidate.namespace);\n const embedNamespaces = dueEmbedNamespaces(namespaces);\n let result: NamespaceUpdateResult;\n try {\n result = await this.deps.namespaceSearchRouter.updateNamespacesDetailed(\n namespaces,\n undefined,\n { strict: true },\n );\n } catch (error) {\n if (\n embedNamespaces.length > 0 &&\n qmdMaintenanceSkipReasonForError(error) === \"throttled\"\n ) {\n await this.deps.namespaceSearchRouter.embedNamespaces(embedNamespaces, {\n strict: true,\n });\n markEmbedded(embedNamespaces);\n }\n throw error;\n }\n if (result.backendCount <= 0) {\n throw new Error(\"no eligible QMD backend for selected namespaces\");\n }\n if (result.eligibleNamespaces.length !== namespaces.length) {\n const eligible = new Set(result.eligibleNamespaces);\n const missing = namespaces.filter(\n (namespace) => !eligible.has(namespace),\n );\n throw new Error(\n `QMD backend ineligible for selected namespaces (${missing.length})`,\n );\n }\n if (embedNamespaces.length > 0) {\n await this.deps.namespaceSearchRouter.embedNamespaces(embedNamespaces, {\n strict: true,\n });\n markEmbedded(embedNamespaces);\n }\n return { itemCount: result.backendCount };\n },\n this.deps.namespaceCatalog,\n {\n skipReasonForError: qmdMaintenanceSkipReasonForError,\n },\n );\n } else {\n await this.deps.getQmd().update();\n const now = Date.now();\n if (\n resolveQmdCapabilities(this.deps.config).qmdAutoEmbed &&\n now - this.lastQmdEmbedAtMs >= this.deps.config.qmdEmbedMinIntervalMs\n ) {\n await this.deps.getQmd().embed();\n this.lastQmdEmbedAtMs = now;\n }\n }\n } finally {\n this.qmdMaintenanceInFlight = false;\n if (this.qmdMaintenancePending) {\n this.requestQmdMaintenance();\n }\n }\n }\n\n /** Build the namespace-aware maintenance plan for one job. */\n private async namespaceMaintenancePlan(\n jobName: string,\n ): Promise<NamespaceMaintenancePlan> {\n return planNamespaceMaintenance(this.deps.config, {\n jobName,\n catalog: this.deps.namespaceCatalog,\n });\n }\n\n // ───────────────────────────────────────────────────────────────────────\n // Lifecycle\n // ───────────────────────────────────────────────────────────────────────\n\n /**\n * Clear any pending debounce timer. Called from the orchestrator's\n * destroy() so a late tick does not fire on a torn-down instance.\n */\n dispose(): void {\n if (this.qmdMaintenanceTimer) {\n clearTimeout(this.qmdMaintenanceTimer);\n this.qmdMaintenanceTimer = null;\n }\n this.qmdMaintenancePending = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAS,kBAAkB;AAC3B,OAAO,UAAU;AA4BjB,SAAS,iCACP,OACuC;AACvC,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,SAAO,wDAAwD,KAAK,OAAO,IACvE,cACA;AACN;AAqBO,IAAM,uBAAN,MAA2B;AAAA,EAahC,YAA6B,MAAgC;AAAhC;AAAA,EAAiC;AAAA,EAAjC;AAAA;AAAA,EAXrB,uCAAuC;AAAA,EACvC,2BAA2B;AAAA,EAC3B,wBAAwB;AAAA;AAAA,EAGxB,sBAA6C;AAAA,EAC7C,wBAAwB;AAAA,EACxB,yBAAyB;AAAA,EACzB,mBAAmB;AAAA,EACnB,8BAA8B,oBAAI,IAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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UAC1C;AAAA,UACA,KAAK,KAAK;AAAA,UACV;AAAA,YACE,oBAAoB;AAAA,UACtB;AAAA,QACF;AAAA,MACF,OAAO;AACL,cAAM,KAAK,KAAK,OAAO,EAAE,OAAO;AAChC,cAAM,MAAM,KAAK,IAAI;AACrB,YACE,uBAAuB,KAAK,KAAK,MAAM,EAAE,gBACzC,MAAM,KAAK,oBAAoB,KAAK,KAAK,OAAO,uBAChD;AACA,gBAAM,KAAK,KAAK,OAAO,EAAE,MAAM;AAC/B,eAAK,mBAAmB;AAAA,QAC1B;AAAA,MACF;AAAA,IACF,UAAE;AACA,WAAK,yBAAyB;AAC9B,UAAI,KAAK,uBAAuB;AAC9B,aAAK,sBAAsB;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAc,yBACZ,SACmC;AACnC,WAAO,yBAAyB,KAAK,KAAK,QAAQ;AAAA,MAChD;AAAA,MACA,SAAS,KAAK,KAAK;AAAA,IACrB,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,UAAgB;AACd,QAAI,KAAK,qBAAqB;AAC5B,mBAAa,KAAK,mBAAmB;AACrC,WAAK,sBAAsB;AAAA,IAC7B;AACA,SAAK,wBAAwB;AAAA,EAC/B;AACF;","names":[]}
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
} from "./chunk-PWFWCGOO.js";
|
|
9
9
|
import {
|
|
10
10
|
LocalLlmClient
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-IX4L7E5G.js";
|
|
12
12
|
import {
|
|
13
13
|
sessionStoragePaths
|
|
14
14
|
} from "./chunk-S4DDLTPX.js";
|
|
@@ -24,6 +24,9 @@ import {
|
|
|
24
24
|
import {
|
|
25
25
|
extractJsonCandidates
|
|
26
26
|
} from "./chunk-RGMVMVMF.js";
|
|
27
|
+
import {
|
|
28
|
+
resolveLocalLlmCapabilities
|
|
29
|
+
} from "./chunk-JWDE7OVJ.js";
|
|
27
30
|
import {
|
|
28
31
|
log
|
|
29
32
|
} from "./chunk-NU3CSQ4H.js";
|
|
@@ -61,7 +64,7 @@ var HourlySummarizer = class {
|
|
|
61
64
|
gatewayConfig,
|
|
62
65
|
fallbackLlmRuntimeContextFromConfig(config)
|
|
63
66
|
);
|
|
64
|
-
if (!gatewayConfig?.agents?.defaults?.model?.primary && !config.
|
|
67
|
+
if (!gatewayConfig?.agents?.defaults?.model?.primary && !resolveLocalLlmCapabilities(config).localLlm && config.modelSource !== "gateway") {
|
|
65
68
|
log.warn("no gateway default AI and local LLM disabled \u2014 hourly summarization disabled");
|
|
66
69
|
}
|
|
67
70
|
}
|
|
@@ -69,7 +72,7 @@ var HourlySummarizer = class {
|
|
|
69
72
|
return this.config.modelSource === "gateway";
|
|
70
73
|
}
|
|
71
74
|
get shouldUseLocalLlm() {
|
|
72
|
-
return this.config.
|
|
75
|
+
return resolveLocalLlmCapabilities(this.config).localLlm && !this.useGatewayModelSource;
|
|
73
76
|
}
|
|
74
77
|
withGatewayAgent(options) {
|
|
75
78
|
if (!this.useGatewayModelSource) return options;
|
|
@@ -686,4 +689,4 @@ ${truncatedConversation}`;
|
|
|
686
689
|
export {
|
|
687
690
|
HourlySummarizer
|
|
688
691
|
};
|
|
689
|
-
//# sourceMappingURL=chunk-
|
|
692
|
+
//# sourceMappingURL=chunk-HFXZIF3V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/summarizer.ts"],"sourcesContent":["import { mkdir, readFile, writeFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { log } from \"./logger.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport type { HourlySummary, TranscriptEntry, PluginConfig, GatewayConfig } from \"./types.js\";\nimport type { TranscriptManager } from \"./transcript.js\";\nimport { readSummarySnapshot, upsertSummarySnapshot, writeSummarySnapshot } from \"./summary-snapshot.js\";\nimport {\n encodeStoragePathSegment,\n resolveSafeStoragePath,\n} from \"./storage-paths.js\";\nimport { sessionStoragePaths } from \"./session-identity.js\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\n\n// Schema for LLM summary output\nconst HourlySummarySchema = z.object({\n bullets: z\n .array(z.string().trim().min(1))\n .min(1)\n .describe(\"3-5 bullet points summarizing the hour's activity\"),\n});\n\ntype HourlySummaryResult = z.infer<typeof HourlySummarySchema>;\n\nconst HourlySummaryExtendedSchema = z.object({\n topics: z.array(z.string()).default([]),\n decisions: z.array(z.string()).default([]),\n actionItems: z.array(z.string()).default([]),\n rejected: z.array(z.string()).default([]),\n});\n\ntype HourlySummaryExtendedResult = z.infer<typeof HourlySummaryExtendedSchema>;\n\ntype HourlySummaryExtendedMeta = {\n userTurns: number;\n assistantTurns: number;\n toolCalls: number;\n toolCounts: Record<string, number>;\n};\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nexport class HourlySummarizer {\n private summariesDir: string;\n private config: PluginConfig;\n private localLlm: LocalLlmClient;\n private fallbackLlm: FallbackLlmClient;\n private modelRegistry: ModelRegistry;\n private transcript?: TranscriptManager;\n\n constructor(config: PluginConfig, gatewayConfig?: GatewayConfig, modelRegistry?: ModelRegistry, transcript?: TranscriptManager) {\n this.config = config;\n this.summariesDir = path.join(config.memoryDir, \"summaries\", \"hourly\");\n this.modelRegistry = modelRegistry ?? new ModelRegistry(config.memoryDir);\n this.transcript = transcript;\n\n // Initialize local LLM client with shared model registry\n this.localLlm = new LocalLlmClient(config, this.modelRegistry);\n\n // Initialize fallback client with gateway config\n this.fallbackLlm = new FallbackLlmClient(\n gatewayConfig,\n fallbackLlmRuntimeContextFromConfig(config),\n );\n\n if (!gatewayConfig?.agents?.defaults?.model?.primary && !resolveLocalLlmCapabilities(config).localLlm && config.modelSource !== \"gateway\") {\n log.warn(\"no gateway default AI and local LLM disabled — hourly summarization disabled\");\n }\n }\n\n private get useGatewayModelSource(): boolean {\n return this.config.modelSource === \"gateway\";\n }\n\n private get shouldUseLocalLlm(): boolean {\n return resolveLocalLlmCapabilities(this.config).localLlm && !this.useGatewayModelSource;\n }\n\n private withGatewayAgent(options: import(\"./fallback-llm.js\").FallbackLlmOptions): import(\"./fallback-llm.js\").FallbackLlmOptions {\n if (!this.useGatewayModelSource) return options;\n // Shared resolution (taskModelChain > gatewayAgentId) — gotcha #22. Issue #1365.\n return { ...options, ...gatewayTaskChainOptions(this.config) };\n }\n\n async initialize(): Promise<void> {\n await mkdir(this.summariesDir, { recursive: true });\n log.info(\"hourly summarizer initialized\");\n }\n\n private async summarySessionDir(sessionKey: string): Promise<string> {\n return resolveSafeStoragePath(\n this.summariesDir,\n encodeStoragePathSegment(sessionKey, \"session\"),\n );\n }\n\n private async legacySummarySessionDir(sessionKey: string): Promise<string | null> {\n if (sessionKey.includes(\"\\0\")) return null;\n try {\n return await resolveSafeStoragePath(this.summariesDir, sessionKey);\n } catch {\n return null;\n }\n }\n\n private summaryDateString(hour: string): string {\n const dateStr = hour.slice(0, 10);\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateStr)) {\n throw new Error(`invalid hourly summary timestamp: ${hour}`);\n }\n return dateStr;\n }\n\n // Generate summary for a specific hour and session\n async generateSummary(\n sessionKey: string,\n hourStart: Date,\n entries: TranscriptEntry[]\n ): Promise<HourlySummary | null> {\n if (entries.length === 0) return null;\n\n // Format entries for the LLM\n const conversation = entries\n .map((e) => `[${e.role}] ${e.content}`)\n .join(\"\\n\\n\");\n\n if (this.config.hourlySummariesExtendedEnabled) {\n const extended = await this.generateExtended(sessionKey, hourStart, conversation, entries);\n if (!extended) return null;\n const meta: HourlySummaryExtendedMeta = {\n userTurns: entries.filter((e) => e.role === \"user\").length,\n assistantTurns: entries.filter((e) => e.role === \"assistant\").length,\n toolCalls: extended._meta.toolCalls,\n toolCounts: extended._meta.toolCounts,\n };\n // Keep HourlySummary surface stable; encode \"topics\" as bullets for recall injection.\n const base: HourlySummary = {\n hour: hourStart.toISOString(),\n sessionKey,\n bullets: extended.topics.length > 0 ? extended.topics.slice(0, 5) : [\"(summary generated)\"],\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n const withExtras = base as any;\n withExtras._extended = extended;\n withExtras._extendedMeta = meta;\n return base;\n }\n\n const hourIso = hourStart.toISOString();\n const startTime = Date.now();\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.generateWithLocalLlm(conversation);\n if (localResult) {\n const durationMs = Date.now() - startTime;\n log.debug(\n `generated hourly summary for ${sessionKey} at ${hourIso} in ${durationMs}ms using local LLM`\n );\n return {\n hour: hourIso,\n sessionKey,\n bullets: localResult.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n // Local failed, fall back if allowed\n if (!this.config.localLlmFallback) {\n log.warn(\"summary generation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"summary generation: local LLM unavailable, falling back to gateway default AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"summary generation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"summary generation: local LLM error, falling back to gateway default AI:\", err);\n }\n }\n\n // Fall back to gateway's default AI\n log.info(\"summary generation: falling back to gateway default AI\");\n\n try {\n const messages = [\n {\n role: \"system\" as const,\n content: `You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\n\nGuidelines:\n- Focus on what was accomplished, decided, or discussed\n- Include specific topics, projects, or entities mentioned\n- Note any significant user requests or agent actions\n- Keep bullets brief but informative (1-2 sentences each)\n- Skip trivial greetings or meta-conversation\n- Use present tense for ongoing work, past for completed items\n\nRespond with valid JSON matching this schema:\n{\n \"bullets\": [\"bullet 1\", \"bullet 2\", \"bullet 3\"]\n}`,\n },\n { role: \"user\" as const, content: `Summarize this conversation:\\n\\n${conversation}` },\n ];\n\n const result = await this.fallbackLlm.parseWithSchema(\n messages,\n HourlySummarySchema,\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 8192 }),\n );\n\n const durationMs = Date.now() - startTime;\n\n if (result) {\n log.debug(\n `generated hourly summary for ${sessionKey} at ${hourIso} in ${durationMs}ms via fallback`,\n );\n return {\n hour: hourIso,\n sessionKey,\n bullets: result.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n\n log.warn(\"summary generation fallback returned no parsed output\");\n return null;\n } catch (err) {\n log.error(\"summary generation fallback failed\", err);\n return null;\n }\n }\n\n private async generateExtended(\n sessionKey: string,\n hourStart: Date,\n conversation: string,\n entries: TranscriptEntry[],\n ): Promise<(HourlySummaryExtendedResult & { _meta: HourlySummaryExtendedMeta }) | null> {\n const hourIso = hourStart.toISOString();\n const startTime = Date.now();\n\n const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);\n let toolCounts: Record<string, number> = {};\n if (this.config.hourlySummariesIncludeToolStats && this.transcript) {\n const uses = await this.transcript.readToolUse(sessionKey, hourStart, hourEnd);\n for (const u of uses) toolCounts[u.tool] = (toolCounts[u.tool] ?? 0) + 1;\n }\n\n const sys = `You are a conversation summarization system.\\n\\nSummarize the hour into structured sections.\\n\\nReturn valid JSON matching:\\n{\\n \\\"topics\\\": [\\\"...\\\"],\\n \\\"decisions\\\": [\\\"...\\\"],\\n \\\"actionItems\\\": [\\\"...\\\"],\\n \\\"rejected\\\": [\\\"...\\\"]\\n}\\n\\nGuidelines:\\n- Prefer concrete topics and decisions.\\n- Action items should be imperative.\\n- Rejected ideas are things that were explicitly discarded or reversed.\\n- If there are none for a section, return an empty array.\\n`;\n\n const toolStatsLine = Object.keys(toolCounts).length > 0\n ? `Tools used (counts): ${Object.entries(toolCounts).sort((a,b)=>b[1]-a[1]).slice(0,10).map(([k,v])=>`${k}=${v}`).join(\", \")}\\n\\n`\n : \"\";\n const userTurns = entries.filter((e) => e.role === \"user\").length;\n const assistantTurns = entries.filter((e) => e.role === \"assistant\").length;\n const toolCalls = Object.values(toolCounts).reduce((a,b)=>a+b,0);\n const statsLine = `Stats: userTurns=${userTurns}, assistantTurns=${assistantTurns}, toolCalls=${toolCalls}\\n\\n`;\n\n const user = `Hour: ${hourIso}\\nSession: ${sessionKey}\\n\\n${statsLine}${toolStatsLine}Conversation:\\n${conversation}\\n`;\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const contextSizes = this.modelRegistry.calculateContextSizes(this.config.localLlmModel, this.config.localLlmMaxContext);\n const truncated = user.length > contextSizes.maxInputChars ? user.slice(0, contextSizes.maxInputChars) + \"\\n\\n[truncated]\" : user;\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"Output valid JSON only.\" },\n { role: \"user\", content: sys + \"\\n\\n\" + truncated },\n ],\n {\n temperature: 0.2,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"hourly_summary_extended\",\n priority: \"background\",\n },\n );\n if (response?.content) {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n const result = HourlySummaryExtendedSchema.parse(parsed);\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (local)`,\n );\n return { ...result, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n } catch {\n // keep trying candidates\n }\n }\n }\n } catch (err) {\n if (!this.config.localLlmFallback) return null;\n log.info(\"extended summary: local failed, falling back:\", err);\n }\n }\n\n try {\n const result = await this.fallbackLlm.parseWithSchema(\n [\n { role: \"system\" as const, content: sys },\n { role: \"user\" as const, content: user },\n ],\n HourlySummaryExtendedSchema,\n this.withGatewayAgent({ temperature: 0.2, maxTokens: 2048 }),\n );\n if (result) {\n log.debug(`generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (fallback)`);\n return { ...result, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n }\n return null;\n } catch (err) {\n log.error(\"extended summary generation failed\", err);\n return null;\n }\n }\n\n /**\n * Generate summary using local LLM with JSON mode.\n * Uses dynamic context sizing based on model capabilities.\n */\n private async generateWithLocalLlm(conversation: string): Promise<HourlySummaryResult | null> {\n // Get dynamic context sizes based on model capabilities\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Summarizer model context: ${contextSizes.description}`);\n\n const maxConversationChars = contextSizes.maxInputChars;\n const truncatedConversation = conversation.length > maxConversationChars\n ? conversation.slice(0, maxConversationChars) + \"\\n\\n[truncated]\"\n : conversation;\n\n const instructions = `You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\n\nGuidelines:\n- Focus on what was accomplished, decided, or discussed\n- Include specific topics, projects, or entities mentioned\n- Note any significant user requests or agent actions\n- Keep bullets brief but informative (1-2 sentences each)\n- Skip trivial greetings or meta-conversation\n- Use present tense for ongoing work, past for completed items\n\nRespond with valid JSON matching this schema:\n{\n \"bullets\": [\"bullet 1\", \"bullet 2\", \"bullet 3\"]\n}`;\n\n const fullPrompt = `${instructions}\\n\\nConversation to summarize:\\n${truncatedConversation}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a conversation summarization system. Output valid JSON only.\" },\n { role: \"user\", content: fullPrompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"hourly_summary\",\n priority: \"background\",\n },\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n // Parse JSON response\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return HourlySummarySchema.parse(parsed);\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM summary: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n // Save summary to file\n async saveSummary(summary: HourlySummary): Promise<void> {\n const sessionDir = await this.summarySessionDir(summary.sessionKey);\n await mkdir(sessionDir, { recursive: true });\n\n // Format date as YYYY-MM-DD for the filename\n const dateStr = this.summaryDateString(summary.hour);\n const filePath = await resolveSafeStoragePath(sessionDir, `${dateStr}.md`);\n\n // Format hour as HH:00 for display\n const hourStr = summary.hour.slice(11, 13);\n\n // Build markdown content\n const lines: string[] = [];\n\n // Check if file exists to append or create\n let existingContent = \"\";\n try {\n existingContent = await readFile(filePath, \"utf-8\");\n } catch {\n // File doesn't exist yet, will create new\n }\n\n // Check if this hour already exists (idempotent)\n const hourHeader = `## ${hourStr}:00`;\n if (existingContent.includes(hourHeader)) {\n // Replace existing hour section\n const headerMatch = new RegExp(`(^|\\\\n)${escapeRegExp(hourHeader)}\\\\n`).exec(existingContent);\n const sectionStart = headerMatch\n ? headerMatch.index + headerMatch[1].length\n : existingContent.indexOf(hourHeader);\n const nextHeaderPattern = /\\n## \\d{2}:00\\n/g;\n nextHeaderPattern.lastIndex = sectionStart + hourHeader.length;\n const nextHeader = nextHeaderPattern.exec(existingContent);\n const beforeHour = existingContent.slice(0, sectionStart);\n const afterHour = nextHeader\n ? existingContent.slice(nextHeader.index + 1)\n : \"\";\n const newSection = this.formatHourSection(summary, hourHeader);\n existingContent = beforeHour + newSection.trimEnd() + (afterHour ? \"\\n\\n\" + afterHour : \"\\n\");\n\n await writeFile(filePath, existingContent, \"utf-8\");\n log.debug(`updated hourly summary for ${summary.sessionKey} at ${hourStr}:00`);\n } else {\n // Append new hour section\n const newSection = this.formatHourSection(summary, hourHeader);\n\n if (existingContent) {\n // Add to existing file\n await writeFile(filePath, existingContent.trimEnd() + \"\\n\\n\" + newSection, \"utf-8\");\n } else {\n // Create new file with header\n const header = `# Hourly Summaries — ${dateStr}\\n\\n*Session: ${summary.sessionKey}*\\n`;\n await writeFile(filePath, header + \"\\n\" + newSection, \"utf-8\");\n }\n log.debug(`saved hourly summary for ${summary.sessionKey} at ${hourStr}:00`);\n }\n try {\n await upsertSummarySnapshot(this.config.memoryDir, summary);\n } catch (error) {\n log.warn(\n `hourly summarizer: failed to update summary snapshot for ${summary.sessionKey} (fail-open): ${String(error)}`,\n );\n }\n }\n\n private formatHourSection(summary: HourlySummary, hourHeader: string): string {\n const ext = (summary as any)._extended as (HourlySummaryExtendedResult & { _meta?: HourlySummaryExtendedMeta }) | undefined;\n const meta = (summary as any)._extendedMeta as HourlySummaryExtendedMeta | undefined;\n const lines: string[] = [hourHeader, \"\"];\n\n if (this.config.hourlySummariesExtendedEnabled && ext) {\n lines.push(\"### Topics Discussed\");\n for (const t of ext.topics) lines.push(`- ${t}`);\n lines.push(\"\");\n lines.push(\"### Decisions Made\");\n for (const d of ext.decisions) lines.push(`- ${d}`);\n lines.push(\"\");\n lines.push(\"### Action Items\");\n for (const a of ext.actionItems) lines.push(`- ${a}`);\n lines.push(\"\");\n lines.push(\"### Rejected Ideas / Reversals\");\n for (const r of ext.rejected) lines.push(`- ${r}`);\n lines.push(\"\");\n if (meta && Object.keys(meta.toolCounts).length > 0) {\n lines.push(\"### Tools Used\");\n const top = Object.entries(meta.toolCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 12);\n for (const [name, count] of top) lines.push(`- ${name}: ${count}`);\n lines.push(\"\");\n }\n lines.push(\"### Stats\");\n lines.push(`- Turns: ${summary.turnCount}`);\n if (meta) {\n lines.push(`- User turns: ${meta.userTurns}`);\n lines.push(`- Assistant turns: ${meta.assistantTurns}`);\n lines.push(`- Tool calls: ${meta.toolCalls}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n\n for (const bullet of summary.bullets) lines.push(`- ${bullet}`);\n lines.push(` *(${summary.turnCount} turns)*`);\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n\n // Read recent summaries for recall injection\n async readRecent(sessionKey: string, hours: number): Promise<HourlySummary[]> {\n try {\n const cutoffTime = Date.now() - hours * 60 * 60 * 1000;\n\n const snapshot = await readSummarySnapshot(this.config.memoryDir, sessionKey);\n if (snapshot) {\n return snapshot\n .filter((s) => new Date(s.hour).getTime() >= cutoffTime)\n .sort((a, b) => new Date(b.hour).getTime() - new Date(a.hour).getTime());\n }\n\n const summaries: HourlySummary[] = [];\n const encodedDir = await this.summarySessionDir(sessionKey);\n const legacyDir = await this.legacySummarySessionDir(sessionKey);\n const seenDirs = new Set<string>();\n\n for (const sessionDir of [encodedDir, legacyDir]) {\n if (!sessionDir || seenDirs.has(sessionDir)) continue;\n seenDirs.add(sessionDir);\n const parsed = await this.readSummaryDir(sessionDir, sessionKey);\n summaries.push(...parsed);\n }\n\n const byHour = new Map<string, HourlySummary>();\n for (const summary of summaries) {\n if (!byHour.has(summary.hour)) byHour.set(summary.hour, summary);\n }\n\n const sortedSummaries = Array.from(byHour.values()).sort(\n (a, b) => new Date(b.hour).getTime() - new Date(a.hour).getTime(),\n );\n\n // Filter to recent hours while materializing the full parsed history.\n const recent = sortedSummaries.filter(\n (s) => new Date(s.hour).getTime() >= cutoffTime,\n );\n\n if (sortedSummaries.length > 0) {\n try {\n await writeSummarySnapshot(\n this.config.memoryDir,\n sessionKey,\n sortedSummaries,\n );\n } catch (error) {\n log.warn(\n `hourly summarizer: failed to materialize summary snapshot for ${sessionKey} (fail-open): ${String(error)}`,\n );\n }\n }\n\n return recent;\n } catch {\n // Directory doesn't exist or error reading\n return [];\n }\n }\n\n private async readSummaryDir(\n sessionDir: string,\n sessionKey: string,\n ): Promise<HourlySummary[]> {\n let files: string[];\n try {\n files = await readdir(sessionDir);\n } catch {\n return [];\n }\n\n const summaries: HourlySummary[] = [];\n const mdFiles = files.filter((f) => f.endsWith(\".md\"));\n for (const file of mdFiles) {\n const filePath = await resolveSafeStoragePath(sessionDir, file).catch(() => null);\n if (filePath === null) continue;\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n summaries.push(...this.parseSummaryFile(content, sessionKey, file));\n } catch {\n // Skip unreadable summary files.\n }\n }\n\n return summaries;\n }\n\n private parseSummaryFile(\n content: string,\n sessionKey: string,\n filename: string\n ): HourlySummary[] {\n const summaries: HourlySummary[] = [];\n\n // Extract date from filename (YYYY-MM-DD.md)\n const dateMatch = filename.match(/^(\\d{4}-\\d{2}-\\d{2})\\.md$/);\n if (!dateMatch) return summaries;\n const dateStr = dateMatch[1];\n\n // Split by hour sections\n const hourSections = content.split(/\\n## (\\d{2}):00\\n/);\n\n // First element is the header, skip it\n for (let i = 1; i < hourSections.length; i += 2) {\n const hourStr = hourSections[i];\n const sectionContent = hourSections[i + 1] || \"\";\n\n // Parse bullets\n const bullets: string[] = [];\n const lines = sectionContent.split(\"\\n\");\n let turnCount = 0;\n\n let inTopics = false;\n let sawExtendedTopicsHeader = false;\n for (const line of lines) {\n if (line.startsWith(\"### Topics\")) {\n inTopics = true;\n sawExtendedTopicsHeader = true;\n continue;\n }\n if (line.startsWith(\"### \") && !line.startsWith(\"### Topics\")) {\n inTopics = false;\n }\n const bulletMatch = line.match(/^- (.+)$/);\n if (bulletMatch) {\n // For extended format, only treat topic bullets as recall bullets.\n if (!sawExtendedTopicsHeader || inTopics) bullets.push(bulletMatch[1]);\n }\n const turnMatch = line.match(/\\((\\d+) turns?\\)/);\n if (turnMatch) turnCount = parseInt(turnMatch[1], 10);\n }\n\n if (bullets.length > 0) {\n summaries.push({\n hour: `${dateStr}T${hourStr}:00:00.000Z`,\n sessionKey,\n bullets,\n turnCount,\n generatedAt: \"\", // Not stored in file, not needed for recall\n });\n }\n }\n\n return summaries;\n }\n\n // Format summaries for recall injection\n formatForRecall(summaries: HourlySummary[], maxCount: number): string {\n if (summaries.length === 0) return \"\";\n\n const limited = summaries.slice(0, maxCount);\n const lines: string[] = [`## Recent Activity (last ${limited.length} hours)`];\n\n for (const summary of limited) {\n const hourStr = summary.hour.slice(11, 16); // HH:MM\n for (const bullet of summary.bullets) {\n lines.push(`- ${hourStr}: ${bullet}`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n // Main entry point for cron job\n async runHourly(): Promise<void> {\n log.debug(\"running hourly summary generation\");\n\n // Get active sessions from transcript\n const sessions = await this.getActiveSessions();\n\n for (const sessionKey of sessions) {\n // Calculate the hour we want to summarize (previous hour)\n const now = new Date();\n const hourStart = new Date(now.getTime() - 60 * 60 * 1000);\n hourStart.setMinutes(0, 0, 0);\n const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);\n\n // Get entries for this session in the target hour\n const entries = await this.getTranscriptEntries(sessionKey, hourStart, hourEnd);\n\n if (entries.length === 0) {\n log.debug(`no transcript entries for ${sessionKey} at ${hourStart.toISOString()}`);\n continue;\n }\n\n // Generate and save summary\n const summary = await this.generateSummary(sessionKey, hourStart, entries);\n if (summary) {\n await this.saveSummary(summary);\n log.info(`generated hourly summary for ${sessionKey} (${entries.length} turns)`);\n }\n }\n }\n\n // Get list of active sessions from transcript directory\n private async getActiveSessions(): Promise<string[]> {\n const transcriptDir = await resolveSafeStoragePath(\n this.config.memoryDir,\n \"transcripts\",\n ).catch(() => null);\n if (transcriptDir === null) return [];\n\n try {\n const sessionKeys = new Set<string>();\n const typeEntries = await readdir(transcriptDir, { withFileTypes: true });\n for (const typeEnt of typeEntries) {\n if (!typeEnt.isDirectory()) continue;\n const typeDir = await resolveSafeStoragePath(transcriptDir, typeEnt.name).catch(() => null);\n if (typeDir === null) continue;\n const idEntries = await readdir(typeDir, { withFileTypes: true });\n for (const idEnt of idEntries) {\n if (!idEnt.isDirectory()) continue;\n const chanDir = await resolveSafeStoragePath(typeDir, idEnt.name).catch(() => null);\n if (chanDir === null) continue;\n const files = (await readdir(chanDir)).filter((f) => f.endsWith(\".jsonl\")).sort();\n for (const file of files) {\n const transcriptPath = await resolveSafeStoragePath(chanDir, file).catch(() => null);\n if (transcriptPath === null) continue;\n await this.collectTranscriptSessionKeys(transcriptPath, sessionKeys);\n }\n }\n }\n return Array.from(sessionKeys);\n } catch {\n return [];\n }\n }\n\n private async collectTranscriptSessionKeys(\n transcriptPath: string,\n sessionKeys: Set<string>,\n ): Promise<void> {\n try {\n const raw = await readFile(transcriptPath, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n if (typeof entry.sessionKey === \"string\" && entry.sessionKey.length > 0) {\n sessionKeys.add(entry.sessionKey);\n }\n } catch {\n // ignore malformed transcript lines\n }\n }\n } catch {\n // ignore unreadable transcript files\n }\n }\n\n // Get transcript entries for a session within a time range\n private async getTranscriptEntries(\n sessionKey: string,\n startTime: Date,\n endTime: Date\n ): Promise<TranscriptEntry[]> {\n // Shared session-identity layer (issue #1496, rule #22). Arbitrary keys\n // route to `session/<hash>`; legacy `agent:<id>:...` keep their paths. The\n // shared helper also supplies the read-back-only candidate dirs (mirrors\n // TranscriptManager) so legacy `other/default` AND old `parts.length >= 3`\n // data stays discoverable here too.\n const paths = sessionStoragePaths(sessionKey);\n\n try {\n const transcriptRoot = path.join(this.config.memoryDir, \"transcripts\");\n const candidateDirs = new Set(\n [paths.dir, paths.alternateDir, paths.legacyDir, ...paths.readbackDirs].filter(\n (dir): dir is string => typeof dir === \"string\" && dir.length > 0,\n ),\n );\n const entries: TranscriptEntry[] = [];\n // Dedup identical raw rows that a partially-applied migration may have\n // left in both the primary dir and a read-back dir (issue #1496, cursor\n // review). Exact raw JSONL line is the stable identity.\n const seenRawLines = new Set<string>();\n\n // Read all daily transcript files in the directory\n for (const candidateDir of candidateDirs) {\n const transcriptDir = await resolveSafeStoragePath(transcriptRoot, candidateDir).catch(() => null);\n if (transcriptDir === null) continue;\n\n const files = await readdir(transcriptDir).catch(() => []);\n for (const file of files) {\n if (!file.endsWith(\".jsonl\")) continue;\n\n const transcriptPath = await resolveSafeStoragePath(transcriptDir, file).catch(() => null);\n if (transcriptPath === null) continue;\n\n try {\n const content = await readFile(transcriptPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\");\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n const entryTime = new Date(entry.timestamp).getTime();\n\n if (\n entry.sessionKey === sessionKey &&\n entryTime >= startTime.getTime() &&\n entryTime < endTime.getTime() &&\n !seenRawLines.has(line)\n ) {\n seenRawLines.add(line);\n entries.push(entry);\n }\n } catch {\n // Skip malformed lines\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return entries;\n } catch {\n return [];\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,WAAW,eAAe;AACpD,OAAO,UAAU;AACjB,SAAS,SAAS;AAiBlB,IAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,SAAS,EACN,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,EAC9B,IAAI,CAAC,EACL,SAAS,mDAAmD;AACjE,CAAC;AAID,IAAM,8BAA8B,EAAE,OAAO;AAAA,EAC3C,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACtC,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EACzC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA,EAC3C,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC1C,CAAC;AAWD,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEO,IAAM,mBAAN,MAAuB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,QAAsB,eAA+B,eAA+B,YAAgC;AAC9H,SAAK,SAAS;AACd,SAAK,eAAe,KAAK,KAAK,OAAO,WAAW,aAAa,QAAQ;AACrE,SAAK,gBAAgB,iBAAiB,IAAI,cAAc,OAAO,SAAS;AACxE,SAAK,aAAa;AAG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