nexus-agents 8.46.8 → 8.46.9
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/{ast-rule-runner-ENNFRPS4.js → ast-rule-runner-D3K4OWJR.js} +3 -3
- package/dist/{child-mcp-config-Q3HTTXMZ.js → child-mcp-config-KMFC3V5X.js} +2 -2
- package/dist/{chunk-NW4WPWZM.js → chunk-2MNXFMLO.js} +8 -8
- package/dist/{chunk-AZSKRFB7.js → chunk-2SEIMNKE.js} +4 -4
- package/dist/{chunk-2QWHJXZ6.js → chunk-3AWXED62.js} +2 -2
- package/dist/{chunk-ZUCCHUPM.js → chunk-43ONDTAK.js} +2 -2
- package/dist/{chunk-7RO52LJF.js → chunk-6X7QXBQW.js} +2 -2
- package/dist/{chunk-3IPZ5SPC.js → chunk-7MXQBY6W.js} +5 -5
- package/dist/{chunk-7YM5D4F2.js → chunk-DN7GLLIH.js} +3 -3
- package/dist/{chunk-RSLWBU7D.js → chunk-DNXPTQTA.js} +2 -2
- package/dist/{chunk-ATG4RSEH.js → chunk-E3JBFLMJ.js} +2 -2
- package/dist/{chunk-2KEKNZOO.js → chunk-EYXMTUKI.js} +2 -2
- package/dist/{chunk-AUF3SW7N.js → chunk-GW6NZFTH.js} +37 -37
- package/dist/{chunk-SGIR6SBV.js → chunk-H2AOFLQD.js} +2 -2
- package/dist/{chunk-A7RVICRW.js → chunk-K46JS3AR.js} +2 -2
- package/dist/{chunk-YUMC7FOS.js → chunk-KGRJIYNF.js} +5 -5
- package/dist/{chunk-SICXEQDA.js → chunk-KHCFW5LJ.js} +5 -5
- package/dist/{chunk-VP56PBMN.js → chunk-L655LBOK.js} +3 -3
- package/dist/{chunk-MIFCNJO6.js → chunk-M26JTGBL.js} +2 -2
- package/dist/{chunk-PMOHJXRA.js → chunk-MUJCGBZW.js} +25 -5
- package/dist/{chunk-PMOHJXRA.js.map → chunk-MUJCGBZW.js.map} +1 -1
- package/dist/{chunk-E5MTVRMV.js → chunk-MZ4X6UDA.js} +2 -2
- package/dist/{chunk-NM3KSTH7.js → chunk-NTK3UA6R.js} +2 -2
- package/dist/{chunk-JAUJ7PB4.js → chunk-PGMDJ7LH.js} +2 -2
- package/dist/{chunk-TIK6CIM3.js → chunk-PUGFOPEA.js} +9 -9
- package/dist/{chunk-3PZGFKO6.js → chunk-QGXQMRA7.js} +4 -4
- package/dist/{chunk-2LO5BVCH.js → chunk-QLF22ILR.js} +7 -7
- package/dist/{chunk-DMFWCAXB.js → chunk-R4QUX6Z5.js} +2 -2
- package/dist/{chunk-JKLGJMNL.js → chunk-RJRKVBLP.js} +3 -3
- package/dist/{chunk-FSBW2D6U.js → chunk-TDVAJEQL.js} +7 -7
- package/dist/{chunk-AKXXBJAP.js → chunk-TG4IGHLY.js} +2 -2
- package/dist/{chunk-RL3TZ4Y3.js → chunk-U44T6PAZ.js} +6 -6
- package/dist/{chunk-KI4OIDBV.js → chunk-UTV7RU6C.js} +4 -4
- package/dist/{chunk-HPH77QTD.js → chunk-VJFBC4YA.js} +2 -2
- package/dist/{chunk-QMZWUJ2I.js → chunk-WYZEHUME.js} +2 -2
- package/dist/{chunk-NDH6MQMM.js → chunk-YGJRO5JK.js} +6 -6
- package/dist/{chunk-SEDQA6N5.js → chunk-YO6PT4CN.js} +2 -2
- package/dist/{chunk-KTLNUNDU.js → chunk-YRVMNMH5.js} +2 -2
- package/dist/{chunk-I2NOD7GW.js → chunk-ZS6D7W74.js} +2 -2
- package/dist/{cli-circuit-breaker-43R3IQPV.js → cli-circuit-breaker-TXONSAMR.js} +3 -3
- package/dist/cli.js +45 -45
- package/dist/{composite-router-DT5FHIOJ.js → composite-router-AXNQ4JGW.js} +2 -2
- package/dist/{consensus-vote-NUIRYYT2.js → consensus-vote-LQZKNJ3N.js} +19 -19
- package/dist/{context-retriever-4VEN5UT3.js → context-retriever-GJDSNXZL.js} +10 -10
- package/dist/{dist-SAZAWYVP.js → dist-U4WS2A7E.js} +2 -2
- package/dist/{doctor-deep-Z4MGK2BP.js → doctor-deep-236PS5U3.js} +3 -3
- package/dist/{doctor-live-UGUWXT6Z.js → doctor-live-AUWLABYR.js} +9 -9
- package/dist/{expert-bridge-C42WPTF6.js → expert-bridge-RWAYSGUI.js} +4 -4
- package/dist/{factory-UA5DZGHC.js → factory-4EVXLY6D.js} +5 -5
- package/dist/{factory-NASBYAKW.js → factory-EBTRU3DD.js} +9 -9
- package/dist/{improvement-review-LIH53JRG.js → improvement-review-GWUZTT3L.js} +6 -6
- package/dist/index.js +33 -33
- package/dist/{init-opencode-UTZY6BYY.js → init-opencode-M5QMSO7O.js} +6 -6
- package/dist/issue-triage-PGNKV4I4.js +17 -0
- package/dist/{pr-reviewer-helpers-LQSGP46N.js → pr-reviewer-helpers-ASQN222W.js} +4 -4
- package/dist/{registry-command-AWBOBXU2.js → registry-command-OUGKDRCJ.js} +2 -2
- package/dist/{repo-security-plan-TQVUCCQR.js → repo-security-plan-4B57KH55.js} +3 -3
- package/dist/{research-helpers-synthesize-YABA2P4Q.js → research-helpers-synthesize-4D5HY3EF.js} +4 -4
- package/dist/{routing-memory-MWZHQWDB.js → routing-memory-GIOIGCYG.js} +2 -2
- package/dist/{session-memory-QKWYDORW.js → session-memory-GGHAN5SF.js} +3 -3
- package/dist/{setup-config-VFHABXQ6.js → setup-config-H2NNVJSV.js} +3 -3
- package/dist/{setup-custom-api-BXJHOOPR.js → setup-custom-api-YWLWUGDE.js} +4 -4
- package/dist/setup-data-dir-GW2NJ3YM.js +29 -0
- package/dist/{tool-memory-B5F2ZYR2.js → tool-memory-LIYTSR4V.js} +7 -7
- package/dist/{tool-memory-registry-adapters-TP6U27K3.js → tool-memory-registry-adapters-ATMDGO4D.js} +3 -3
- package/dist/{unified-registry-OBDYGBM6.js → unified-registry-VGIJ3TSU.js} +10 -10
- package/dist/{weather-report-XEYT7LOW.js → weather-report-UULZVM7C.js} +2 -2
- package/package.json +1 -1
- package/dist/issue-triage-PTD5H4PZ.js +0 -17
- package/dist/setup-data-dir-MTRHL4TC.js +0 -29
- /package/dist/{ast-rule-runner-ENNFRPS4.js.map → ast-rule-runner-D3K4OWJR.js.map} +0 -0
- /package/dist/{child-mcp-config-Q3HTTXMZ.js.map → child-mcp-config-KMFC3V5X.js.map} +0 -0
- /package/dist/{chunk-NW4WPWZM.js.map → chunk-2MNXFMLO.js.map} +0 -0
- /package/dist/{chunk-AZSKRFB7.js.map → chunk-2SEIMNKE.js.map} +0 -0
- /package/dist/{chunk-2QWHJXZ6.js.map → chunk-3AWXED62.js.map} +0 -0
- /package/dist/{chunk-ZUCCHUPM.js.map → chunk-43ONDTAK.js.map} +0 -0
- /package/dist/{chunk-7RO52LJF.js.map → chunk-6X7QXBQW.js.map} +0 -0
- /package/dist/{chunk-3IPZ5SPC.js.map → chunk-7MXQBY6W.js.map} +0 -0
- /package/dist/{chunk-7YM5D4F2.js.map → chunk-DN7GLLIH.js.map} +0 -0
- /package/dist/{chunk-RSLWBU7D.js.map → chunk-DNXPTQTA.js.map} +0 -0
- /package/dist/{chunk-ATG4RSEH.js.map → chunk-E3JBFLMJ.js.map} +0 -0
- /package/dist/{chunk-2KEKNZOO.js.map → chunk-EYXMTUKI.js.map} +0 -0
- /package/dist/{chunk-AUF3SW7N.js.map → chunk-GW6NZFTH.js.map} +0 -0
- /package/dist/{chunk-SGIR6SBV.js.map → chunk-H2AOFLQD.js.map} +0 -0
- /package/dist/{chunk-A7RVICRW.js.map → chunk-K46JS3AR.js.map} +0 -0
- /package/dist/{chunk-YUMC7FOS.js.map → chunk-KGRJIYNF.js.map} +0 -0
- /package/dist/{chunk-SICXEQDA.js.map → chunk-KHCFW5LJ.js.map} +0 -0
- /package/dist/{chunk-VP56PBMN.js.map → chunk-L655LBOK.js.map} +0 -0
- /package/dist/{chunk-MIFCNJO6.js.map → chunk-M26JTGBL.js.map} +0 -0
- /package/dist/{chunk-E5MTVRMV.js.map → chunk-MZ4X6UDA.js.map} +0 -0
- /package/dist/{chunk-NM3KSTH7.js.map → chunk-NTK3UA6R.js.map} +0 -0
- /package/dist/{chunk-JAUJ7PB4.js.map → chunk-PGMDJ7LH.js.map} +0 -0
- /package/dist/{chunk-TIK6CIM3.js.map → chunk-PUGFOPEA.js.map} +0 -0
- /package/dist/{chunk-3PZGFKO6.js.map → chunk-QGXQMRA7.js.map} +0 -0
- /package/dist/{chunk-2LO5BVCH.js.map → chunk-QLF22ILR.js.map} +0 -0
- /package/dist/{chunk-DMFWCAXB.js.map → chunk-R4QUX6Z5.js.map} +0 -0
- /package/dist/{chunk-JKLGJMNL.js.map → chunk-RJRKVBLP.js.map} +0 -0
- /package/dist/{chunk-FSBW2D6U.js.map → chunk-TDVAJEQL.js.map} +0 -0
- /package/dist/{chunk-AKXXBJAP.js.map → chunk-TG4IGHLY.js.map} +0 -0
- /package/dist/{chunk-RL3TZ4Y3.js.map → chunk-U44T6PAZ.js.map} +0 -0
- /package/dist/{chunk-KI4OIDBV.js.map → chunk-UTV7RU6C.js.map} +0 -0
- /package/dist/{chunk-HPH77QTD.js.map → chunk-VJFBC4YA.js.map} +0 -0
- /package/dist/{chunk-QMZWUJ2I.js.map → chunk-WYZEHUME.js.map} +0 -0
- /package/dist/{chunk-NDH6MQMM.js.map → chunk-YGJRO5JK.js.map} +0 -0
- /package/dist/{chunk-SEDQA6N5.js.map → chunk-YO6PT4CN.js.map} +0 -0
- /package/dist/{chunk-KTLNUNDU.js.map → chunk-YRVMNMH5.js.map} +0 -0
- /package/dist/{chunk-I2NOD7GW.js.map → chunk-ZS6D7W74.js.map} +0 -0
- /package/dist/{cli-circuit-breaker-43R3IQPV.js.map → cli-circuit-breaker-TXONSAMR.js.map} +0 -0
- /package/dist/{composite-router-DT5FHIOJ.js.map → composite-router-AXNQ4JGW.js.map} +0 -0
- /package/dist/{consensus-vote-NUIRYYT2.js.map → consensus-vote-LQZKNJ3N.js.map} +0 -0
- /package/dist/{context-retriever-4VEN5UT3.js.map → context-retriever-GJDSNXZL.js.map} +0 -0
- /package/dist/{dist-SAZAWYVP.js.map → dist-U4WS2A7E.js.map} +0 -0
- /package/dist/{doctor-deep-Z4MGK2BP.js.map → doctor-deep-236PS5U3.js.map} +0 -0
- /package/dist/{doctor-live-UGUWXT6Z.js.map → doctor-live-AUWLABYR.js.map} +0 -0
- /package/dist/{expert-bridge-C42WPTF6.js.map → expert-bridge-RWAYSGUI.js.map} +0 -0
- /package/dist/{factory-NASBYAKW.js.map → factory-4EVXLY6D.js.map} +0 -0
- /package/dist/{factory-UA5DZGHC.js.map → factory-EBTRU3DD.js.map} +0 -0
- /package/dist/{improvement-review-LIH53JRG.js.map → improvement-review-GWUZTT3L.js.map} +0 -0
- /package/dist/{init-opencode-UTZY6BYY.js.map → init-opencode-M5QMSO7O.js.map} +0 -0
- /package/dist/{issue-triage-PTD5H4PZ.js.map → issue-triage-PGNKV4I4.js.map} +0 -0
- /package/dist/{pr-reviewer-helpers-LQSGP46N.js.map → pr-reviewer-helpers-ASQN222W.js.map} +0 -0
- /package/dist/{registry-command-AWBOBXU2.js.map → registry-command-OUGKDRCJ.js.map} +0 -0
- /package/dist/{repo-security-plan-TQVUCCQR.js.map → repo-security-plan-4B57KH55.js.map} +0 -0
- /package/dist/{research-helpers-synthesize-YABA2P4Q.js.map → research-helpers-synthesize-4D5HY3EF.js.map} +0 -0
- /package/dist/{routing-memory-MWZHQWDB.js.map → routing-memory-GIOIGCYG.js.map} +0 -0
- /package/dist/{session-memory-QKWYDORW.js.map → session-memory-GGHAN5SF.js.map} +0 -0
- /package/dist/{setup-config-VFHABXQ6.js.map → setup-config-H2NNVJSV.js.map} +0 -0
- /package/dist/{setup-custom-api-BXJHOOPR.js.map → setup-custom-api-YWLWUGDE.js.map} +0 -0
- /package/dist/{setup-data-dir-MTRHL4TC.js.map → setup-data-dir-GW2NJ3YM.js.map} +0 -0
- /package/dist/{tool-memory-B5F2ZYR2.js.map → tool-memory-LIYTSR4V.js.map} +0 -0
- /package/dist/{tool-memory-registry-adapters-TP6U27K3.js.map → tool-memory-registry-adapters-ATMDGO4D.js.map} +0 -0
- /package/dist/{unified-registry-OBDYGBM6.js.map → unified-registry-VGIJ3TSU.js.map} +0 -0
- /package/dist/{weather-report-XEYT7LOW.js.map → weather-report-UULZVM7C.js.map} +0 -0
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
MemoryRegistry,
|
|
3
3
|
hasMemoryRegistry,
|
|
4
4
|
setMemoryRegistry
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-MUJCGBZW.js";
|
|
6
6
|
import {
|
|
7
7
|
nexusDataPath
|
|
8
8
|
} from "./chunk-BTYRPZON.js";
|
|
@@ -93,4 +93,4 @@ export {
|
|
|
93
93
|
StatsOnlyAdapter,
|
|
94
94
|
ensureSharedMemoryRegistry
|
|
95
95
|
};
|
|
96
|
-
//# sourceMappingURL=chunk-
|
|
96
|
+
//# sourceMappingURL=chunk-M26JTGBL.js.map
|
|
@@ -670,15 +670,35 @@ var MemoryRegistry = class {
|
|
|
670
670
|
/**
|
|
671
671
|
* Close every registered backend and the shared SQLite handle. After
|
|
672
672
|
* `close()` the registry rejects all further operations.
|
|
673
|
+
*
|
|
674
|
+
* Idempotent only once it has actually SUCCEEDED (#5776). It used to set
|
|
675
|
+
* `this.closed = true` before the loop and `await` each backend in turn, so
|
|
676
|
+
* one rejecting backend aborted the loop: every backend after it stayed open,
|
|
677
|
+
* `this.backends` was never cleared, and the shared SQLite handle — the one
|
|
678
|
+
* thing the registry itself owns — never closed. The retry a shutdown path
|
|
679
|
+
* would naturally make then hit `if (this.closed) return` and RESOLVED,
|
|
680
|
+
* reporting success for a close that never happened.
|
|
681
|
+
*
|
|
682
|
+
* Now every backend is attempted (`allSettled`), the owned handle closes
|
|
683
|
+
* regardless, and the registry IS marked closed — because by then everything
|
|
684
|
+
* it owns really is shut — but the first backend failure is re-thrown so the
|
|
685
|
+
* caller learns about it. A retry then returns early and resolves, which is
|
|
686
|
+
* honest: there is genuinely nothing left to close. Marking it open instead
|
|
687
|
+
* would be worse than the original bug — `assertOpen` would pass and the next
|
|
688
|
+
* operation would run against a closed SQLite handle.
|
|
673
689
|
*/
|
|
674
690
|
async close() {
|
|
675
691
|
if (this.closed) return;
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
}
|
|
692
|
+
const results = await Promise.allSettled(
|
|
693
|
+
[...this.backends.values()].map((backend) => backend.close())
|
|
694
|
+
);
|
|
680
695
|
this.backends.clear();
|
|
681
696
|
if (this.db !== void 0) this.db.close();
|
|
697
|
+
this.closed = true;
|
|
698
|
+
const failures = results.filter((r) => r.status === "rejected");
|
|
699
|
+
if (failures.length > 0) {
|
|
700
|
+
throw failures[0]?.reason instanceof Error ? failures[0].reason : new Error(`nexus-memory: ${String(failures.length)} backend(s) failed to close`);
|
|
701
|
+
}
|
|
682
702
|
}
|
|
683
703
|
assertOpen() {
|
|
684
704
|
if (this.closed) {
|
|
@@ -784,4 +804,4 @@ export {
|
|
|
784
804
|
runImporters,
|
|
785
805
|
backupSourceFile
|
|
786
806
|
};
|
|
787
|
-
//# sourceMappingURL=chunk-
|
|
807
|
+
//# sourceMappingURL=chunk-MUJCGBZW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../nexus-memory/src/telemetry.ts","../../nexus-memory/src/backends/memory.ts","../../nexus-memory/src/backends/open-database.ts","../../nexus-memory/src/backends/sqlite.ts","../../nexus-memory/src/registry.ts","../../nexus-memory/src/factory.ts","../../nexus-memory/src/importer.ts"],"sourcesContent":["/**\n * Memory telemetry — aggregated counters (default) + opt-in full-audit mode.\n *\n * Phase 2 vote (#2768) settled on **C**: per-`{domain, op}` counters in\n * steady state, full per-event payloads when `NEXUS_MEMORY_AUDIT_MODE=audit`.\n *\n * The catfish-mitigation requirement is honored: audit mode emits\n * `{ op, keySummary, payloadSummary, resultSummary, cli, durationMs, hit }`\n * — not just counters — so an incident replay can reconstruct individual\n * ops. Summaries are truncated to keep emission cheap.\n *\n * @module nexus-memory/telemetry\n */\n\nimport type { CliName, MemoryEvent, MemoryEventCounters, MemoryEventListener } from './types.js';\n\nconst KEY_SUMMARY_LIMIT = 120;\nconst PAYLOAD_SUMMARY_LIMIT = 240;\n\n/** Per-`{domain, op}` rolling counters. */\nconst counters = new Map<string, MemoryEventCounters>();\nconst listeners = new Set<MemoryEventListener>();\n\n/** Audit mode is opt-in via env. Checked once per emission so the env\n * can be toggled at runtime by tests via `process.env`. */\nfunction isAuditMode(): boolean {\n return process.env['NEXUS_MEMORY_AUDIT_MODE'] === 'audit';\n}\n\nfunction counterKey(domain: string, op: MemoryEvent['op']): string {\n return `${domain}::${op}`;\n}\n\nfunction truncate(value: unknown, limit: number): string {\n let s: string;\n if (typeof value === 'string') {\n s = value;\n } else if (value === undefined) {\n s = '<undefined>';\n } else if (value === null) {\n s = '<null>';\n } else {\n try {\n s = JSON.stringify(value);\n } catch {\n s = '<unserializable>';\n }\n }\n return s.length > limit ? `${s.slice(0, limit - 1)}…` : s;\n}\n\ninterface RecordedEvent extends Omit<\n MemoryEvent,\n 'keySummary' | 'payloadSummary' | 'resultSummary'\n> {\n readonly key?: unknown;\n readonly payload?: unknown;\n readonly result?: unknown;\n}\n\n/** The zero row a domain/op starts from — every field named, none defaulted implicitly. */\nfunction emptyCounter(domain: string, op: MemoryEvent['op']): MemoryEventCounters {\n return { domain, op, count: 0, errorCount: 0, hitCount: 0, totalDurationMs: 0, maxDurationMs: 0 };\n}\n\nfunction updateCounter(event: RecordedEvent): void {\n const ck = counterKey(event.domain, event.op);\n const prev = counters.get(ck) ?? emptyCounter(event.domain, event.op);\n counters.set(ck, {\n domain: prev.domain,\n op: prev.op,\n count: prev.count + 1,\n errorCount: prev.errorCount + (event.error !== undefined ? 1 : 0),\n hitCount: prev.hitCount + (event.hit === true ? 1 : 0),\n totalDurationMs: prev.totalDurationMs + event.durationMs,\n maxDurationMs: Math.max(prev.maxDurationMs, event.durationMs),\n });\n}\n\nfunction buildPublicEvent(event: RecordedEvent, audit: boolean): MemoryEvent {\n return {\n domain: event.domain,\n op: event.op,\n durationMs: event.durationMs,\n // #5965: without this the counter records a failure the subscriber never\n // sees — two instruments disagreeing about the same operation.\n ...(event.error !== undefined && { error: event.error }),\n ...(event.cli !== undefined && { cli: event.cli }),\n ...(event.hit !== undefined && { hit: event.hit }),\n ...(audit &&\n event.key !== undefined && {\n keySummary: truncate(event.key, KEY_SUMMARY_LIMIT),\n }),\n ...(audit &&\n event.payload !== undefined && {\n payloadSummary: truncate(event.payload, PAYLOAD_SUMMARY_LIMIT),\n }),\n ...(audit &&\n event.result !== undefined && {\n resultSummary: truncate(event.result, PAYLOAD_SUMMARY_LIMIT),\n }),\n };\n}\n\n/**\n * Record a memory operation, successful or not. Updates counters always;\n * emits the event to subscribers always (subscribers get the full event in\n * audit mode, the aggregate-only event otherwise).\n *\n * \"Always\" is load-bearing and was not true until #5965: every backend called\n * this AFTER the work, so a throw skipped it entirely.\n *\n * Implementation note: the `op` argument is the typed `MemoryEvent['op']`\n * literal — backends never pass an unknown string here.\n */\nexport function recordMemoryEvent(event: RecordedEvent): void {\n updateCounter(event);\n const publicEvent = buildPublicEvent(event, isAuditMode());\n for (const listener of listeners) {\n try {\n listener(publicEvent);\n } catch {\n // Subscriber failures must never affect memory operations.\n }\n }\n}\n\n/** Snapshot of current counters. Returned array is a copy. */\nexport function getMemoryEventCounters(): readonly MemoryEventCounters[] {\n return [...counters.values()];\n}\n\n/** Subscribe to the per-event stream. Returns an unsubscribe function. */\nexport function subscribeToMemoryEvents(listener: MemoryEventListener): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * Reset counters + drop all subscribers. Tests should call this in\n * `beforeEach` to keep state from leaking.\n */\nexport function resetMemoryTelemetry(): void {\n counters.clear();\n listeners.clear();\n}\n\n/**\n * Runs one backend operation and records it even when it throws (#5965).\n *\n * The record call used to sit after the work, so a `MemoryValidationError`, a\n * SQLite constraint or disk error, or a call on a closed backend produced no\n * event and no counter row at all — a domain rejecting every write looked\n * exactly like a domain nobody was using. The event is emitted BEFORE the\n * error is re-thrown, so the caller's own error handling is unchanged.\n *\n * The success event stays at each call site: only the caller knows the `hit`,\n * `key`, `payload` and `result` a successful op should carry.\n */\nexport function recordFailedMemoryOp<T>(\n context: { readonly domain: string; readonly op: MemoryEvent['op']; readonly cli?: CliName },\n start: number,\n body: () => T\n): T {\n try {\n return body();\n } catch (error) {\n recordMemoryEvent({\n domain: context.domain,\n op: context.op,\n ...(context.cli !== undefined && { cli: context.cli }),\n durationMs: Date.now() - start,\n // Message only — a validation error's detail can quote the value that\n // failed, and that value is caller payload.\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n}\n","/**\n * In-memory backend — primarily for tests, but also used as the cold-archive\n * fallback when no `dbPath` is provided.\n *\n * Implements {@link IMemoryBackend}; passes the same contract test as\n * {@link SqliteBackend}.\n *\n * @module nexus-memory/backends/memory\n */\n\nimport type { z } from 'zod';\nimport { recordFailedMemoryOp, recordMemoryEvent } from '../telemetry.js';\nimport type { BackendStats, IMemoryBackend, QueryFilter, WriteMeta } from '../types.js';\n\ninterface Row<TValue> {\n readonly value: TValue;\n readonly cli?: string;\n readonly source?: string;\n readonly timestamp: number;\n readonly trustTier?: 1 | 2 | 3 | 4;\n}\n\nexport interface InMemoryBackendOptions<TValue> {\n readonly domain: string;\n /**\n * Optional Zod schema. Phase 2 vote mitigation #1 (security dissent):\n * when supplied, every `write()` validates the value first; invalid\n * payloads throw `MemoryValidationError`.\n */\n readonly schema?: z.ZodType<TValue>;\n}\n\nexport class MemoryValidationError extends Error {\n constructor(domain: string, cause: unknown) {\n super(`nexus-memory: write rejected for domain \"${domain}\": ${String(cause)}`);\n this.name = 'MemoryValidationError';\n }\n}\n\nfunction buildInMemoryRow<TValue>(value: TValue, meta: WriteMeta | undefined): Row<TValue> {\n return {\n value,\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n ...(meta?.source !== undefined && { source: meta.source }),\n timestamp: meta?.timestamp ?? Date.now(),\n ...(meta?.trustTier !== undefined && { trustTier: meta.trustTier }),\n };\n}\n\n/** Apply `where`, `orderBy`, `limit` to an in-memory row set. Extracted from\n * `query` to satisfy the eslint complexity gate. */\nfunction applyInMemoryFilter<T>(values: T[], filter?: QueryFilter<T>): T[] {\n let out = values;\n if (filter?.where !== undefined) {\n const where = filter.where;\n out = out.filter((v) => {\n for (const [k, expected] of Object.entries(where)) {\n if ((v as Record<string, unknown>)[k] !== expected) return false;\n }\n return true;\n });\n }\n if (filter?.orderBy !== undefined) {\n const orderBy = filter.orderBy;\n const dir = filter.orderDir === 'desc' ? -1 : 1;\n out = [...out].sort((a, b) => {\n const av = (a as Record<string | symbol | number, unknown>)[orderBy];\n const bv = (b as Record<string | symbol | number, unknown>)[orderBy];\n if (av === bv) return 0;\n if (av === undefined || av === null) return 1;\n if (bv === undefined || bv === null) return -1;\n return (av < bv ? -1 : 1) * dir;\n });\n }\n if (filter?.limit !== undefined) {\n out = out.slice(0, filter.limit);\n }\n return out;\n}\n\nexport class InMemoryBackend<TKey, TValue> implements IMemoryBackend<TKey, TValue> {\n readonly domain: string;\n private readonly rows = new Map<TKey, Row<TValue>>();\n private readonly schema?: z.ZodType<TValue>;\n private closed = false;\n\n constructor(options: InMemoryBackendOptions<TValue>) {\n this.domain = options.domain;\n if (options.schema !== undefined) {\n this.schema = options.schema;\n }\n }\n\n async read(key: TKey): Promise<TValue | undefined> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'read',\n },\n start,\n () => {\n this.assertOpen();\n const row = this.rows.get(key);\n recordMemoryEvent({\n domain: this.domain,\n op: 'read',\n hit: row !== undefined,\n durationMs: Date.now() - start,\n key,\n result: row?.value,\n });\n return Promise.resolve(row?.value);\n }\n );\n }\n\n private validate(value: TValue): void {\n // #4021: reject `undefined` uniformly (before the optional schema check) so\n // both backends behave identically. Previously this backend stored a phantom\n // row for `write(key, undefined)` while SqliteBackend threw a cryptic NOT NULL\n // bind error — a contract divergence. `undefined` is the missing-key sentinel\n // `read` returns; an explicit `undefined` write is a caller bug — use `null`.\n if (value === undefined) {\n throw new MemoryValidationError(this.domain, 'value must not be undefined (use null)');\n }\n if (this.schema === undefined) return;\n const result = this.schema.safeParse(value);\n if (!result.success) {\n throw new MemoryValidationError(this.domain, result.error);\n }\n }\n\n async write(key: TKey, value: TValue, meta?: WriteMeta): Promise<void> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n },\n start,\n () => {\n this.assertOpen();\n this.validate(value);\n this.rows.set(key, buildInMemoryRow(value, meta));\n recordMemoryEvent({\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n durationMs: Date.now() - start,\n key,\n payload: value,\n });\n return Promise.resolve();\n }\n );\n }\n\n async query(filter?: QueryFilter<TValue>): Promise<readonly TValue[]> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'query',\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n },\n start,\n () => {\n this.assertOpen();\n let rows = [...this.rows.values()];\n if (filter?.cli !== undefined) {\n rows = rows.filter((r) => r.cli === filter.cli);\n }\n const values = applyInMemoryFilter(\n rows.map((r) => r.value),\n filter\n );\n recordMemoryEvent({\n domain: this.domain,\n op: 'query',\n hit: values.length > 0,\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n durationMs: Date.now() - start,\n key: filter,\n result: { count: values.length },\n });\n return Promise.resolve(values);\n }\n );\n }\n\n async delete(key: TKey): Promise<boolean> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'delete',\n },\n start,\n () => {\n this.assertOpen();\n const removed = this.rows.delete(key);\n recordMemoryEvent({\n domain: this.domain,\n op: 'delete',\n hit: removed,\n durationMs: Date.now() - start,\n key,\n });\n return Promise.resolve(removed);\n }\n );\n }\n\n async stats(): Promise<BackendStats> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'stats',\n },\n start,\n () => {\n this.assertOpen();\n const timestamps = [...this.rows.values()].map((r) => r.timestamp);\n const result: BackendStats = {\n domain: this.domain,\n count: this.rows.size,\n oldestTimestamp: timestamps.length > 0 ? Math.min(...timestamps) : null,\n newestTimestamp: timestamps.length > 0 ? Math.max(...timestamps) : null,\n };\n recordMemoryEvent({\n domain: this.domain,\n op: 'stats',\n durationMs: Date.now() - start,\n result,\n });\n return Promise.resolve(result);\n }\n );\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.rows.clear();\n return Promise.resolve();\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(`nexus-memory: backend \"${this.domain}\" is closed`);\n }\n }\n}\n","/**\n * Shared helper for opening a SQLite connection on disk.\n *\n * Centralizes the two pre-#3995 concerns that were duplicated at every\n * `new Database(dbPath)` site in this package:\n *\n * 1. **Auto-create the parent directory.** SQLite throws\n * `SQLITE_CANTOPEN` when the parent directory of `dbPath` does not exist\n * (the classic fresh-install regression — the resolver hands back a path\n * under `~/.nexus-agents/memory/` that nobody has created yet). We\n * `mkdirSync(dirname(dbPath), { recursive: true })` first so opening the\n * DB never throws merely because the directory is missing. `:memory:`\n * (and the empty string) are pure in-memory handles with no parent dir, so\n * they skip the mkdir.\n * 2. **WAL journal mode.** Keeps concurrent MCP-server + CLI readers coherent.\n *\n * Kept dep-free on purpose: nexus-memory must stay free of inter-package\n * imports so `nexus-eval-*` repos can reuse it. The canonical\n * `nexusDataPath` resolver lives in nexus-agents and injects the path here as\n * a plain string (see `getMemoryRegistry` wiring in nexus-agents). This helper\n * only guarantees that whatever absolute path it is handed is openable.\n *\n * @module nexus-memory/backends/open-database\n */\n\nimport { createRequire } from 'node:module';\n\n/**\n * Loaded through `createRequire`, not a static import (#5392).\n *\n * A static `import ... from 'node:sqlite'` is HOISTED by the bundler to the top\n * of the emitted chunk, so it evaluates before any consumer code can run. Node\n * emits the SQLite `ExperimentalWarning` at IMPORT time, so that ordering made\n * the CLI's warning filter unable to fire at all. `createRequire` keeps the load\n * synchronous — which is why node:sqlite was chosen — while deferring it to\n * first call. Node caches the module, so repeat calls are free.\n */\nconst requireFromHere = createRequire(import.meta.url);\n\nfunction loadSqlite(): typeof import('node:sqlite') {\n return requireFromHere('node:sqlite') as typeof import('node:sqlite');\n}\n\n/**\n * Result of running a prepared statement. Mirrors what both `node:sqlite` and\n * better-sqlite3 return, so consumers did not have to change (#5388).\n */\nexport interface SqliteRunResult {\n readonly changes: number | bigint;\n readonly lastInsertRowid: number | bigint;\n}\n\n/** Minimal prepared-statement surface this package actually uses. */\nexport interface SqliteStatement {\n run(...params: unknown[]): SqliteRunResult;\n get(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n}\n\n/**\n * Minimal database surface this package actually uses.\n *\n * Declared locally rather than imported: nexus-memory stays free of\n * inter-package imports so `nexus-eval-*` repos can reuse it, and since #5388\n * there is no dependency to import a type FROM — `node:sqlite` is a builtin.\n */\nexport interface SqliteDatabase {\n exec(sql: string): void;\n prepare(sql: string): SqliteStatement;\n close(): void;\n}\nimport { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\n/**\n * Open a SQLite database at `dbPath`, creating the parent directory\n * first (for on-disk paths) and enabling WAL journal mode.\n *\n * @param dbPath Absolute SQLite file path, or `':memory:'` / `''` for an\n * in-memory database (no directory is created in that case).\n */\nexport function openSqliteDatabase(dbPath: string): SqliteDatabase {\n if (dbPath !== ':memory:' && dbPath !== '') {\n // Fresh-install robustness (#3995): opening under a missing parent throws SQLITE_CANTOPEN\n // when the parent dir is missing. Create it up front, idempotently.\n mkdirSync(dirname(dbPath), { recursive: true });\n }\n const { DatabaseSync } = loadSqlite();\n const db = new DatabaseSync(dbPath);\n // `node:sqlite` has no `.pragma()` helper, so WAL goes through `exec`.\n db.exec('PRAGMA journal_mode = WAL');\n\n const narrowed = db as unknown as SqliteDatabase;\n return {\n exec: (sql: string) => {\n db.exec(sql);\n },\n prepare: narrowed.prepare.bind(narrowed),\n // better-sqlite3's `close()` is idempotent; `DatabaseSync`'s throws\n // `database is not open` on a second call, and shutdown paths here are\n // reentrant. Preserve the contract callers were written against (#5388).\n close: () => {\n if (db.isOpen) db.close();\n },\n };\n}\n","/**\n * SQLite backend — async wrapper over `node:sqlite` (which is sync).\n *\n * One table per domain (Phase 2 vote shape C, hot-table side). The schema\n * is intentionally minimal: `key`, `value` (JSON-serialized), `cli`,\n * `source`, `timestamp`, `trust_tier`. Hot-path backends extending this\n * will add typed columns and indexes for query performance.\n *\n * Async surface: every method returns `Promise<T>` so we can swap in a\n * network-backed implementation later without changing callers. The\n * actual SQLite ops are sync inside.\n *\n * @module nexus-memory/backends/sqlite\n */\n\nimport type {\n SqliteDatabase as DatabaseType,\n SqliteStatement as Statement,\n} from './open-database.js';\nimport type { z } from 'zod';\nimport { recordFailedMemoryOp, recordMemoryEvent } from '../telemetry.js';\nimport type { BackendStats, IMemoryBackend, QueryFilter, WriteMeta } from '../types.js';\nimport { MemoryValidationError } from './memory.js';\nimport { openSqliteDatabase } from './open-database.js';\n\nexport interface SqliteBackendOptions<TValue> {\n readonly domain: string;\n /** Absolute path to the SQLite file. Use `':memory:'` for tests. */\n readonly dbPath: string;\n /**\n * Zod schema for cold-archive validation (Phase 2 vote mitigation #1).\n * When supplied, every `write()` validates first.\n */\n readonly schema?: z.ZodType<TValue>;\n /** Pre-existing database handle. Used by `MemoryRegistry` to share a single connection. */\n readonly db?: DatabaseType;\n}\n\ninterface SqliteRow {\n readonly key: string;\n readonly value: string;\n readonly cli: string | null;\n readonly source: string | null;\n readonly timestamp: number;\n readonly trust_tier: number | null;\n}\n\nfunction buildWriteRow(\n key: unknown,\n value: unknown,\n meta: WriteMeta | undefined\n): Record<string, string | number | null> {\n return {\n key: keyToString(key),\n value: JSON.stringify(value),\n cli: meta?.cli ?? null,\n source: meta?.source ?? null,\n timestamp: meta?.timestamp ?? Date.now(),\n trust_tier: meta?.trustTier ?? null,\n };\n}\n\n/** Stringify a key so SQLite primary-key lookups stay simple. */\nfunction keyToString(key: unknown): string {\n if (typeof key === 'string') return key;\n if (typeof key === 'number' || typeof key === 'boolean') return String(key);\n return JSON.stringify(key);\n}\n\n/** Apply `where`, `orderBy`, `limit` to an in-memory row set. Extracted from\n * `query` to satisfy the eslint complexity gate. */\nfunction applyQueryFilter<T>(values: T[], filter?: QueryFilter<T>): T[] {\n let out = values;\n if (filter?.where !== undefined) {\n const where = filter.where;\n out = out.filter((v) => {\n for (const [k, expected] of Object.entries(where)) {\n if ((v as Record<string, unknown>)[k] !== expected) return false;\n }\n return true;\n });\n }\n if (filter?.orderBy !== undefined) {\n const orderBy = filter.orderBy;\n const dir = filter.orderDir === 'desc' ? -1 : 1;\n out = [...out].sort((a, b) => {\n const av = (a as Record<string | symbol | number, unknown>)[orderBy];\n const bv = (b as Record<string | symbol | number, unknown>)[orderBy];\n if (av === bv) return 0;\n if (av === undefined || av === null) return 1;\n if (bv === undefined || bv === null) return -1;\n return (av < bv ? -1 : 1) * dir;\n });\n }\n if (filter?.limit !== undefined) {\n out = out.slice(0, filter.limit);\n }\n return out;\n}\n\nexport class SqliteBackend<TKey, TValue> implements IMemoryBackend<TKey, TValue> {\n readonly domain: string;\n private readonly db: DatabaseType;\n private readonly ownsDb: boolean;\n private readonly schema?: z.ZodType<TValue>;\n private readonly stmts: {\n read: Statement;\n write: Statement;\n delete: Statement;\n count: Statement;\n bounds: Statement;\n queryAll: Statement;\n };\n private closed = false;\n\n constructor(options: SqliteBackendOptions<TValue>) {\n this.domain = options.domain;\n if (options.db !== undefined) {\n this.db = options.db;\n this.ownsDb = false;\n } else {\n // #3995: open via the shared helper, which creates the parent dir\n // first (fresh-install robustness) and enables WAL mode.\n this.db = openSqliteDatabase(options.dbPath);\n this.ownsDb = true;\n }\n if (options.schema !== undefined) {\n this.schema = options.schema;\n }\n this.ensureTable();\n this.stmts = this.prepareStatements();\n }\n\n private ensureTable(): void {\n // Table name = domain. Domain comes from in-tree code, never untrusted input,\n // so direct interpolation is safe; still validate the shape defensively.\n if (!/^[a-z][a-z0-9_]{0,63}$/i.test(this.domain)) {\n throw new Error(\n `nexus-memory: invalid domain \"${this.domain}\" — must match [a-zA-Z][a-zA-Z0-9_]{0,63}`\n );\n }\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS ${this.domain} (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n cli TEXT,\n source TEXT,\n timestamp INTEGER NOT NULL,\n trust_tier INTEGER\n );\n CREATE INDEX IF NOT EXISTS ${this.domain}_cli ON ${this.domain}(cli);\n CREATE INDEX IF NOT EXISTS ${this.domain}_timestamp ON ${this.domain}(timestamp);\n `);\n }\n\n private prepareStatements(): SqliteBackend<TKey, TValue>['stmts'] {\n return {\n read: this.db.prepare(\n `SELECT key, value, cli, source, timestamp, trust_tier FROM ${this.domain} WHERE key = ?`\n ),\n write: this.db.prepare(\n `INSERT INTO ${this.domain} (key, value, cli, source, timestamp, trust_tier)\n VALUES (@key, @value, @cli, @source, @timestamp, @trust_tier)\n ON CONFLICT(key) DO UPDATE SET\n value = excluded.value,\n cli = excluded.cli,\n source = excluded.source,\n timestamp = excluded.timestamp,\n trust_tier = excluded.trust_tier`\n ),\n delete: this.db.prepare(`DELETE FROM ${this.domain} WHERE key = ?`),\n count: this.db.prepare(`SELECT COUNT(*) AS count FROM ${this.domain}`),\n bounds: this.db.prepare(\n `SELECT MIN(timestamp) AS oldest, MAX(timestamp) AS newest FROM ${this.domain}`\n ),\n queryAll: this.db.prepare(\n `SELECT key, value, cli, source, timestamp, trust_tier FROM ${this.domain}`\n ),\n };\n }\n\n async read(key: TKey): Promise<TValue | undefined> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'read',\n },\n start,\n () => {\n this.assertOpen();\n const row = this.stmts.read.get(keyToString(key)) as SqliteRow | undefined;\n const value = row !== undefined ? (JSON.parse(row.value) as TValue) : undefined;\n recordMemoryEvent({\n domain: this.domain,\n op: 'read',\n hit: value !== undefined,\n ...(row?.cli !== null && row?.cli !== undefined && { cli: row.cli as never }),\n durationMs: Date.now() - start,\n key,\n result: value,\n });\n return Promise.resolve(value);\n }\n );\n }\n\n private validate(value: TValue): void {\n // #4021: reject `undefined` uniformly (before the optional schema check) so\n // both backends behave identically. Previously SqliteBackend threw a cryptic\n // NOT NULL bind error for `write(key, undefined)` while InMemoryBackend stored\n // a phantom row. `undefined` is the missing-key sentinel; use `null` for an\n // explicit absent value.\n if (value === undefined) {\n throw new MemoryValidationError(this.domain, 'value must not be undefined (use null)');\n }\n if (this.schema === undefined) return;\n const result = this.schema.safeParse(value);\n if (!result.success) {\n throw new MemoryValidationError(this.domain, result.error);\n }\n }\n\n async write(key: TKey, value: TValue, meta?: WriteMeta): Promise<void> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n },\n start,\n () => {\n this.assertOpen();\n this.validate(value);\n this.stmts.write.run(buildWriteRow(key, value, meta));\n recordMemoryEvent({\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n durationMs: Date.now() - start,\n key,\n payload: value,\n });\n return Promise.resolve();\n }\n );\n }\n\n async query(filter?: QueryFilter<TValue>): Promise<readonly TValue[]> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'query',\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n },\n start,\n () => {\n this.assertOpen();\n // Phase 3 keeps query simple — full table scan with in-process filter.\n // Hot-path backends will override or extend with indexed columns.\n let rows = this.stmts.queryAll.all() as SqliteRow[];\n if (filter?.cli !== undefined) {\n rows = rows.filter((r) => r.cli === filter.cli);\n }\n let values = rows.map((r) => JSON.parse(r.value) as TValue);\n values = applyQueryFilter(values, filter);\n recordMemoryEvent({\n domain: this.domain,\n op: 'query',\n hit: values.length > 0,\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n durationMs: Date.now() - start,\n key: filter,\n result: { count: values.length },\n });\n return Promise.resolve(values);\n }\n );\n }\n\n async delete(key: TKey): Promise<boolean> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'delete',\n },\n start,\n () => {\n this.assertOpen();\n const result = this.stmts.delete.run(keyToString(key));\n const removed = result.changes > 0;\n recordMemoryEvent({\n domain: this.domain,\n op: 'delete',\n hit: removed,\n durationMs: Date.now() - start,\n key,\n });\n return Promise.resolve(removed);\n }\n );\n }\n\n async stats(): Promise<BackendStats> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'stats',\n },\n start,\n () => {\n this.assertOpen();\n const countRow = this.stmts.count.get() as { count: number };\n const boundsRow = this.stmts.bounds.get() as {\n oldest: number | null;\n newest: number | null;\n };\n const result: BackendStats = {\n domain: this.domain,\n count: countRow.count,\n oldestTimestamp: boundsRow.oldest,\n newestTimestamp: boundsRow.newest,\n };\n recordMemoryEvent({\n domain: this.domain,\n op: 'stats',\n durationMs: Date.now() - start,\n result,\n });\n return Promise.resolve(result);\n }\n );\n }\n\n async close(): Promise<void> {\n if (this.closed) return Promise.resolve();\n this.closed = true;\n if (this.ownsDb) this.db.close();\n return Promise.resolve();\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(`nexus-memory: backend \"${this.domain}\" is closed`);\n }\n }\n}\n","/**\n * MemoryRegistry — the single entry point for accessing memory backends.\n *\n * Every concept-space (experience, outcomes, beliefs, …) registers a\n * backend; callers reach it via `registry.get('experience')` or, more\n * commonly, the typed accessors that wrap the registry.\n *\n * Sharing a SQLite connection across backends keeps WAL-mode behavior\n * coherent — one writer thread, many tables.\n *\n * @module nexus-memory/registry\n */\n\nimport type { SqliteDatabase as DatabaseType } from './backends/open-database.js';\nimport type { z } from 'zod';\nimport { InMemoryBackend } from './backends/memory.js';\nimport { openSqliteDatabase } from './backends/open-database.js';\nimport { SqliteBackend } from './backends/sqlite.js';\nimport type { IMemoryBackend } from './types.js';\n\nexport interface MemoryRegistryOptions {\n /**\n * SQLite file path. Use `':memory:'` for tests. When omitted, the\n * registry creates `InMemoryBackend` instances and never touches disk\n * — the standard test-isolation pattern (Phase 2 acceptance criterion).\n */\n readonly dbPath?: string;\n}\n\nexport interface RegisterBackendOptions<TValue> {\n /** Stable domain identifier. Becomes the SQLite table name. */\n readonly domain: string;\n /** Optional Zod schema for cold-archive validation. */\n readonly schema?: z.ZodType<TValue>;\n}\n\n/**\n * The registry. One per `dbPath` (or one in-memory registry per test).\n * `MemoryRegistry.get(domain)` is `O(1)` after registration.\n */\nexport class MemoryRegistry {\n private readonly backends = new Map<string, IMemoryBackend<unknown, unknown>>();\n private readonly db?: DatabaseType;\n private closed = false;\n\n constructor(options: MemoryRegistryOptions = {}) {\n if (options.dbPath !== undefined) {\n // #3995: open via the shared helper, which creates the parent dir\n // first (fresh-install robustness) and enables WAL mode.\n this.db = openSqliteDatabase(options.dbPath);\n }\n }\n\n /**\n * Register a backend for `domain`. Throws on duplicate domain.\n *\n * When the registry has a `dbPath`, the new backend is SQLite-backed\n * and shares the registry's connection. Otherwise, an `InMemoryBackend`\n * is created (used for tests).\n */\n register<TKey, TValue>(options: RegisterBackendOptions<TValue>): IMemoryBackend<TKey, TValue> {\n this.assertOpen();\n if (this.backends.has(options.domain)) {\n throw new Error(`nexus-memory: domain \"${options.domain}\" already registered`);\n }\n const backend: IMemoryBackend<TKey, TValue> =\n this.db !== undefined\n ? new SqliteBackend<TKey, TValue>({\n domain: options.domain,\n dbPath: '<shared>', // unused when db is supplied\n db: this.db,\n ...(options.schema !== undefined && { schema: options.schema }),\n })\n : new InMemoryBackend<TKey, TValue>({\n domain: options.domain,\n ...(options.schema !== undefined && { schema: options.schema }),\n });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- TypeScript narrows the union type here, but the Map needs the lifted IMemoryBackend<unknown, unknown>; the assertion documents the variance and survives future contract changes.\n this.backends.set(options.domain, backend as IMemoryBackend<unknown, unknown>);\n return backend;\n }\n\n /**\n * Attach an externally-managed {@link IMemoryBackend}. Use this when the\n * backend owns its own storage (e.g., a pre-existing SQLite file under\n * `~/.nexus-agents/memory/agentic.db`) and you want it discoverable\n * through the registry without changing its persistence.\n *\n * Phase 5–7 of the memory-unification epic use this to bring the\n * tool-memory backends (`agentic`, `adaptive`, `typed`, `belief`),\n * OutcomeStore, SICA, skills, etc. under a unified observability\n * contract without rewriting their internals. Each attached backend\n * still owns its own `.db` (or JSONL, etc.) until a follow-up migration\n * folds the storage in fully.\n */\n attach<TKey, TValue>(\n domain: string,\n backend: IMemoryBackend<TKey, TValue>\n ): IMemoryBackend<TKey, TValue> {\n this.assertOpen();\n if (this.backends.has(domain)) {\n throw new Error(`nexus-memory: domain \"${domain}\" already registered`);\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- See `register`.\n this.backends.set(domain, backend as IMemoryBackend<unknown, unknown>);\n return backend;\n }\n\n /**\n * Get a previously-registered backend. Returns `undefined` if the\n * domain isn't registered — callers should treat that as \"not yet\n * migrated to the unified contract.\"\n */\n get<TKey, TValue>(domain: string): IMemoryBackend<TKey, TValue> | undefined {\n this.assertOpen();\n const backend = this.backends.get(domain);\n return backend as IMemoryBackend<TKey, TValue> | undefined;\n }\n\n /** List all registered domains. Useful for `memory_stats`-style readers. */\n domains(): readonly string[] {\n return [...this.backends.keys()];\n }\n\n /**\n * Close every registered backend and the shared SQLite handle. After\n * `close()` the registry rejects all further operations.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n for (const backend of this.backends.values()) {\n await backend.close();\n }\n this.backends.clear();\n if (this.db !== undefined) this.db.close();\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error('nexus-memory: registry is closed');\n }\n }\n}\n\n// ============================================================================\n// Singleton accessor\n// ============================================================================\n\nlet sharedRegistry: MemoryRegistry | null = null;\n\n/**\n * Get the process-wide shared registry. Initializes on first call with\n * `dbPath` from `NEXUS_DATA_DIR` (defaults to `~/.nexus-agents/memory/memory.db`)\n * unless `setMemoryRegistry` was called first.\n *\n * Test code should call `setMemoryRegistry(createInMemoryMemoryRegistry())`\n * in `beforeEach` — this matches the existing `setOutcomeStore` pattern.\n */\nexport function getMemoryRegistry(): MemoryRegistry {\n if (sharedRegistry === null) {\n // Default path resolution happens here, NOT at module load — so tests\n // that call `setMemoryRegistry` before any `getMemoryRegistry` see\n // their in-memory instance, not a side-effectful production path.\n const dbPath = resolveDefaultDbPath();\n sharedRegistry = new MemoryRegistry({ dbPath });\n }\n return sharedRegistry;\n}\n\n/**\n * Inject a registry. Used by tests to swap in `InMemoryBackend`-backed\n * registries. After test, call again with `null` to reset, or call\n * `closeMemoryRegistry()` to dispose.\n */\nexport function setMemoryRegistry(registry: MemoryRegistry | null): void {\n sharedRegistry = registry;\n}\n\n/**\n * True when the shared registry has already been constructed or injected.\n * Lets nexus-agents inject the canonical {@link nexusDataPath}-resolved DB\n * path (#3995) WITHOUT clobbering a registry a test already set, and without\n * triggering the lazy default-path resolution that `getMemoryRegistry()`\n * would. Read-only — keeps nexus-memory dep-free.\n */\nexport function hasMemoryRegistry(): boolean {\n return sharedRegistry !== null;\n}\n\n/** Close + null out the shared registry. Idempotent. */\nexport async function closeMemoryRegistry(): Promise<void> {\n if (sharedRegistry !== null) {\n await sharedRegistry.close();\n sharedRegistry = null;\n }\n}\n\nfunction resolveDefaultDbPath(): string {\n // Match `nexus-agents`'s `nexusDataPath` convention without importing it\n // (keep nexus-memory free of inter-package deps for nexus-eval-* reuse).\n const root = process.env['NEXUS_DATA_DIR'] ?? `${process.env['HOME'] ?? '/tmp'}/.nexus-agents`;\n return `${root}/memory/memory.db`;\n}\n","/**\n * Test factories. Production code uses {@link getMemoryRegistry} from\n * `./registry.js`; tests use these helpers to avoid touching disk.\n *\n * @module nexus-memory/factory\n */\n\nimport { MemoryRegistry } from './registry.js';\n\n/**\n * Create a registry that lives entirely in memory. Every `register()`\n * call returns an {@link InMemoryBackend}; nothing is persisted.\n *\n * Use this in `beforeEach`:\n *\n * ```ts\n * beforeEach(() => {\n * setMemoryRegistry(createInMemoryMemoryRegistry());\n * });\n * afterEach(async () => {\n * await closeMemoryRegistry();\n * });\n * ```\n */\nexport function createInMemoryMemoryRegistry(): MemoryRegistry {\n return new MemoryRegistry({\n /* no dbPath → InMemoryBackend per domain */\n });\n}\n\n/**\n * Create a SQLite-backed registry rooted at `dbPath`. Pass `':memory:'`\n * for tests that need to exercise the SQLite code path (e.g.,\n * migration tests, parity tests).\n */\nexport function createSqliteMemoryRegistry(dbPath: string): MemoryRegistry {\n return new MemoryRegistry({ dbPath });\n}\n","/**\n * One-shot importer scaffold. Each Phase 4+ migration registers its own\n * importer here; the registry runs them on first launch (after a marker\n * file check) and renames source files to `.bak.<timestamp>` once\n * complete.\n *\n * This file ships the skeleton + the marker-file logic; concrete\n * importers (MobiMem JSON, OutcomeStore JSONL, agentic.db, etc.) plug in\n * during their respective migration phases.\n *\n * @module nexus-memory/importer\n */\n\nimport { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { MemoryRegistry } from './registry.js';\n\nexport interface ImporterRun {\n readonly domain: string;\n readonly rowsImported: number;\n readonly sourcePathBackup: string | null;\n}\n\nexport interface Importer {\n /** Stable identifier — used in the marker filename to track completion. */\n readonly id: string;\n /** Logical domain this importer targets in the registry. */\n readonly domain: string;\n /**\n * Run the import. Implementations: (1) check if source data exists,\n * (2) parse + validate it, (3) write rows into the registry's backend,\n * (4) rename source to `.bak.<timestamp>` and return the backup path.\n * Idempotent — if marker file says we already ran, the registry skips it.\n */\n run(registry: MemoryRegistry): Promise<ImporterRun>;\n}\n\nconst importers = new Map<string, Importer>();\n\n/** Register an importer. Phase 4+ migrations call this at module load. */\nexport function registerImporter(importer: Importer): void {\n if (importers.has(importer.id)) {\n throw new Error(`nexus-memory: importer \"${importer.id}\" already registered`);\n }\n importers.set(importer.id, importer);\n}\n\n/** For tests: clear all registered importers. */\nexport function resetImporters(): void {\n importers.clear();\n}\n\n/** Snapshot of registered importer IDs. */\nexport function listImporters(): readonly string[] {\n return [...importers.keys()];\n}\n\nexport interface RunImportersOptions {\n /**\n * Directory holding `.imported-{id}` marker files. Defaults to the\n * registry's data dir; tests should override.\n */\n readonly markerDir: string;\n /** Skip the marker check (forces re-run). Tests only. */\n readonly force?: boolean;\n}\n\n/**\n * Run every registered importer that hasn't yet completed (per marker\n * file). Returns the list of runs that actually executed.\n *\n * Failures are NOT fatal — a single importer's exception is logged via\n * the returned `errors` array; other importers still get a chance to run.\n */\nexport async function runImporters(\n registry: MemoryRegistry,\n options: RunImportersOptions\n): Promise<{ runs: readonly ImporterRun[]; errors: readonly { id: string; error: Error }[] }> {\n mkdirSync(options.markerDir, { recursive: true });\n const runs: ImporterRun[] = [];\n const errors: { id: string; error: Error }[] = [];\n for (const importer of importers.values()) {\n const marker = join(options.markerDir, `.imported-${importer.id}`);\n if (options.force !== true && existsSync(marker)) continue;\n try {\n const run = await importer.run(registry);\n writeMarker(marker, run);\n runs.push(run);\n } catch (err) {\n errors.push({ id: importer.id, error: err instanceof Error ? err : new Error(String(err)) });\n }\n }\n return { runs, errors };\n}\n\nfunction writeMarker(path: string, run: ImporterRun): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(\n path,\n JSON.stringify({ ...run, completedAt: new Date().toISOString() }, null, 2),\n 'utf-8'\n );\n}\n\n/**\n * Rename a source file to `.bak.<unix-timestamp>`. Used by concrete\n * importers after a successful migration. Returns the backup path, or\n * `null` when the source doesn't exist.\n */\nexport function backupSourceFile(sourcePath: string): string | null {\n if (!existsSync(sourcePath)) return null;\n const backup = `${sourcePath}.bak.${String(Date.now())}`;\n renameSync(sourcePath, backup);\n return backup;\n}\n"],"mappings":";AEyBA,SAAS,qBAAqB;AA8C9B,SAAS,iBAAiB;AAC1B,SAAS,eAAe;AI3DxB,SAAS,YAAY,aAAAA,YAAW,YAAY,qBAAq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D,SAAO,CAAC,GAAG,UAAU,KAAK,CAAC;AAC7B;AAmBA,eAAsB,aACpB,UACA,SAC4F;AAC5FD,aAAU,QAAQ,WAAW,EAAE,WAAW,KAAK,CAAC;AAChD,QAAM,OAAsB,CAAC;AAC7B,QAAM,SAAyC,CAAC;AAChD,aAAW,YAAY,UAAU,OAAO,GAAG;AACzC,UAAM,SAAS,KAAK,QAAQ,WAAW,aAAa,SAAS,EAAE,EAAE;AACjE,QAAI,QAAQ,UAAU,QAAQ,WAAW,MAAM,EAAG;AAClD,QAAI;AACF,YAAM,MAAM,MAAM,SAAS,IAAI,QAAQ;AACvC,kBAAY,QAAQ,GAAG;AACvB,WAAK,KAAK,GAAG;IACf,SAAS,KAAK;AACZ,aAAO,KAAK,EAAE,IAAI,SAAS,IAAI,OAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,EAAE,CAAC;IAC7F;EACF;AACA,SAAO,EAAE,MAAM,OAAO;AACxB;AAEA,SAAS,YAAY,MAAc,KAAwB;AACzDA,aAAUC,SAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAC5C;IACE;IACA,KAAK,UAAU,EAAE,GAAG,KAAK,cAAa,oBAAI,KAAK,GAAE,YAAY,EAAE,GAAG,MAAM,CAAC;IACzE;EACF;AACF;AAOO,SAAS,iBAAiB,YAAmC;AAClE,MAAI,CAAC,WAAW,UAAU,EAAG,QAAO;AACpC,QAAM,SAAS,GAAG,UAAU,QAAQ,OAAO,KAAK,IAAI,CAAC,CAAC;AACtD,aAAW,YAAY,MAAM;AAC7B,SAAO;AACT;","names":["mkdirSync","dirname"]}
|
|
1
|
+
{"version":3,"sources":["../../nexus-memory/src/telemetry.ts","../../nexus-memory/src/backends/memory.ts","../../nexus-memory/src/backends/open-database.ts","../../nexus-memory/src/backends/sqlite.ts","../../nexus-memory/src/registry.ts","../../nexus-memory/src/factory.ts","../../nexus-memory/src/importer.ts"],"sourcesContent":["/**\n * Memory telemetry — aggregated counters (default) + opt-in full-audit mode.\n *\n * Phase 2 vote (#2768) settled on **C**: per-`{domain, op}` counters in\n * steady state, full per-event payloads when `NEXUS_MEMORY_AUDIT_MODE=audit`.\n *\n * The catfish-mitigation requirement is honored: audit mode emits\n * `{ op, keySummary, payloadSummary, resultSummary, cli, durationMs, hit }`\n * — not just counters — so an incident replay can reconstruct individual\n * ops. Summaries are truncated to keep emission cheap.\n *\n * @module nexus-memory/telemetry\n */\n\nimport type { CliName, MemoryEvent, MemoryEventCounters, MemoryEventListener } from './types.js';\n\nconst KEY_SUMMARY_LIMIT = 120;\nconst PAYLOAD_SUMMARY_LIMIT = 240;\n\n/** Per-`{domain, op}` rolling counters. */\nconst counters = new Map<string, MemoryEventCounters>();\nconst listeners = new Set<MemoryEventListener>();\n\n/** Audit mode is opt-in via env. Checked once per emission so the env\n * can be toggled at runtime by tests via `process.env`. */\nfunction isAuditMode(): boolean {\n return process.env['NEXUS_MEMORY_AUDIT_MODE'] === 'audit';\n}\n\nfunction counterKey(domain: string, op: MemoryEvent['op']): string {\n return `${domain}::${op}`;\n}\n\nfunction truncate(value: unknown, limit: number): string {\n let s: string;\n if (typeof value === 'string') {\n s = value;\n } else if (value === undefined) {\n s = '<undefined>';\n } else if (value === null) {\n s = '<null>';\n } else {\n try {\n s = JSON.stringify(value);\n } catch {\n s = '<unserializable>';\n }\n }\n return s.length > limit ? `${s.slice(0, limit - 1)}…` : s;\n}\n\ninterface RecordedEvent extends Omit<\n MemoryEvent,\n 'keySummary' | 'payloadSummary' | 'resultSummary'\n> {\n readonly key?: unknown;\n readonly payload?: unknown;\n readonly result?: unknown;\n}\n\n/** The zero row a domain/op starts from — every field named, none defaulted implicitly. */\nfunction emptyCounter(domain: string, op: MemoryEvent['op']): MemoryEventCounters {\n return { domain, op, count: 0, errorCount: 0, hitCount: 0, totalDurationMs: 0, maxDurationMs: 0 };\n}\n\nfunction updateCounter(event: RecordedEvent): void {\n const ck = counterKey(event.domain, event.op);\n const prev = counters.get(ck) ?? emptyCounter(event.domain, event.op);\n counters.set(ck, {\n domain: prev.domain,\n op: prev.op,\n count: prev.count + 1,\n errorCount: prev.errorCount + (event.error !== undefined ? 1 : 0),\n hitCount: prev.hitCount + (event.hit === true ? 1 : 0),\n totalDurationMs: prev.totalDurationMs + event.durationMs,\n maxDurationMs: Math.max(prev.maxDurationMs, event.durationMs),\n });\n}\n\nfunction buildPublicEvent(event: RecordedEvent, audit: boolean): MemoryEvent {\n return {\n domain: event.domain,\n op: event.op,\n durationMs: event.durationMs,\n // #5965: without this the counter records a failure the subscriber never\n // sees — two instruments disagreeing about the same operation.\n ...(event.error !== undefined && { error: event.error }),\n ...(event.cli !== undefined && { cli: event.cli }),\n ...(event.hit !== undefined && { hit: event.hit }),\n ...(audit &&\n event.key !== undefined && {\n keySummary: truncate(event.key, KEY_SUMMARY_LIMIT),\n }),\n ...(audit &&\n event.payload !== undefined && {\n payloadSummary: truncate(event.payload, PAYLOAD_SUMMARY_LIMIT),\n }),\n ...(audit &&\n event.result !== undefined && {\n resultSummary: truncate(event.result, PAYLOAD_SUMMARY_LIMIT),\n }),\n };\n}\n\n/**\n * Record a memory operation, successful or not. Updates counters always;\n * emits the event to subscribers always (subscribers get the full event in\n * audit mode, the aggregate-only event otherwise).\n *\n * \"Always\" is load-bearing and was not true until #5965: every backend called\n * this AFTER the work, so a throw skipped it entirely.\n *\n * Implementation note: the `op` argument is the typed `MemoryEvent['op']`\n * literal — backends never pass an unknown string here.\n */\nexport function recordMemoryEvent(event: RecordedEvent): void {\n updateCounter(event);\n const publicEvent = buildPublicEvent(event, isAuditMode());\n for (const listener of listeners) {\n try {\n listener(publicEvent);\n } catch {\n // Subscriber failures must never affect memory operations.\n }\n }\n}\n\n/** Snapshot of current counters. Returned array is a copy. */\nexport function getMemoryEventCounters(): readonly MemoryEventCounters[] {\n return [...counters.values()];\n}\n\n/** Subscribe to the per-event stream. Returns an unsubscribe function. */\nexport function subscribeToMemoryEvents(listener: MemoryEventListener): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\n/**\n * Reset counters + drop all subscribers. Tests should call this in\n * `beforeEach` to keep state from leaking.\n */\nexport function resetMemoryTelemetry(): void {\n counters.clear();\n listeners.clear();\n}\n\n/**\n * Runs one backend operation and records it even when it throws (#5965).\n *\n * The record call used to sit after the work, so a `MemoryValidationError`, a\n * SQLite constraint or disk error, or a call on a closed backend produced no\n * event and no counter row at all — a domain rejecting every write looked\n * exactly like a domain nobody was using. The event is emitted BEFORE the\n * error is re-thrown, so the caller's own error handling is unchanged.\n *\n * The success event stays at each call site: only the caller knows the `hit`,\n * `key`, `payload` and `result` a successful op should carry.\n */\nexport function recordFailedMemoryOp<T>(\n context: { readonly domain: string; readonly op: MemoryEvent['op']; readonly cli?: CliName },\n start: number,\n body: () => T\n): T {\n try {\n return body();\n } catch (error) {\n recordMemoryEvent({\n domain: context.domain,\n op: context.op,\n ...(context.cli !== undefined && { cli: context.cli }),\n durationMs: Date.now() - start,\n // Message only — a validation error's detail can quote the value that\n // failed, and that value is caller payload.\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n}\n","/**\n * In-memory backend — primarily for tests, but also used as the cold-archive\n * fallback when no `dbPath` is provided.\n *\n * Implements {@link IMemoryBackend}; passes the same contract test as\n * {@link SqliteBackend}.\n *\n * @module nexus-memory/backends/memory\n */\n\nimport type { z } from 'zod';\nimport { recordFailedMemoryOp, recordMemoryEvent } from '../telemetry.js';\nimport type { BackendStats, IMemoryBackend, QueryFilter, WriteMeta } from '../types.js';\n\ninterface Row<TValue> {\n readonly value: TValue;\n readonly cli?: string;\n readonly source?: string;\n readonly timestamp: number;\n readonly trustTier?: 1 | 2 | 3 | 4;\n}\n\nexport interface InMemoryBackendOptions<TValue> {\n readonly domain: string;\n /**\n * Optional Zod schema. Phase 2 vote mitigation #1 (security dissent):\n * when supplied, every `write()` validates the value first; invalid\n * payloads throw `MemoryValidationError`.\n */\n readonly schema?: z.ZodType<TValue>;\n}\n\nexport class MemoryValidationError extends Error {\n constructor(domain: string, cause: unknown) {\n super(`nexus-memory: write rejected for domain \"${domain}\": ${String(cause)}`);\n this.name = 'MemoryValidationError';\n }\n}\n\nfunction buildInMemoryRow<TValue>(value: TValue, meta: WriteMeta | undefined): Row<TValue> {\n return {\n value,\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n ...(meta?.source !== undefined && { source: meta.source }),\n timestamp: meta?.timestamp ?? Date.now(),\n ...(meta?.trustTier !== undefined && { trustTier: meta.trustTier }),\n };\n}\n\n/** Apply `where`, `orderBy`, `limit` to an in-memory row set. Extracted from\n * `query` to satisfy the eslint complexity gate. */\nfunction applyInMemoryFilter<T>(values: T[], filter?: QueryFilter<T>): T[] {\n let out = values;\n if (filter?.where !== undefined) {\n const where = filter.where;\n out = out.filter((v) => {\n for (const [k, expected] of Object.entries(where)) {\n if ((v as Record<string, unknown>)[k] !== expected) return false;\n }\n return true;\n });\n }\n if (filter?.orderBy !== undefined) {\n const orderBy = filter.orderBy;\n const dir = filter.orderDir === 'desc' ? -1 : 1;\n out = [...out].sort((a, b) => {\n const av = (a as Record<string | symbol | number, unknown>)[orderBy];\n const bv = (b as Record<string | symbol | number, unknown>)[orderBy];\n if (av === bv) return 0;\n if (av === undefined || av === null) return 1;\n if (bv === undefined || bv === null) return -1;\n return (av < bv ? -1 : 1) * dir;\n });\n }\n if (filter?.limit !== undefined) {\n out = out.slice(0, filter.limit);\n }\n return out;\n}\n\nexport class InMemoryBackend<TKey, TValue> implements IMemoryBackend<TKey, TValue> {\n readonly domain: string;\n private readonly rows = new Map<TKey, Row<TValue>>();\n private readonly schema?: z.ZodType<TValue>;\n private closed = false;\n\n constructor(options: InMemoryBackendOptions<TValue>) {\n this.domain = options.domain;\n if (options.schema !== undefined) {\n this.schema = options.schema;\n }\n }\n\n async read(key: TKey): Promise<TValue | undefined> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'read',\n },\n start,\n () => {\n this.assertOpen();\n const row = this.rows.get(key);\n recordMemoryEvent({\n domain: this.domain,\n op: 'read',\n hit: row !== undefined,\n durationMs: Date.now() - start,\n key,\n result: row?.value,\n });\n return Promise.resolve(row?.value);\n }\n );\n }\n\n private validate(value: TValue): void {\n // #4021: reject `undefined` uniformly (before the optional schema check) so\n // both backends behave identically. Previously this backend stored a phantom\n // row for `write(key, undefined)` while SqliteBackend threw a cryptic NOT NULL\n // bind error — a contract divergence. `undefined` is the missing-key sentinel\n // `read` returns; an explicit `undefined` write is a caller bug — use `null`.\n if (value === undefined) {\n throw new MemoryValidationError(this.domain, 'value must not be undefined (use null)');\n }\n if (this.schema === undefined) return;\n const result = this.schema.safeParse(value);\n if (!result.success) {\n throw new MemoryValidationError(this.domain, result.error);\n }\n }\n\n async write(key: TKey, value: TValue, meta?: WriteMeta): Promise<void> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n },\n start,\n () => {\n this.assertOpen();\n this.validate(value);\n this.rows.set(key, buildInMemoryRow(value, meta));\n recordMemoryEvent({\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n durationMs: Date.now() - start,\n key,\n payload: value,\n });\n return Promise.resolve();\n }\n );\n }\n\n async query(filter?: QueryFilter<TValue>): Promise<readonly TValue[]> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'query',\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n },\n start,\n () => {\n this.assertOpen();\n let rows = [...this.rows.values()];\n if (filter?.cli !== undefined) {\n rows = rows.filter((r) => r.cli === filter.cli);\n }\n const values = applyInMemoryFilter(\n rows.map((r) => r.value),\n filter\n );\n recordMemoryEvent({\n domain: this.domain,\n op: 'query',\n hit: values.length > 0,\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n durationMs: Date.now() - start,\n key: filter,\n result: { count: values.length },\n });\n return Promise.resolve(values);\n }\n );\n }\n\n async delete(key: TKey): Promise<boolean> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'delete',\n },\n start,\n () => {\n this.assertOpen();\n const removed = this.rows.delete(key);\n recordMemoryEvent({\n domain: this.domain,\n op: 'delete',\n hit: removed,\n durationMs: Date.now() - start,\n key,\n });\n return Promise.resolve(removed);\n }\n );\n }\n\n async stats(): Promise<BackendStats> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'stats',\n },\n start,\n () => {\n this.assertOpen();\n const timestamps = [...this.rows.values()].map((r) => r.timestamp);\n const result: BackendStats = {\n domain: this.domain,\n count: this.rows.size,\n oldestTimestamp: timestamps.length > 0 ? Math.min(...timestamps) : null,\n newestTimestamp: timestamps.length > 0 ? Math.max(...timestamps) : null,\n };\n recordMemoryEvent({\n domain: this.domain,\n op: 'stats',\n durationMs: Date.now() - start,\n result,\n });\n return Promise.resolve(result);\n }\n );\n }\n\n async close(): Promise<void> {\n this.closed = true;\n this.rows.clear();\n return Promise.resolve();\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(`nexus-memory: backend \"${this.domain}\" is closed`);\n }\n }\n}\n","/**\n * Shared helper for opening a SQLite connection on disk.\n *\n * Centralizes the two pre-#3995 concerns that were duplicated at every\n * `new Database(dbPath)` site in this package:\n *\n * 1. **Auto-create the parent directory.** SQLite throws\n * `SQLITE_CANTOPEN` when the parent directory of `dbPath` does not exist\n * (the classic fresh-install regression — the resolver hands back a path\n * under `~/.nexus-agents/memory/` that nobody has created yet). We\n * `mkdirSync(dirname(dbPath), { recursive: true })` first so opening the\n * DB never throws merely because the directory is missing. `:memory:`\n * (and the empty string) are pure in-memory handles with no parent dir, so\n * they skip the mkdir.\n * 2. **WAL journal mode.** Keeps concurrent MCP-server + CLI readers coherent.\n *\n * Kept dep-free on purpose: nexus-memory must stay free of inter-package\n * imports so `nexus-eval-*` repos can reuse it. The canonical\n * `nexusDataPath` resolver lives in nexus-agents and injects the path here as\n * a plain string (see `getMemoryRegistry` wiring in nexus-agents). This helper\n * only guarantees that whatever absolute path it is handed is openable.\n *\n * @module nexus-memory/backends/open-database\n */\n\nimport { createRequire } from 'node:module';\n\n/**\n * Loaded through `createRequire`, not a static import (#5392).\n *\n * A static `import ... from 'node:sqlite'` is HOISTED by the bundler to the top\n * of the emitted chunk, so it evaluates before any consumer code can run. Node\n * emits the SQLite `ExperimentalWarning` at IMPORT time, so that ordering made\n * the CLI's warning filter unable to fire at all. `createRequire` keeps the load\n * synchronous — which is why node:sqlite was chosen — while deferring it to\n * first call. Node caches the module, so repeat calls are free.\n */\nconst requireFromHere = createRequire(import.meta.url);\n\nfunction loadSqlite(): typeof import('node:sqlite') {\n return requireFromHere('node:sqlite') as typeof import('node:sqlite');\n}\n\n/**\n * Result of running a prepared statement. Mirrors what both `node:sqlite` and\n * better-sqlite3 return, so consumers did not have to change (#5388).\n */\nexport interface SqliteRunResult {\n readonly changes: number | bigint;\n readonly lastInsertRowid: number | bigint;\n}\n\n/** Minimal prepared-statement surface this package actually uses. */\nexport interface SqliteStatement {\n run(...params: unknown[]): SqliteRunResult;\n get(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n}\n\n/**\n * Minimal database surface this package actually uses.\n *\n * Declared locally rather than imported: nexus-memory stays free of\n * inter-package imports so `nexus-eval-*` repos can reuse it, and since #5388\n * there is no dependency to import a type FROM — `node:sqlite` is a builtin.\n */\nexport interface SqliteDatabase {\n exec(sql: string): void;\n prepare(sql: string): SqliteStatement;\n close(): void;\n}\nimport { mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\n/**\n * Open a SQLite database at `dbPath`, creating the parent directory\n * first (for on-disk paths) and enabling WAL journal mode.\n *\n * @param dbPath Absolute SQLite file path, or `':memory:'` / `''` for an\n * in-memory database (no directory is created in that case).\n */\nexport function openSqliteDatabase(dbPath: string): SqliteDatabase {\n if (dbPath !== ':memory:' && dbPath !== '') {\n // Fresh-install robustness (#3995): opening under a missing parent throws SQLITE_CANTOPEN\n // when the parent dir is missing. Create it up front, idempotently.\n mkdirSync(dirname(dbPath), { recursive: true });\n }\n const { DatabaseSync } = loadSqlite();\n const db = new DatabaseSync(dbPath);\n // `node:sqlite` has no `.pragma()` helper, so WAL goes through `exec`.\n db.exec('PRAGMA journal_mode = WAL');\n\n const narrowed = db as unknown as SqliteDatabase;\n return {\n exec: (sql: string) => {\n db.exec(sql);\n },\n prepare: narrowed.prepare.bind(narrowed),\n // better-sqlite3's `close()` is idempotent; `DatabaseSync`'s throws\n // `database is not open` on a second call, and shutdown paths here are\n // reentrant. Preserve the contract callers were written against (#5388).\n close: () => {\n if (db.isOpen) db.close();\n },\n };\n}\n","/**\n * SQLite backend — async wrapper over `node:sqlite` (which is sync).\n *\n * One table per domain (Phase 2 vote shape C, hot-table side). The schema\n * is intentionally minimal: `key`, `value` (JSON-serialized), `cli`,\n * `source`, `timestamp`, `trust_tier`. Hot-path backends extending this\n * will add typed columns and indexes for query performance.\n *\n * Async surface: every method returns `Promise<T>` so we can swap in a\n * network-backed implementation later without changing callers. The\n * actual SQLite ops are sync inside.\n *\n * @module nexus-memory/backends/sqlite\n */\n\nimport type {\n SqliteDatabase as DatabaseType,\n SqliteStatement as Statement,\n} from './open-database.js';\nimport type { z } from 'zod';\nimport { recordFailedMemoryOp, recordMemoryEvent } from '../telemetry.js';\nimport type { BackendStats, IMemoryBackend, QueryFilter, WriteMeta } from '../types.js';\nimport { MemoryValidationError } from './memory.js';\nimport { openSqliteDatabase } from './open-database.js';\n\nexport interface SqliteBackendOptions<TValue> {\n readonly domain: string;\n /** Absolute path to the SQLite file. Use `':memory:'` for tests. */\n readonly dbPath: string;\n /**\n * Zod schema for cold-archive validation (Phase 2 vote mitigation #1).\n * When supplied, every `write()` validates first.\n */\n readonly schema?: z.ZodType<TValue>;\n /** Pre-existing database handle. Used by `MemoryRegistry` to share a single connection. */\n readonly db?: DatabaseType;\n}\n\ninterface SqliteRow {\n readonly key: string;\n readonly value: string;\n readonly cli: string | null;\n readonly source: string | null;\n readonly timestamp: number;\n readonly trust_tier: number | null;\n}\n\nfunction buildWriteRow(\n key: unknown,\n value: unknown,\n meta: WriteMeta | undefined\n): Record<string, string | number | null> {\n return {\n key: keyToString(key),\n value: JSON.stringify(value),\n cli: meta?.cli ?? null,\n source: meta?.source ?? null,\n timestamp: meta?.timestamp ?? Date.now(),\n trust_tier: meta?.trustTier ?? null,\n };\n}\n\n/** Stringify a key so SQLite primary-key lookups stay simple. */\nfunction keyToString(key: unknown): string {\n if (typeof key === 'string') return key;\n if (typeof key === 'number' || typeof key === 'boolean') return String(key);\n return JSON.stringify(key);\n}\n\n/** Apply `where`, `orderBy`, `limit` to an in-memory row set. Extracted from\n * `query` to satisfy the eslint complexity gate. */\nfunction applyQueryFilter<T>(values: T[], filter?: QueryFilter<T>): T[] {\n let out = values;\n if (filter?.where !== undefined) {\n const where = filter.where;\n out = out.filter((v) => {\n for (const [k, expected] of Object.entries(where)) {\n if ((v as Record<string, unknown>)[k] !== expected) return false;\n }\n return true;\n });\n }\n if (filter?.orderBy !== undefined) {\n const orderBy = filter.orderBy;\n const dir = filter.orderDir === 'desc' ? -1 : 1;\n out = [...out].sort((a, b) => {\n const av = (a as Record<string | symbol | number, unknown>)[orderBy];\n const bv = (b as Record<string | symbol | number, unknown>)[orderBy];\n if (av === bv) return 0;\n if (av === undefined || av === null) return 1;\n if (bv === undefined || bv === null) return -1;\n return (av < bv ? -1 : 1) * dir;\n });\n }\n if (filter?.limit !== undefined) {\n out = out.slice(0, filter.limit);\n }\n return out;\n}\n\nexport class SqliteBackend<TKey, TValue> implements IMemoryBackend<TKey, TValue> {\n readonly domain: string;\n private readonly db: DatabaseType;\n private readonly ownsDb: boolean;\n private readonly schema?: z.ZodType<TValue>;\n private readonly stmts: {\n read: Statement;\n write: Statement;\n delete: Statement;\n count: Statement;\n bounds: Statement;\n queryAll: Statement;\n };\n private closed = false;\n\n constructor(options: SqliteBackendOptions<TValue>) {\n this.domain = options.domain;\n if (options.db !== undefined) {\n this.db = options.db;\n this.ownsDb = false;\n } else {\n // #3995: open via the shared helper, which creates the parent dir\n // first (fresh-install robustness) and enables WAL mode.\n this.db = openSqliteDatabase(options.dbPath);\n this.ownsDb = true;\n }\n if (options.schema !== undefined) {\n this.schema = options.schema;\n }\n this.ensureTable();\n this.stmts = this.prepareStatements();\n }\n\n private ensureTable(): void {\n // Table name = domain. Domain comes from in-tree code, never untrusted input,\n // so direct interpolation is safe; still validate the shape defensively.\n if (!/^[a-z][a-z0-9_]{0,63}$/i.test(this.domain)) {\n throw new Error(\n `nexus-memory: invalid domain \"${this.domain}\" — must match [a-zA-Z][a-zA-Z0-9_]{0,63}`\n );\n }\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS ${this.domain} (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n cli TEXT,\n source TEXT,\n timestamp INTEGER NOT NULL,\n trust_tier INTEGER\n );\n CREATE INDEX IF NOT EXISTS ${this.domain}_cli ON ${this.domain}(cli);\n CREATE INDEX IF NOT EXISTS ${this.domain}_timestamp ON ${this.domain}(timestamp);\n `);\n }\n\n private prepareStatements(): SqliteBackend<TKey, TValue>['stmts'] {\n return {\n read: this.db.prepare(\n `SELECT key, value, cli, source, timestamp, trust_tier FROM ${this.domain} WHERE key = ?`\n ),\n write: this.db.prepare(\n `INSERT INTO ${this.domain} (key, value, cli, source, timestamp, trust_tier)\n VALUES (@key, @value, @cli, @source, @timestamp, @trust_tier)\n ON CONFLICT(key) DO UPDATE SET\n value = excluded.value,\n cli = excluded.cli,\n source = excluded.source,\n timestamp = excluded.timestamp,\n trust_tier = excluded.trust_tier`\n ),\n delete: this.db.prepare(`DELETE FROM ${this.domain} WHERE key = ?`),\n count: this.db.prepare(`SELECT COUNT(*) AS count FROM ${this.domain}`),\n bounds: this.db.prepare(\n `SELECT MIN(timestamp) AS oldest, MAX(timestamp) AS newest FROM ${this.domain}`\n ),\n queryAll: this.db.prepare(\n `SELECT key, value, cli, source, timestamp, trust_tier FROM ${this.domain}`\n ),\n };\n }\n\n async read(key: TKey): Promise<TValue | undefined> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'read',\n },\n start,\n () => {\n this.assertOpen();\n const row = this.stmts.read.get(keyToString(key)) as SqliteRow | undefined;\n const value = row !== undefined ? (JSON.parse(row.value) as TValue) : undefined;\n recordMemoryEvent({\n domain: this.domain,\n op: 'read',\n hit: value !== undefined,\n ...(row?.cli !== null && row?.cli !== undefined && { cli: row.cli as never }),\n durationMs: Date.now() - start,\n key,\n result: value,\n });\n return Promise.resolve(value);\n }\n );\n }\n\n private validate(value: TValue): void {\n // #4021: reject `undefined` uniformly (before the optional schema check) so\n // both backends behave identically. Previously SqliteBackend threw a cryptic\n // NOT NULL bind error for `write(key, undefined)` while InMemoryBackend stored\n // a phantom row. `undefined` is the missing-key sentinel; use `null` for an\n // explicit absent value.\n if (value === undefined) {\n throw new MemoryValidationError(this.domain, 'value must not be undefined (use null)');\n }\n if (this.schema === undefined) return;\n const result = this.schema.safeParse(value);\n if (!result.success) {\n throw new MemoryValidationError(this.domain, result.error);\n }\n }\n\n async write(key: TKey, value: TValue, meta?: WriteMeta): Promise<void> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n },\n start,\n () => {\n this.assertOpen();\n this.validate(value);\n this.stmts.write.run(buildWriteRow(key, value, meta));\n recordMemoryEvent({\n domain: this.domain,\n op: 'write',\n ...(meta?.cli !== undefined && { cli: meta.cli }),\n durationMs: Date.now() - start,\n key,\n payload: value,\n });\n return Promise.resolve();\n }\n );\n }\n\n async query(filter?: QueryFilter<TValue>): Promise<readonly TValue[]> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'query',\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n },\n start,\n () => {\n this.assertOpen();\n // Phase 3 keeps query simple — full table scan with in-process filter.\n // Hot-path backends will override or extend with indexed columns.\n let rows = this.stmts.queryAll.all() as SqliteRow[];\n if (filter?.cli !== undefined) {\n rows = rows.filter((r) => r.cli === filter.cli);\n }\n let values = rows.map((r) => JSON.parse(r.value) as TValue);\n values = applyQueryFilter(values, filter);\n recordMemoryEvent({\n domain: this.domain,\n op: 'query',\n hit: values.length > 0,\n ...(filter?.cli !== undefined && { cli: filter.cli }),\n durationMs: Date.now() - start,\n key: filter,\n result: { count: values.length },\n });\n return Promise.resolve(values);\n }\n );\n }\n\n async delete(key: TKey): Promise<boolean> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'delete',\n },\n start,\n () => {\n this.assertOpen();\n const result = this.stmts.delete.run(keyToString(key));\n const removed = result.changes > 0;\n recordMemoryEvent({\n domain: this.domain,\n op: 'delete',\n hit: removed,\n durationMs: Date.now() - start,\n key,\n });\n return Promise.resolve(removed);\n }\n );\n }\n\n async stats(): Promise<BackendStats> {\n const start = Date.now();\n return recordFailedMemoryOp(\n {\n domain: this.domain,\n op: 'stats',\n },\n start,\n () => {\n this.assertOpen();\n const countRow = this.stmts.count.get() as { count: number };\n const boundsRow = this.stmts.bounds.get() as {\n oldest: number | null;\n newest: number | null;\n };\n const result: BackendStats = {\n domain: this.domain,\n count: countRow.count,\n oldestTimestamp: boundsRow.oldest,\n newestTimestamp: boundsRow.newest,\n };\n recordMemoryEvent({\n domain: this.domain,\n op: 'stats',\n durationMs: Date.now() - start,\n result,\n });\n return Promise.resolve(result);\n }\n );\n }\n\n async close(): Promise<void> {\n if (this.closed) return Promise.resolve();\n this.closed = true;\n if (this.ownsDb) this.db.close();\n return Promise.resolve();\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(`nexus-memory: backend \"${this.domain}\" is closed`);\n }\n }\n}\n","/**\n * MemoryRegistry — the single entry point for accessing memory backends.\n *\n * Every concept-space (experience, outcomes, beliefs, …) registers a\n * backend; callers reach it via `registry.get('experience')` or, more\n * commonly, the typed accessors that wrap the registry.\n *\n * Sharing a SQLite connection across backends keeps WAL-mode behavior\n * coherent — one writer thread, many tables.\n *\n * @module nexus-memory/registry\n */\n\nimport type { SqliteDatabase as DatabaseType } from './backends/open-database.js';\nimport type { z } from 'zod';\nimport { InMemoryBackend } from './backends/memory.js';\nimport { openSqliteDatabase } from './backends/open-database.js';\nimport { SqliteBackend } from './backends/sqlite.js';\nimport type { IMemoryBackend } from './types.js';\n\nexport interface MemoryRegistryOptions {\n /**\n * SQLite file path. Use `':memory:'` for tests. When omitted, the\n * registry creates `InMemoryBackend` instances and never touches disk\n * — the standard test-isolation pattern (Phase 2 acceptance criterion).\n */\n readonly dbPath?: string;\n}\n\nexport interface RegisterBackendOptions<TValue> {\n /** Stable domain identifier. Becomes the SQLite table name. */\n readonly domain: string;\n /** Optional Zod schema for cold-archive validation. */\n readonly schema?: z.ZodType<TValue>;\n}\n\n/**\n * The registry. One per `dbPath` (or one in-memory registry per test).\n * `MemoryRegistry.get(domain)` is `O(1)` after registration.\n */\nexport class MemoryRegistry {\n private readonly backends = new Map<string, IMemoryBackend<unknown, unknown>>();\n private readonly db?: DatabaseType;\n private closed = false;\n\n constructor(options: MemoryRegistryOptions = {}) {\n if (options.dbPath !== undefined) {\n // #3995: open via the shared helper, which creates the parent dir\n // first (fresh-install robustness) and enables WAL mode.\n this.db = openSqliteDatabase(options.dbPath);\n }\n }\n\n /**\n * Register a backend for `domain`. Throws on duplicate domain.\n *\n * When the registry has a `dbPath`, the new backend is SQLite-backed\n * and shares the registry's connection. Otherwise, an `InMemoryBackend`\n * is created (used for tests).\n */\n register<TKey, TValue>(options: RegisterBackendOptions<TValue>): IMemoryBackend<TKey, TValue> {\n this.assertOpen();\n if (this.backends.has(options.domain)) {\n throw new Error(`nexus-memory: domain \"${options.domain}\" already registered`);\n }\n const backend: IMemoryBackend<TKey, TValue> =\n this.db !== undefined\n ? new SqliteBackend<TKey, TValue>({\n domain: options.domain,\n dbPath: '<shared>', // unused when db is supplied\n db: this.db,\n ...(options.schema !== undefined && { schema: options.schema }),\n })\n : new InMemoryBackend<TKey, TValue>({\n domain: options.domain,\n ...(options.schema !== undefined && { schema: options.schema }),\n });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- TypeScript narrows the union type here, but the Map needs the lifted IMemoryBackend<unknown, unknown>; the assertion documents the variance and survives future contract changes.\n this.backends.set(options.domain, backend as IMemoryBackend<unknown, unknown>);\n return backend;\n }\n\n /**\n * Attach an externally-managed {@link IMemoryBackend}. Use this when the\n * backend owns its own storage (e.g., a pre-existing SQLite file under\n * `~/.nexus-agents/memory/agentic.db`) and you want it discoverable\n * through the registry without changing its persistence.\n *\n * Phase 5–7 of the memory-unification epic use this to bring the\n * tool-memory backends (`agentic`, `adaptive`, `typed`, `belief`),\n * OutcomeStore, SICA, skills, etc. under a unified observability\n * contract without rewriting their internals. Each attached backend\n * still owns its own `.db` (or JSONL, etc.) until a follow-up migration\n * folds the storage in fully.\n */\n attach<TKey, TValue>(\n domain: string,\n backend: IMemoryBackend<TKey, TValue>\n ): IMemoryBackend<TKey, TValue> {\n this.assertOpen();\n if (this.backends.has(domain)) {\n throw new Error(`nexus-memory: domain \"${domain}\" already registered`);\n }\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- See `register`.\n this.backends.set(domain, backend as IMemoryBackend<unknown, unknown>);\n return backend;\n }\n\n /**\n * Get a previously-registered backend. Returns `undefined` if the\n * domain isn't registered — callers should treat that as \"not yet\n * migrated to the unified contract.\"\n */\n get<TKey, TValue>(domain: string): IMemoryBackend<TKey, TValue> | undefined {\n this.assertOpen();\n const backend = this.backends.get(domain);\n return backend as IMemoryBackend<TKey, TValue> | undefined;\n }\n\n /** List all registered domains. Useful for `memory_stats`-style readers. */\n domains(): readonly string[] {\n return [...this.backends.keys()];\n }\n\n /**\n * Close every registered backend and the shared SQLite handle. After\n * `close()` the registry rejects all further operations.\n *\n * Idempotent only once it has actually SUCCEEDED (#5776). It used to set\n * `this.closed = true` before the loop and `await` each backend in turn, so\n * one rejecting backend aborted the loop: every backend after it stayed open,\n * `this.backends` was never cleared, and the shared SQLite handle — the one\n * thing the registry itself owns — never closed. The retry a shutdown path\n * would naturally make then hit `if (this.closed) return` and RESOLVED,\n * reporting success for a close that never happened.\n *\n * Now every backend is attempted (`allSettled`), the owned handle closes\n * regardless, and the registry IS marked closed — because by then everything\n * it owns really is shut — but the first backend failure is re-thrown so the\n * caller learns about it. A retry then returns early and resolves, which is\n * honest: there is genuinely nothing left to close. Marking it open instead\n * would be worse than the original bug — `assertOpen` would pass and the next\n * operation would run against a closed SQLite handle.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n const results = await Promise.allSettled(\n [...this.backends.values()].map((backend) => backend.close())\n );\n // The shared handle is ours to close whether or not a backend misbehaved;\n // leaking it is what turns one bad backend into a stuck process.\n this.backends.clear();\n if (this.db !== undefined) this.db.close();\n\n // Set BEFORE the throw: everything this registry owns is shut, so any\n // further operation must reject rather than reach a closed handle.\n this.closed = true;\n\n const failures = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');\n if (failures.length > 0) {\n throw failures[0]?.reason instanceof Error\n ? failures[0].reason\n : new Error(`nexus-memory: ${String(failures.length)} backend(s) failed to close`);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error('nexus-memory: registry is closed');\n }\n }\n}\n\n// ============================================================================\n// Singleton accessor\n// ============================================================================\n\nlet sharedRegistry: MemoryRegistry | null = null;\n\n/**\n * Get the process-wide shared registry. Initializes on first call with\n * `dbPath` from `NEXUS_DATA_DIR` (defaults to `~/.nexus-agents/memory/memory.db`)\n * unless `setMemoryRegistry` was called first.\n *\n * Test code should call `setMemoryRegistry(createInMemoryMemoryRegistry())`\n * in `beforeEach` — this matches the existing `setOutcomeStore` pattern.\n */\nexport function getMemoryRegistry(): MemoryRegistry {\n if (sharedRegistry === null) {\n // Default path resolution happens here, NOT at module load — so tests\n // that call `setMemoryRegistry` before any `getMemoryRegistry` see\n // their in-memory instance, not a side-effectful production path.\n const dbPath = resolveDefaultDbPath();\n sharedRegistry = new MemoryRegistry({ dbPath });\n }\n return sharedRegistry;\n}\n\n/**\n * Inject a registry. Used by tests to swap in `InMemoryBackend`-backed\n * registries. After test, call again with `null` to reset, or call\n * `closeMemoryRegistry()` to dispose.\n */\nexport function setMemoryRegistry(registry: MemoryRegistry | null): void {\n sharedRegistry = registry;\n}\n\n/**\n * True when the shared registry has already been constructed or injected.\n * Lets nexus-agents inject the canonical {@link nexusDataPath}-resolved DB\n * path (#3995) WITHOUT clobbering a registry a test already set, and without\n * triggering the lazy default-path resolution that `getMemoryRegistry()`\n * would. Read-only — keeps nexus-memory dep-free.\n */\nexport function hasMemoryRegistry(): boolean {\n return sharedRegistry !== null;\n}\n\n/** Close + null out the shared registry. Idempotent. */\nexport async function closeMemoryRegistry(): Promise<void> {\n if (sharedRegistry !== null) {\n await sharedRegistry.close();\n sharedRegistry = null;\n }\n}\n\nfunction resolveDefaultDbPath(): string {\n // Match `nexus-agents`'s `nexusDataPath` convention without importing it\n // (keep nexus-memory free of inter-package deps for nexus-eval-* reuse).\n const root = process.env['NEXUS_DATA_DIR'] ?? `${process.env['HOME'] ?? '/tmp'}/.nexus-agents`;\n return `${root}/memory/memory.db`;\n}\n","/**\n * Test factories. Production code uses {@link getMemoryRegistry} from\n * `./registry.js`; tests use these helpers to avoid touching disk.\n *\n * @module nexus-memory/factory\n */\n\nimport { MemoryRegistry } from './registry.js';\n\n/**\n * Create a registry that lives entirely in memory. Every `register()`\n * call returns an {@link InMemoryBackend}; nothing is persisted.\n *\n * Use this in `beforeEach`:\n *\n * ```ts\n * beforeEach(() => {\n * setMemoryRegistry(createInMemoryMemoryRegistry());\n * });\n * afterEach(async () => {\n * await closeMemoryRegistry();\n * });\n * ```\n */\nexport function createInMemoryMemoryRegistry(): MemoryRegistry {\n return new MemoryRegistry({\n /* no dbPath → InMemoryBackend per domain */\n });\n}\n\n/**\n * Create a SQLite-backed registry rooted at `dbPath`. Pass `':memory:'`\n * for tests that need to exercise the SQLite code path (e.g.,\n * migration tests, parity tests).\n */\nexport function createSqliteMemoryRegistry(dbPath: string): MemoryRegistry {\n return new MemoryRegistry({ dbPath });\n}\n","/**\n * One-shot importer scaffold. Each Phase 4+ migration registers its own\n * importer here; the registry runs them on first launch (after a marker\n * file check) and renames source files to `.bak.<timestamp>` once\n * complete.\n *\n * This file ships the skeleton + the marker-file logic; concrete\n * importers (MobiMem JSON, OutcomeStore JSONL, agentic.db, etc.) plug in\n * during their respective migration phases.\n *\n * @module nexus-memory/importer\n */\n\nimport { existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { MemoryRegistry } from './registry.js';\n\nexport interface ImporterRun {\n readonly domain: string;\n readonly rowsImported: number;\n readonly sourcePathBackup: string | null;\n}\n\nexport interface Importer {\n /** Stable identifier — used in the marker filename to track completion. */\n readonly id: string;\n /** Logical domain this importer targets in the registry. */\n readonly domain: string;\n /**\n * Run the import. Implementations: (1) check if source data exists,\n * (2) parse + validate it, (3) write rows into the registry's backend,\n * (4) rename source to `.bak.<timestamp>` and return the backup path.\n * Idempotent — if marker file says we already ran, the registry skips it.\n */\n run(registry: MemoryRegistry): Promise<ImporterRun>;\n}\n\nconst importers = new Map<string, Importer>();\n\n/** Register an importer. Phase 4+ migrations call this at module load. */\nexport function registerImporter(importer: Importer): void {\n if (importers.has(importer.id)) {\n throw new Error(`nexus-memory: importer \"${importer.id}\" already registered`);\n }\n importers.set(importer.id, importer);\n}\n\n/** For tests: clear all registered importers. */\nexport function resetImporters(): void {\n importers.clear();\n}\n\n/** Snapshot of registered importer IDs. */\nexport function listImporters(): readonly string[] {\n return [...importers.keys()];\n}\n\nexport interface RunImportersOptions {\n /**\n * Directory holding `.imported-{id}` marker files. Defaults to the\n * registry's data dir; tests should override.\n */\n readonly markerDir: string;\n /** Skip the marker check (forces re-run). Tests only. */\n readonly force?: boolean;\n}\n\n/**\n * Run every registered importer that hasn't yet completed (per marker\n * file). Returns the list of runs that actually executed.\n *\n * Failures are NOT fatal — a single importer's exception is logged via\n * the returned `errors` array; other importers still get a chance to run.\n */\nexport async function runImporters(\n registry: MemoryRegistry,\n options: RunImportersOptions\n): Promise<{ runs: readonly ImporterRun[]; errors: readonly { id: string; error: Error }[] }> {\n mkdirSync(options.markerDir, { recursive: true });\n const runs: ImporterRun[] = [];\n const errors: { id: string; error: Error }[] = [];\n for (const importer of importers.values()) {\n const marker = join(options.markerDir, `.imported-${importer.id}`);\n if (options.force !== true && existsSync(marker)) continue;\n try {\n const run = await importer.run(registry);\n writeMarker(marker, run);\n runs.push(run);\n } catch (err) {\n errors.push({ id: importer.id, error: err instanceof Error ? err : new Error(String(err)) });\n }\n }\n return { runs, errors };\n}\n\nfunction writeMarker(path: string, run: ImporterRun): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(\n path,\n JSON.stringify({ ...run, completedAt: new Date().toISOString() }, null, 2),\n 'utf-8'\n );\n}\n\n/**\n * Rename a source file to `.bak.<unix-timestamp>`. Used by concrete\n * importers after a successful migration. Returns the backup path, or\n * `null` when the source doesn't exist.\n */\nexport function backupSourceFile(sourcePath: string): string | null {\n if (!existsSync(sourcePath)) return null;\n const backup = `${sourcePath}.bak.${String(Date.now())}`;\n renameSync(sourcePath, backup);\n return backup;\n}\n"],"mappings":";AEyBA,SAAS,qBAAqB;AA8C9B,SAAS,iBAAiB;AAC1B,SAAS,eAAe;AI3DxB,SAAS,YAAY,aAAAA,YAAW,YAAY,qBAAqB;AACjE,SAAS,WAAAC,UAAS,YAAY;ANE9B,IAAM,oBAAoB;AAC1B,IAAM,wBAAwB;AAG9B,IAAM,WAAW,oBAAI,IAAiC;AACtD,IAAM,YAAY,oBAAI,IAAyB;AAI/C,SAAS,cAAuB;AAC9B,SAAO,QAAQ,IAAI,yBAAyB,MAAM;AACpD;AAEA,SAAS,WAAW,QAAgB,IAA+B;AACjE,SAAO,G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18
|
// src/config/model-parameter-support.ts
|
|
19
19
|
function parseClaudeMajorMinor(bareId) {
|
|
@@ -834,4 +834,4 @@ export {
|
|
|
834
834
|
DEFAULT_COLLECT_STREAM_MAX_CHUNKS,
|
|
835
835
|
collectStream
|
|
836
836
|
};
|
|
837
|
-
//# sourceMappingURL=chunk-
|
|
837
|
+
//# sourceMappingURL=chunk-MZ4X6UDA.js.map
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
TASK_CATEGORIES,
|
|
3
3
|
getAdaptiveBonus,
|
|
4
4
|
getOutcomeStore
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
6
6
|
|
|
7
7
|
// src/cli/doctor-deep.ts
|
|
8
8
|
var CLI_NAMES = ["claude", "gemini", "codex", "opencode"];
|
|
@@ -106,4 +106,4 @@ export {
|
|
|
106
106
|
runDeepDiagnostics,
|
|
107
107
|
formatDeepDiagnostics
|
|
108
108
|
};
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-NTK3UA6R.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
getErrorMessage,
|
|
5
5
|
getTimeProvider,
|
|
6
6
|
ok
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
8
8
|
|
|
9
9
|
// src/context/session-memory.ts
|
|
10
10
|
import * as fs from "node:fs";
|
|
@@ -370,4 +370,4 @@ export {
|
|
|
370
370
|
SessionMemory,
|
|
371
371
|
createSessionMemory
|
|
372
372
|
};
|
|
373
|
-
//# sourceMappingURL=chunk-
|
|
373
|
+
//# sourceMappingURL=chunk-PGMDJ7LH.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
computeCostDetail,
|
|
3
3
|
priceBasisOf
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-K46JS3AR.js";
|
|
5
5
|
import {
|
|
6
6
|
allOf
|
|
7
7
|
} from "./chunk-OQB3XC5O.js";
|
|
@@ -23,26 +23,26 @@ import {
|
|
|
23
23
|
toolSuccessStructured,
|
|
24
24
|
withProgressHeartbeat,
|
|
25
25
|
wrapToolWithTimeout
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-QGXQMRA7.js";
|
|
27
27
|
import {
|
|
28
28
|
VERSION
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-TG4IGHLY.js";
|
|
30
30
|
import {
|
|
31
31
|
assessPanelIndependence,
|
|
32
32
|
countDistinctModels,
|
|
33
33
|
createEvent,
|
|
34
34
|
getGlobalRegistry
|
|
35
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-2SEIMNKE.js";
|
|
36
36
|
import {
|
|
37
37
|
getToolMemory
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-YGJRO5JK.js";
|
|
39
39
|
import {
|
|
40
40
|
authRemediation,
|
|
41
41
|
delay,
|
|
42
42
|
getAvailableClis,
|
|
43
43
|
sleep,
|
|
44
44
|
withTimeout
|
|
45
|
-
} from "./chunk-
|
|
45
|
+
} from "./chunk-2MNXFMLO.js";
|
|
46
46
|
import {
|
|
47
47
|
AgentError,
|
|
48
48
|
CLI_NAMES,
|
|
@@ -70,7 +70,7 @@ import {
|
|
|
70
70
|
registerPersistentOutcomeStoreFactory,
|
|
71
71
|
resolveClassGuardMs,
|
|
72
72
|
resolveVoteTimeout
|
|
73
|
-
} from "./chunk-
|
|
73
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
74
74
|
import {
|
|
75
75
|
ensureLearningDir,
|
|
76
76
|
getOutcomesFile
|
|
@@ -7253,7 +7253,7 @@ function logPartialProposal(bounded, log) {
|
|
|
7253
7253
|
}
|
|
7254
7254
|
async function runContrarianCheck(proposal, log) {
|
|
7255
7255
|
try {
|
|
7256
|
-
const { executeExpert } = await import("./expert-bridge-
|
|
7256
|
+
const { executeExpert } = await import("./expert-bridge-RWAYSGUI.js");
|
|
7257
7257
|
const bounded = boundArtifactForReview(proposal, CONTRARIAN_PROPOSAL_BUDGET, "proposal");
|
|
7258
7258
|
logPartialProposal(bounded, log);
|
|
7259
7259
|
const result = await executeExpert("architecture", buildContrarianPrompt(bounded));
|
|
@@ -7850,4 +7850,4 @@ export {
|
|
|
7850
7850
|
CONSENSUS_VOTE_TOOL_SCHEMA,
|
|
7851
7851
|
registerConsensusVoteTool
|
|
7852
7852
|
};
|
|
7853
|
-
//# sourceMappingURL=chunk-
|
|
7853
|
+
//# sourceMappingURL=chunk-PUGFOPEA.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
VERSION
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-TG4IGHLY.js";
|
|
4
4
|
import {
|
|
5
5
|
emitClawGuardViolation
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-3AWXED62.js";
|
|
7
7
|
import {
|
|
8
8
|
CACHE_TIMEOUTS,
|
|
9
9
|
MCP_TIMEOUTS,
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
getTimeProvider,
|
|
20
20
|
ok,
|
|
21
21
|
resolveToolClassGuardMs
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
23
23
|
import {
|
|
24
24
|
getNexusDataDir
|
|
25
25
|
} from "./chunk-BTYRPZON.js";
|
|
@@ -2317,4 +2317,4 @@ export {
|
|
|
2317
2317
|
VOTING_THRESHOLDS,
|
|
2318
2318
|
ConsensusMetricsSchema
|
|
2319
2319
|
};
|
|
2320
|
-
//# sourceMappingURL=chunk-
|
|
2320
|
+
//# sourceMappingURL=chunk-QGXQMRA7.js.map
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveCliSlot
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-E3JBFLMJ.js";
|
|
4
4
|
import {
|
|
5
5
|
createLogger,
|
|
6
6
|
getTimeProvider,
|
|
7
7
|
isRateLimitText
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
9
9
|
|
|
10
10
|
// src/pipeline/expert-bridge.ts
|
|
11
11
|
function resolveCliFromModelString(model) {
|
|
@@ -21,7 +21,7 @@ async function getMcpConfigPath() {
|
|
|
21
21
|
if (cachedMcpConfigPath !== null) return cachedMcpConfigPath;
|
|
22
22
|
mcpConfigInitPromise ??= (async () => {
|
|
23
23
|
try {
|
|
24
|
-
const { generateMcpConfig } = await import("./child-mcp-config-
|
|
24
|
+
const { generateMcpConfig } = await import("./child-mcp-config-KMFC3V5X.js");
|
|
25
25
|
const config = await generateMcpConfig();
|
|
26
26
|
cachedMcpConfigPath = config.configPath;
|
|
27
27
|
cachedMcpConfigCleanup = config.cleanup;
|
|
@@ -93,8 +93,8 @@ var routerInitPromise = null;
|
|
|
93
93
|
async function getRouter() {
|
|
94
94
|
if (cachedRouter !== null) return cachedRouter;
|
|
95
95
|
routerInitPromise ??= (async () => {
|
|
96
|
-
const { createAllAdapters } = await import("./factory-
|
|
97
|
-
const { createCompositeRouter } = await import("./composite-router-
|
|
96
|
+
const { createAllAdapters } = await import("./factory-EBTRU3DD.js");
|
|
97
|
+
const { createCompositeRouter } = await import("./composite-router-AXNQ4JGW.js");
|
|
98
98
|
const adapters = createAllAdapters();
|
|
99
99
|
if (adapters.size === 0) {
|
|
100
100
|
routerInitPromise = null;
|
|
@@ -102,7 +102,7 @@ async function getRouter() {
|
|
|
102
102
|
}
|
|
103
103
|
cachedRouter = adaptCompositeRouter(createCompositeRouter(adapters));
|
|
104
104
|
try {
|
|
105
|
-
const { createCliCircuitBreakerIntegration } = await import("./cli-circuit-breaker-
|
|
105
|
+
const { createCliCircuitBreakerIntegration } = await import("./cli-circuit-breaker-TXONSAMR.js");
|
|
106
106
|
cachedCircuitBreaker = createCliCircuitBreakerIntegration([...adapters.values()]);
|
|
107
107
|
} catch (error) {
|
|
108
108
|
const msg = error instanceof Error ? error.message : String(error);
|
|
@@ -213,4 +213,4 @@ export {
|
|
|
213
213
|
tokenSplitFromUsage,
|
|
214
214
|
executeExpert
|
|
215
215
|
};
|
|
216
|
-
//# sourceMappingURL=chunk-
|
|
216
|
+
//# sourceMappingURL=chunk-QLF22ILR.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getRandomProvider,
|
|
3
3
|
getTimeProvider
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
5
5
|
|
|
6
6
|
// src/utils/id-utils.ts
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
@@ -24,4 +24,4 @@ export {
|
|
|
24
24
|
generateHyphenId,
|
|
25
25
|
generateUUID
|
|
26
26
|
};
|
|
27
|
-
//# sourceMappingURL=chunk-
|
|
27
|
+
//# sourceMappingURL=chunk-R4QUX6Z5.js.map
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
toolStructuredError,
|
|
8
8
|
toolSuccessStructured,
|
|
9
9
|
wrapToolWithTimeout
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-QGXQMRA7.js";
|
|
11
11
|
import {
|
|
12
12
|
JsonlStore,
|
|
13
13
|
SECURITY_KEYWORDS,
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
getTimeProvider,
|
|
21
21
|
isDeclaredNeverDeprecate,
|
|
22
22
|
isRegisteredToolName
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
24
24
|
import {
|
|
25
25
|
getNexusDataDir,
|
|
26
26
|
nexusDataPath
|
|
@@ -2173,4 +2173,4 @@ export {
|
|
|
2173
2173
|
runImprovementReview,
|
|
2174
2174
|
registerImprovementReviewTool
|
|
2175
2175
|
};
|
|
2176
|
-
//# sourceMappingURL=chunk-
|
|
2176
|
+
//# sourceMappingURL=chunk-RJRKVBLP.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readOpenAICompatEnv
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-KGRJIYNF.js";
|
|
4
4
|
import {
|
|
5
5
|
allOf
|
|
6
6
|
} from "./chunk-OQB3XC5O.js";
|
|
@@ -8,14 +8,14 @@ import {
|
|
|
8
8
|
NODE_ENGINE_RANGE,
|
|
9
9
|
VERSION,
|
|
10
10
|
isNodeVersionSupported
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-TG4IGHLY.js";
|
|
12
12
|
import {
|
|
13
13
|
capitalize
|
|
14
14
|
} from "./chunk-7LP6VJRP.js";
|
|
15
15
|
import {
|
|
16
16
|
createAllAdapters,
|
|
17
17
|
probeCli
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-2MNXFMLO.js";
|
|
19
19
|
import {
|
|
20
20
|
getNexusTmpDir
|
|
21
21
|
} from "./chunk-T46RV7Y7.js";
|
|
@@ -30,7 +30,7 @@ import {
|
|
|
30
30
|
ok,
|
|
31
31
|
symbols,
|
|
32
32
|
writeLine
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-KHCFW5LJ.js";
|
|
34
34
|
import {
|
|
35
35
|
getLearningDir,
|
|
36
36
|
getOutcomesFile,
|
|
@@ -1227,13 +1227,13 @@ async function runDoctorFix(result) {
|
|
|
1227
1227
|
writeLine2("\u2500".repeat(40));
|
|
1228
1228
|
let fixCount = 0;
|
|
1229
1229
|
if (!result.dataDirectory.rootExists || result.dataDirectory.subdirectories.some((d) => !d.exists || !d.writable)) {
|
|
1230
|
-
const { initDataDirectories: initDataDirectories2, describeDataDirFix: describeDataDirFix2 } = await import("./setup-data-dir-
|
|
1230
|
+
const { initDataDirectories: initDataDirectories2, describeDataDirFix: describeDataDirFix2 } = await import("./setup-data-dir-GW2NJ3YM.js");
|
|
1231
1231
|
const outcome = describeDataDirFix2(initDataDirectories2());
|
|
1232
1232
|
writeLine2(outcome.line);
|
|
1233
1233
|
if (outcome.counted) fixCount++;
|
|
1234
1234
|
}
|
|
1235
1235
|
if (!result.configFile.found) {
|
|
1236
|
-
const { runConfigInitSync } = await import("./setup-config-
|
|
1236
|
+
const { runConfigInitSync } = await import("./setup-config-H2NNVJSV.js");
|
|
1237
1237
|
const configResult = runConfigInitSync(process.cwd(), false, false);
|
|
1238
1238
|
if (configResult.success && configResult.created) {
|
|
1239
1239
|
writeLine2(`\u2713 Generated config: ${configResult.path}`);
|
|
@@ -1329,4 +1329,4 @@ export {
|
|
|
1329
1329
|
startStdioServer,
|
|
1330
1330
|
closeServer
|
|
1331
1331
|
};
|
|
1332
|
-
//# sourceMappingURL=chunk-
|
|
1332
|
+
//# sourceMappingURL=chunk-TDVAJEQL.js.map
|