@remnic/core 9.3.717 → 9.3.719
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-boundary.d.ts +5 -5
- package/dist/access-boundary.js +9 -9
- package/dist/access-cli.js +23 -23
- package/dist/access-http.d.ts +5 -5
- package/dist/access-http.js +13 -13
- package/dist/access-mcp.d.ts +5 -5
- package/dist/access-mcp.js +12 -12
- package/dist/access-operations-batch.js +10 -10
- package/dist/access-operations.d.ts +5 -5
- package/dist/access-operations.js +11 -11
- package/dist/{access-service-d4Tk-Dlr.d.ts → access-service-CZbnt0t2.d.ts} +3 -3
- package/dist/access-service.d.ts +5 -5
- package/dist/access-service.js +8 -8
- package/dist/access-surface-catalog.d.ts +5 -5
- package/dist/action-confidence.d.ts +1 -1
- package/dist/active-memory-bridge.d.ts +1 -1
- package/dist/active-recall.d.ts +1 -1
- package/dist/active-recall.js +1 -1
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +4 -4
- package/dist/briefing.d.ts +3 -1
- package/dist/briefing.js +3 -3
- package/dist/buffer-surprise-report.d.ts +1 -1
- package/dist/buffer.d.ts +1 -1
- package/dist/calibration.d.ts +1 -1
- package/dist/capabilities.d.ts +1 -1
- package/dist/{catalog-CbR0CsUw.d.ts → catalog-CEYlMs9X.d.ts} +1 -1
- package/dist/causal-behavior.d.ts +1 -1
- package/dist/causal-consolidation.d.ts +1 -1
- package/dist/causal-consolidation.js +4 -4
- package/dist/{chunk-JEIROMLX.js → chunk-2COL35PK.js} +95 -9
- package/dist/chunk-2COL35PK.js.map +1 -0
- package/dist/{chunk-XZTUMWKQ.js → chunk-2PTBLS2S.js} +2 -2
- package/dist/{chunk-2Y6LMOQQ.js → chunk-2VHMVWPU.js} +2 -2
- package/dist/{chunk-6UU43ZGD.js → chunk-4KZGLDJJ.js} +2 -2
- package/dist/{chunk-K44MIN6D.js → chunk-5RHM43BJ.js} +3 -3
- package/dist/{chunk-2B43BYYZ.js → chunk-72VDBALG.js} +18 -18
- package/dist/{chunk-UY4JMEAK.js → chunk-7EEVXW7X.js} +2 -2
- package/dist/{chunk-XCTDHF7U.js → chunk-A5TUPZ3N.js} +33 -1
- package/dist/chunk-A5TUPZ3N.js.map +1 -0
- package/dist/{chunk-WI4QX7GH.js → chunk-A66YRSOS.js} +2 -2
- package/dist/{chunk-EM22PCQR.js → chunk-ANI5DUAE.js} +8 -6
- package/dist/{chunk-EM22PCQR.js.map → chunk-ANI5DUAE.js.map} +1 -1
- package/dist/{chunk-VZQXJNBD.js → chunk-APUJIMDM.js} +2 -2
- package/dist/{chunk-MPHDVHIB.js → chunk-DIFU33GU.js} +2 -2
- package/dist/{chunk-DXGS5YOQ.js → chunk-EH27LHML.js} +2 -2
- package/dist/{chunk-YAINYEM3.js → chunk-F3PVXKHP.js} +25 -1398
- package/dist/chunk-F3PVXKHP.js.map +1 -0
- package/dist/{chunk-DZYARLJ7.js → chunk-HLIR3RJ7.js} +2 -2
- package/dist/{chunk-6FUJ2VYY.js → chunk-JAKYZGV4.js} +3 -3
- package/dist/{chunk-ZAVTEQFM.js → chunk-JIZGYQYH.js} +3 -3
- package/dist/{chunk-QOIONSOI.js → chunk-KRGC4EDX.js} +2 -2
- package/dist/{chunk-AJOIM6UR.js → chunk-L5ASZA2F.js} +2 -2
- package/dist/{chunk-I56LKMF7.js → chunk-LXSG4L55.js} +2 -2
- package/dist/{chunk-MSVSP5VO.js → chunk-N3DUH6OO.js} +1 -1
- package/dist/chunk-N3DUH6OO.js.map +1 -0
- package/dist/{chunk-CTUWGJRI.js → chunk-NFRBADNR.js} +166 -28
- package/dist/chunk-NFRBADNR.js.map +1 -0
- package/dist/chunk-OJU73BUX.js +1688 -0
- package/dist/chunk-OJU73BUX.js.map +1 -0
- package/dist/{chunk-JVEMUX6L.js → chunk-OZ2KQ7HF.js} +2 -2
- package/dist/{chunk-OUDAU3T5.js → chunk-P5IPFZVH.js} +4 -4
- package/dist/{chunk-KHQ433G5.js → chunk-REWQAFSA.js} +2 -2
- package/dist/{chunk-V7GDTQ6I.js → chunk-S35FX6MU.js} +2 -2
- package/dist/{chunk-MTHNJCOJ.js → chunk-S3OPGGZB.js} +2 -2
- package/dist/{chunk-ZXLSNG3T.js → chunk-U5H7WHTS.js} +6 -4
- package/dist/{chunk-ZXLSNG3T.js.map → chunk-U5H7WHTS.js.map} +1 -1
- package/dist/{chunk-BZAK3RBN.js → chunk-UCJ5CDTK.js} +6 -6
- package/dist/{chunk-BF2426TN.js → chunk-URM3HW2R.js} +2 -2
- package/dist/{chunk-VO4UICII.js → chunk-YTZLBBEB.js} +2 -2
- package/dist/{chunk-OC56UWV5.js → chunk-YYOK4GVF.js} +2 -2
- package/dist/{cli-insNLYs6.d.ts → cli-1orcdXOY.d.ts} +3 -3
- package/dist/cli.d.ts +6 -6
- package/dist/cli.js +27 -27
- package/dist/compounding/engine.d.ts +1 -1
- package/dist/compounding/engine.js +3 -3
- package/dist/compounding/preference-consolidator.d.ts +1 -1
- package/dist/compression-optimizer.d.ts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/config.js +1 -1
- package/dist/connectors/codex-materialize-runner.d.ts +1 -1
- package/dist/connectors/codex-materialize-runner.js +3 -3
- package/dist/connectors/codex-materialize.d.ts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/connectors/index.js +3 -3
- package/dist/consolidation-provenance-check.d.ts +1 -1
- package/dist/consolidation-undo.d.ts +1 -1
- package/dist/contradiction/index.d.ts +1 -1
- package/dist/conversation-index/backend.d.ts +1 -1
- package/dist/conversation-index/chunker.d.ts +1 -1
- package/dist/conversation-index/faiss-adapter.d.ts +1 -1
- package/dist/conversation-index/indexer.d.ts +1 -1
- package/dist/conversation-index/search.d.ts +1 -1
- package/dist/day-summary.d.ts +1 -1
- package/dist/delinearize.d.ts +1 -1
- package/dist/direct-answer-wiring.d.ts +1 -1
- package/dist/direct-answer.d.ts +1 -1
- package/dist/embedding-fallback.d.ts +1 -1
- package/dist/enrichment/index.d.ts +1 -1
- package/dist/entity-retrieval.d.ts +1 -1
- package/dist/entity-retrieval.js +3 -3
- package/dist/entity-schema.d.ts +1 -1
- package/dist/explicit-capture.d.ts +4 -4
- package/dist/extraction-faithfulness.d.ts +1 -1
- package/dist/extraction-judge-telemetry.d.ts +1 -1
- package/dist/extraction-judge-training.d.ts +1 -1
- package/dist/extraction-judge.d.ts +1 -1
- package/dist/extraction.d.ts +1 -1
- package/dist/fallback-llm.d.ts +1 -1
- package/dist/identity-continuity.d.ts +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/index.d.ts +9 -9
- package/dist/index.js +33 -33
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/maintenance/memory-governance.d.ts +1 -1
- package/dist/maintenance/memory-governance.js +3 -3
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +3 -3
- package/dist/maintenance/rebuild-memory-projection.js +4 -4
- package/dist/mcp-memory-inspector-app.d.ts +5 -5
- package/dist/memory-action-policy.d.ts +1 -1
- package/dist/memory-cache.d.ts +1 -1
- package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-provenance.d.ts +1 -1
- package/dist/memory-worth-outcomes.d.ts +1 -1
- package/dist/models-json.d.ts +1 -1
- package/dist/namespaces/migrate.d.ts +2 -2
- package/dist/namespaces/migrate.js +4 -4
- package/dist/namespaces/principal.d.ts +1 -1
- package/dist/namespaces/search.d.ts +1 -1
- package/dist/namespaces/storage.d.ts +2 -2
- package/dist/namespaces/storage.js +3 -3
- package/dist/native-knowledge.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +1 -1
- package/dist/operator-toolkit.js +9 -9
- package/dist/orchestration/maintenance.d.ts +2 -2
- package/dist/orchestration/maintenance.js +5 -5
- package/dist/{orchestrator-XPKhY2OV.d.ts → orchestrator-kOxredSr.d.ts} +20 -3
- package/dist/orchestrator.d.ts +4 -4
- package/dist/orchestrator.js +16 -16
- package/dist/patterns-cli.d.ts +1 -1
- package/dist/policy-runtime.d.ts +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +1 -1
- package/dist/recall-disclosure-escalation.d.ts +1 -1
- package/dist/recall-explain-renderer.d.ts +1 -1
- package/dist/recall-explain-renderer.js +3 -3
- package/dist/recall-planner-llm.d.ts +1 -1
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-cli.js +4 -4
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray-renderer.js +3 -3
- package/dist/recall-xray.d.ts +1 -1
- package/dist/recall-xray.js +2 -2
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/resume-bundles.js +2 -2
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/schemas.d.ts +22 -22
- package/dist/search/embed-helper.d.ts +1 -1
- package/dist/search/factory.d.ts +1 -1
- package/dist/search/index.d.ts +1 -1
- package/dist/search/lancedb-backend.d.ts +1 -1
- package/dist/search/meilisearch-backend.d.ts +1 -1
- package/dist/search/noop-backend.d.ts +1 -1
- package/dist/search/orama-backend.d.ts +1 -1
- package/dist/search/port.d.ts +1 -1
- package/dist/search/remote-backend.d.ts +1 -1
- package/dist/{semantic-consolidation-DSjMDZ1u.d.ts → semantic-consolidation-B58v3S-a.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +2 -2
- package/dist/semantic-consolidation.js +4 -4
- package/dist/semantic-rule-promotion.js +3 -3
- package/dist/semantic-rule-verifier.d.ts +1 -1
- package/dist/semantic-rule-verifier.js +3 -3
- package/dist/session-observer-bands.d.ts +1 -1
- package/dist/session-observer-state.d.ts +1 -1
- package/dist/shared-context/manager.d.ts +1 -1
- package/dist/signal.d.ts +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/storage.js +2 -2
- package/dist/summarizer.d.ts +1 -1
- package/dist/summary-snapshot.d.ts +1 -1
- package/dist/temporal-supersession.d.ts +1 -1
- package/dist/temporal-validity.d.ts +1 -1
- package/dist/threading.d.ts +1 -1
- package/dist/tier-migration.d.ts +1 -1
- package/dist/tier-routing.d.ts +1 -1
- package/dist/topics.d.ts +1 -1
- package/dist/transcript.d.ts +1 -1
- package/dist/transfer/types.d.ts +12 -12
- package/dist/{types-D9dwzU_x.d.ts → types-ACmDOScJ.d.ts} +36 -0
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/dist/verified-recall.js +3 -3
- package/package.json +2 -2
- package/src/briefing.ts +32 -0
- package/src/config.ts +32 -0
- package/src/correction/index.ts +24 -0
- package/src/correction/passive-capture.test.ts +500 -0
- package/src/correction/passive-capture.ts +335 -0
- package/src/correction/passive-correction-detector.test.ts +263 -0
- package/src/correction/passive-correction-detector.ts +325 -0
- package/src/correction/passive-correction-notifications.ts +123 -0
- package/src/orchestrator.ts +196 -12
- package/src/types.ts +36 -0
- package/dist/chunk-2KF4HDG2.js +0 -24
- package/dist/chunk-2KF4HDG2.js.map +0 -1
- package/dist/chunk-CTUWGJRI.js.map +0 -1
- package/dist/chunk-JEIROMLX.js.map +0 -1
- package/dist/chunk-MSVSP5VO.js.map +0 -1
- package/dist/chunk-XCTDHF7U.js.map +0 -1
- package/dist/chunk-YAINYEM3.js.map +0 -1
- /package/dist/{chunk-XZTUMWKQ.js.map → chunk-2PTBLS2S.js.map} +0 -0
- /package/dist/{chunk-2Y6LMOQQ.js.map → chunk-2VHMVWPU.js.map} +0 -0
- /package/dist/{chunk-6UU43ZGD.js.map → chunk-4KZGLDJJ.js.map} +0 -0
- /package/dist/{chunk-K44MIN6D.js.map → chunk-5RHM43BJ.js.map} +0 -0
- /package/dist/{chunk-2B43BYYZ.js.map → chunk-72VDBALG.js.map} +0 -0
- /package/dist/{chunk-UY4JMEAK.js.map → chunk-7EEVXW7X.js.map} +0 -0
- /package/dist/{chunk-WI4QX7GH.js.map → chunk-A66YRSOS.js.map} +0 -0
- /package/dist/{chunk-VZQXJNBD.js.map → chunk-APUJIMDM.js.map} +0 -0
- /package/dist/{chunk-MPHDVHIB.js.map → chunk-DIFU33GU.js.map} +0 -0
- /package/dist/{chunk-DXGS5YOQ.js.map → chunk-EH27LHML.js.map} +0 -0
- /package/dist/{chunk-DZYARLJ7.js.map → chunk-HLIR3RJ7.js.map} +0 -0
- /package/dist/{chunk-6FUJ2VYY.js.map → chunk-JAKYZGV4.js.map} +0 -0
- /package/dist/{chunk-ZAVTEQFM.js.map → chunk-JIZGYQYH.js.map} +0 -0
- /package/dist/{chunk-QOIONSOI.js.map → chunk-KRGC4EDX.js.map} +0 -0
- /package/dist/{chunk-AJOIM6UR.js.map → chunk-L5ASZA2F.js.map} +0 -0
- /package/dist/{chunk-I56LKMF7.js.map → chunk-LXSG4L55.js.map} +0 -0
- /package/dist/{chunk-JVEMUX6L.js.map → chunk-OZ2KQ7HF.js.map} +0 -0
- /package/dist/{chunk-OUDAU3T5.js.map → chunk-P5IPFZVH.js.map} +0 -0
- /package/dist/{chunk-KHQ433G5.js.map → chunk-REWQAFSA.js.map} +0 -0
- /package/dist/{chunk-V7GDTQ6I.js.map → chunk-S35FX6MU.js.map} +0 -0
- /package/dist/{chunk-MTHNJCOJ.js.map → chunk-S3OPGGZB.js.map} +0 -0
- /package/dist/{chunk-BZAK3RBN.js.map → chunk-UCJ5CDTK.js.map} +0 -0
- /package/dist/{chunk-BF2426TN.js.map → chunk-URM3HW2R.js.map} +0 -0
- /package/dist/{chunk-VO4UICII.js.map → chunk-YTZLBBEB.js.map} +0 -0
- /package/dist/{chunk-OC56UWV5.js.map → chunk-YYOK4GVF.js.map} +0 -0
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
} from "./chunk-H7XKCNR6.js";
|
|
23
23
|
import {
|
|
24
24
|
toRecallExplainJson
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-LXSG4L55.js";
|
|
26
26
|
import {
|
|
27
27
|
buildProposedActions,
|
|
28
28
|
buildQualityScore,
|
|
@@ -30,10 +30,12 @@ import {
|
|
|
30
30
|
listMemoryGovernanceRuns,
|
|
31
31
|
readMemoryGovernanceRunArtifact,
|
|
32
32
|
runMemoryGovernance
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-2PTBLS2S.js";
|
|
34
34
|
import {
|
|
35
|
-
clusterByKey
|
|
36
|
-
|
|
35
|
+
clusterByKey,
|
|
36
|
+
createCorrectionService,
|
|
37
|
+
isCorrectionFeatureEnabled
|
|
38
|
+
} from "./chunk-OJU73BUX.js";
|
|
37
39
|
import {
|
|
38
40
|
getTrustZoneStoreStatus,
|
|
39
41
|
isTrustZoneName,
|
|
@@ -48,7 +50,7 @@ import {
|
|
|
48
50
|
} from "./chunk-FF4KLI5W.js";
|
|
49
51
|
import {
|
|
50
52
|
estimateRecallTokens
|
|
51
|
-
} from "./chunk-
|
|
53
|
+
} from "./chunk-L5ASZA2F.js";
|
|
52
54
|
import {
|
|
53
55
|
combineNamespaces,
|
|
54
56
|
defaultGitInvoker,
|
|
@@ -110,20 +112,17 @@ import {
|
|
|
110
112
|
buildBriefing,
|
|
111
113
|
parseBriefingFocus,
|
|
112
114
|
parseBriefingWindow
|
|
113
|
-
} from "./chunk-
|
|
115
|
+
} from "./chunk-2COL35PK.js";
|
|
114
116
|
import {
|
|
115
117
|
parseEntityFile
|
|
116
|
-
} from "./chunk-
|
|
118
|
+
} from "./chunk-YYOK4GVF.js";
|
|
117
119
|
import {
|
|
118
120
|
stripAttributesSuffix
|
|
119
121
|
} from "./chunk-SVOZFLIQ.js";
|
|
120
|
-
import {
|
|
121
|
-
serializeMutations
|
|
122
|
-
} from "./chunk-LTJAMRGI.js";
|
|
123
122
|
import {
|
|
124
123
|
DEFAULT_RECALL_DISCLOSURE,
|
|
125
124
|
isRecallDisclosure
|
|
126
|
-
} from "./chunk-
|
|
125
|
+
} from "./chunk-N3DUH6OO.js";
|
|
127
126
|
import {
|
|
128
127
|
inferMemoryStatus,
|
|
129
128
|
toMemoryPathRel
|
|
@@ -1153,12 +1152,12 @@ async function findArchitectureCardMemory(storage) {
|
|
|
1153
1152
|
});
|
|
1154
1153
|
return cards[0] ?? null;
|
|
1155
1154
|
}
|
|
1156
|
-
function createArchitectureVersioningHook(enabled, maxVersionsPerPage, sidecarDir, memoryDir,
|
|
1155
|
+
function createArchitectureVersioningHook(enabled, maxVersionsPerPage, sidecarDir, memoryDir, readFile4, writeVersion) {
|
|
1157
1156
|
return {
|
|
1158
1157
|
async snapshotIfExists(memory) {
|
|
1159
1158
|
if (!enabled) return;
|
|
1160
1159
|
try {
|
|
1161
|
-
const fullContent = await
|
|
1160
|
+
const fullContent = await readFile4(memory.path);
|
|
1162
1161
|
await writeVersion(
|
|
1163
1162
|
memory.path,
|
|
1164
1163
|
fullContent,
|
|
@@ -2140,1381 +2139,10 @@ async function deltaGet(request, ctx, codingContext) {
|
|
|
2140
2139
|
}
|
|
2141
2140
|
}
|
|
2142
2141
|
|
|
2143
|
-
// src/correction/correction-contract.ts
|
|
2144
|
-
var MEMORY_CATEGORIES = [
|
|
2145
|
-
"fact",
|
|
2146
|
-
"preference",
|
|
2147
|
-
"correction",
|
|
2148
|
-
"entity",
|
|
2149
|
-
"decision",
|
|
2150
|
-
"relationship",
|
|
2151
|
-
"principle",
|
|
2152
|
-
"commitment",
|
|
2153
|
-
"moment",
|
|
2154
|
-
"skill",
|
|
2155
|
-
"rule",
|
|
2156
|
-
"procedure",
|
|
2157
|
-
"reasoning_trace"
|
|
2158
|
-
];
|
|
2159
|
-
var CORRECTION_ACTION_KINDS = [
|
|
2160
|
-
"supersede",
|
|
2161
|
-
"edit",
|
|
2162
|
-
"retract",
|
|
2163
|
-
"rescope",
|
|
2164
|
-
"redaction_rule"
|
|
2165
|
-
];
|
|
2166
|
-
var CORRECTION_TEXT_MAX = 1e4;
|
|
2167
|
-
var REDACTION_PATTERN_MAX = 256;
|
|
2168
|
-
function validateCorrectionRequest(request) {
|
|
2169
|
-
if (!request || typeof request !== "object") {
|
|
2170
|
-
throw new CorrectionContractError("CorrectionRequest must be an object.");
|
|
2171
|
-
}
|
|
2172
|
-
const text = typeof request.text === "string" ? request.text.trim() : "";
|
|
2173
|
-
if (text.length === 0) {
|
|
2174
|
-
throw new CorrectionContractError("CorrectionRequest.text is required and must be non-empty.");
|
|
2175
|
-
}
|
|
2176
|
-
if (text.length > CORRECTION_TEXT_MAX) {
|
|
2177
|
-
throw new CorrectionContractError(
|
|
2178
|
-
`CorrectionRequest.text exceeds the ${CORRECTION_TEXT_MAX}-character limit (${text.length}).`
|
|
2179
|
-
);
|
|
2180
|
-
}
|
|
2181
|
-
const targetIds = Array.isArray(request.targetIds) ? request.targetIds.filter((id) => typeof id === "string" && id.length > 0) : void 0;
|
|
2182
|
-
if (targetIds !== void 0 && targetIds.length === 0) {
|
|
2183
|
-
return {
|
|
2184
|
-
text,
|
|
2185
|
-
...request.sessionKey ? { sessionKey: request.sessionKey } : {},
|
|
2186
|
-
...request.principal ? { principal: request.principal } : {},
|
|
2187
|
-
...request.namespace ? { namespace: request.namespace } : {}
|
|
2188
|
-
};
|
|
2189
|
-
}
|
|
2190
|
-
return {
|
|
2191
|
-
text,
|
|
2192
|
-
...targetIds ? { targetIds } : {},
|
|
2193
|
-
...request.sessionKey ? { sessionKey: request.sessionKey } : {},
|
|
2194
|
-
...request.principal ? { principal: request.principal } : {},
|
|
2195
|
-
...request.namespace ? { namespace: request.namespace } : {}
|
|
2196
|
-
};
|
|
2197
|
-
}
|
|
2198
|
-
function validateRedactionPattern(pattern) {
|
|
2199
|
-
if (typeof pattern !== "string") {
|
|
2200
|
-
throw new CorrectionContractError("redaction_rule.pattern must be a string.");
|
|
2201
|
-
}
|
|
2202
|
-
const trimmed = pattern.trim();
|
|
2203
|
-
if (trimmed.length === 0) {
|
|
2204
|
-
throw new CorrectionContractError("redaction_rule.pattern is required.");
|
|
2205
|
-
}
|
|
2206
|
-
if (trimmed.length > REDACTION_PATTERN_MAX) {
|
|
2207
|
-
throw new CorrectionContractError(
|
|
2208
|
-
`redaction_rule.pattern exceeds the ${REDACTION_PATTERN_MAX}-character bound.`
|
|
2209
|
-
);
|
|
2210
|
-
}
|
|
2211
|
-
if (isRegexLike(trimmed) && isOverlyBroadRegex(trimmed)) {
|
|
2212
|
-
throw new CorrectionContractError(
|
|
2213
|
-
"redaction_rule.pattern is too broad \u2014 use a bounded literal or a more specific pattern."
|
|
2214
|
-
);
|
|
2215
|
-
}
|
|
2216
|
-
return trimmed;
|
|
2217
|
-
}
|
|
2218
|
-
function isRegexLike(pattern) {
|
|
2219
|
-
if (pattern.startsWith("/") && pattern.endsWith("/") && pattern.length >= 2) return true;
|
|
2220
|
-
return /[\\^$.|?*+()[\]{}]/.test(pattern);
|
|
2221
|
-
}
|
|
2222
|
-
function isOverlyBroadRegex(pattern) {
|
|
2223
|
-
const body = pattern.startsWith("/") && pattern.endsWith("/") ? pattern.slice(1, -1) : pattern;
|
|
2224
|
-
if (/(?:^|[^\\])\(\.\*\)|(?:^|[^\\])\.\*|(?:^|[^\\])\.\+|^\.([^*+]?)$/.test(body)) {
|
|
2225
|
-
return true;
|
|
2226
|
-
}
|
|
2227
|
-
return false;
|
|
2228
|
-
}
|
|
2229
|
-
function validateCorrectionAction(action) {
|
|
2230
|
-
if (!action || typeof action !== "object") {
|
|
2231
|
-
throw new CorrectionContractError("CorrectionAction must be an object.");
|
|
2232
|
-
}
|
|
2233
|
-
const a = action;
|
|
2234
|
-
if (typeof a.kind !== "string" || !CORRECTION_ACTION_KINDS.includes(a.kind)) {
|
|
2235
|
-
throw new CorrectionContractError(
|
|
2236
|
-
`CorrectionAction.kind must be one of: ${CORRECTION_ACTION_KINDS.join(", ")}.`
|
|
2237
|
-
);
|
|
2238
|
-
}
|
|
2239
|
-
switch (a.kind) {
|
|
2240
|
-
case "supersede":
|
|
2241
|
-
if (typeof a.loserId !== "string" || a.loserId.length === 0) {
|
|
2242
|
-
throw new CorrectionContractError("supersede.loserId is required.");
|
|
2243
|
-
}
|
|
2244
|
-
if (a.replacement !== void 0 && a.replacement !== null) {
|
|
2245
|
-
validateMemoryDraft(a.replacement);
|
|
2246
|
-
}
|
|
2247
|
-
break;
|
|
2248
|
-
case "edit":
|
|
2249
|
-
if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
|
|
2250
|
-
throw new CorrectionContractError("edit.memoryId is required.");
|
|
2251
|
-
}
|
|
2252
|
-
if (typeof a.patch !== "string" || a.patch.length === 0) {
|
|
2253
|
-
throw new CorrectionContractError("edit.patch is required and must be non-empty.");
|
|
2254
|
-
}
|
|
2255
|
-
break;
|
|
2256
|
-
case "retract":
|
|
2257
|
-
if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
|
|
2258
|
-
throw new CorrectionContractError("retract.memoryId is required.");
|
|
2259
|
-
}
|
|
2260
|
-
break;
|
|
2261
|
-
case "rescope":
|
|
2262
|
-
if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
|
|
2263
|
-
throw new CorrectionContractError("rescope.memoryId is required.");
|
|
2264
|
-
}
|
|
2265
|
-
if (typeof a.toNamespace !== "string" || a.toNamespace.trim().length === 0) {
|
|
2266
|
-
throw new CorrectionContractError("rescope.toNamespace is required.");
|
|
2267
|
-
}
|
|
2268
|
-
break;
|
|
2269
|
-
case "redaction_rule":
|
|
2270
|
-
if (typeof a.pattern !== "string") {
|
|
2271
|
-
throw new CorrectionContractError("redaction_rule.pattern is required.");
|
|
2272
|
-
}
|
|
2273
|
-
validateRedactionPattern(a.pattern);
|
|
2274
|
-
break;
|
|
2275
|
-
}
|
|
2276
|
-
}
|
|
2277
|
-
function validateMemoryDraft(draft) {
|
|
2278
|
-
if (!draft || typeof draft !== "object") {
|
|
2279
|
-
throw new CorrectionContractError("MemoryDraft must be an object.");
|
|
2280
|
-
}
|
|
2281
|
-
const d = draft;
|
|
2282
|
-
if (typeof d.content !== "string" || d.content.trim().length === 0) {
|
|
2283
|
-
throw new CorrectionContractError("MemoryDraft.content is required and must be non-empty.");
|
|
2284
|
-
}
|
|
2285
|
-
if (d.category !== void 0) {
|
|
2286
|
-
if (typeof d.category !== "string" || !MEMORY_CATEGORIES.includes(d.category)) {
|
|
2287
|
-
throw new CorrectionContractError(
|
|
2288
|
-
`MemoryDraft.category must be one of: ${MEMORY_CATEGORIES.join(", ")}.`
|
|
2289
|
-
);
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
if (d.confidence !== void 0 && (typeof d.confidence !== "number" || d.confidence < 0 || d.confidence > 1)) {
|
|
2293
|
-
throw new CorrectionContractError("MemoryDraft.confidence must be a number in [0, 1].");
|
|
2294
|
-
}
|
|
2295
|
-
if (d.tags !== void 0 && !Array.isArray(d.tags)) {
|
|
2296
|
-
throw new CorrectionContractError("MemoryDraft.tags must be an array.");
|
|
2297
|
-
}
|
|
2298
|
-
if (d.structuredAttributes !== void 0 && (typeof d.structuredAttributes !== "object" || d.structuredAttributes === null)) {
|
|
2299
|
-
throw new CorrectionContractError("MemoryDraft.structuredAttributes must be an object.");
|
|
2300
|
-
}
|
|
2301
|
-
}
|
|
2302
|
-
function deterministicFallbackPlan(args) {
|
|
2303
|
-
return {
|
|
2304
|
-
planId: newPlanId(),
|
|
2305
|
-
request: args.request,
|
|
2306
|
-
namespace: args.namespace,
|
|
2307
|
-
affected: args.affected,
|
|
2308
|
-
classification: "outdated",
|
|
2309
|
-
actions: [],
|
|
2310
|
-
diff: "",
|
|
2311
|
-
confidence: 0,
|
|
2312
|
-
warnings: [...args.warnings, "planner LLM unavailable \u2014 manual action selection required"],
|
|
2313
|
-
createdAt: args.createdAt,
|
|
2314
|
-
expiresAt: args.expiresAt,
|
|
2315
|
-
status: "pending"
|
|
2316
|
-
};
|
|
2317
|
-
}
|
|
2318
|
-
function newPlanId() {
|
|
2319
|
-
return `corr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
2320
|
-
}
|
|
2321
|
-
var CorrectionContractError = class extends Error {
|
|
2322
|
-
constructor(message) {
|
|
2323
|
-
super(message);
|
|
2324
|
-
this.name = "CorrectionContractError";
|
|
2325
|
-
}
|
|
2326
|
-
};
|
|
2327
|
-
|
|
2328
|
-
// src/correction/correction-planner.ts
|
|
2329
|
-
import { mkdir as mkdir2, readFile as readFile3, rename as rename2, unlink, readdir as readdir2, writeFile as writeFile2 } from "fs/promises";
|
|
2330
|
-
import path4 from "path";
|
|
2331
|
-
var CorrectionPlanner = class {
|
|
2332
|
-
constructor(deps) {
|
|
2333
|
-
this.deps = deps;
|
|
2334
|
-
}
|
|
2335
|
-
deps;
|
|
2336
|
-
/**
|
|
2337
|
-
* Plan a correction. `readableNamespaces` is the AUTHORIZED read scope the
|
|
2338
|
-
* service resolved for this caller; the planner never trusts a caller string.
|
|
2339
|
-
*/
|
|
2340
|
-
async plan(request, readableNamespaces) {
|
|
2341
|
-
const cleaned = validateCorrectionRequest(request);
|
|
2342
|
-
if (cleaned.text.length > CORRECTION_TEXT_MAX) {
|
|
2343
|
-
throw new CorrectionContractError("CorrectionRequest.text too long.");
|
|
2344
|
-
}
|
|
2345
|
-
if (cleaned.targetIds && cleaned.targetIds.length > this.deps.maxAffected) {
|
|
2346
|
-
throw new CorrectionContractError(
|
|
2347
|
-
`Correction target list (${cleaned.targetIds.length}) exceeds maxAffected (${this.deps.maxAffected}) \u2014 narrow the target set.`
|
|
2348
|
-
);
|
|
2349
|
-
}
|
|
2350
|
-
const namespaces = readableNamespaces;
|
|
2351
|
-
if (namespaces.length === 0) {
|
|
2352
|
-
throw new CorrectionContractError(
|
|
2353
|
-
"Correction requires at least one readable namespace \u2014 principal has no read scope."
|
|
2354
|
-
);
|
|
2355
|
-
}
|
|
2356
|
-
const located = await this.locateCandidates(cleaned, namespaces);
|
|
2357
|
-
if (located.candidates.length === 0) {
|
|
2358
|
-
return this.persist(
|
|
2359
|
-
this.emptyPlan(cleaned, namespaces[0], "no matching memories found for the correction text")
|
|
2360
|
-
);
|
|
2361
|
-
}
|
|
2362
|
-
const llm = await this.deps.classifyAndDraft({
|
|
2363
|
-
text: cleaned.text,
|
|
2364
|
-
candidates: located.candidates
|
|
2365
|
-
});
|
|
2366
|
-
for (const action of llm.actions) {
|
|
2367
|
-
validateCorrectionAction(action);
|
|
2368
|
-
if (action.kind === "redaction_rule") {
|
|
2369
|
-
validateRedactionPattern(action.pattern);
|
|
2370
|
-
}
|
|
2371
|
-
}
|
|
2372
|
-
const affected = this.deriveAffected(located.candidates, llm);
|
|
2373
|
-
const touchedCount = new Set(
|
|
2374
|
-
llm.actions.map(
|
|
2375
|
-
(a) => a.kind === "supersede" ? a.loserId : a.kind === "edit" || a.kind === "retract" || a.kind === "rescope" ? a.memoryId : null
|
|
2376
|
-
).filter((id) => id !== null)
|
|
2377
|
-
).size;
|
|
2378
|
-
if (touchedCount > this.deps.maxAffected) {
|
|
2379
|
-
throw new CorrectionContractError(
|
|
2380
|
-
`Correction touches ${touchedCount} memories, exceeding the maxAffected limit of ${this.deps.maxAffected}. Narrow the correction text or supply explicit targetIds.`
|
|
2381
|
-
);
|
|
2382
|
-
}
|
|
2383
|
-
const candidateIds = new Set(located.candidates.map((c) => c.memoryId));
|
|
2384
|
-
if (llm.actions.length > 0 && candidateIds.size > 0) {
|
|
2385
|
-
const filtered = llm.actions.filter((action) => {
|
|
2386
|
-
const id = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : null;
|
|
2387
|
-
return id === null || candidateIds.has(id);
|
|
2388
|
-
});
|
|
2389
|
-
if (filtered.length < llm.actions.length) {
|
|
2390
|
-
const dropped = llm.actions.length - filtered.length;
|
|
2391
|
-
llm.warnings = [...llm.warnings, `${dropped} action(s) targeted memories outside the located candidate set and were dropped (prompt-injection guard).`];
|
|
2392
|
-
llm.actions = filtered;
|
|
2393
|
-
}
|
|
2394
|
-
}
|
|
2395
|
-
const diff = llm.fallback ? "" : await this.deps.renderDiff({ candidates: located.candidates, actions: llm.actions });
|
|
2396
|
-
const createdAt = this.deps.now().toISOString();
|
|
2397
|
-
const expiresAt = new Date(
|
|
2398
|
-
this.deps.now().getTime() + this.deps.planTtlHours * 60 * 60 * 1e3
|
|
2399
|
-
).toISOString();
|
|
2400
|
-
const plan = llm.fallback ? deterministicFallbackPlan({
|
|
2401
|
-
request: cleaned,
|
|
2402
|
-
namespace: namespaces[0],
|
|
2403
|
-
affected,
|
|
2404
|
-
warnings: llm.warnings,
|
|
2405
|
-
createdAt,
|
|
2406
|
-
expiresAt
|
|
2407
|
-
}) : {
|
|
2408
|
-
planId: newPlanId(),
|
|
2409
|
-
request: cleaned,
|
|
2410
|
-
namespace: namespaces[0],
|
|
2411
|
-
affected,
|
|
2412
|
-
classification: llm.classification,
|
|
2413
|
-
actions: llm.actions,
|
|
2414
|
-
diff,
|
|
2415
|
-
confidence: clampConfidence(llm.confidence),
|
|
2416
|
-
warnings: llm.warnings,
|
|
2417
|
-
createdAt,
|
|
2418
|
-
expiresAt,
|
|
2419
|
-
status: "pending"
|
|
2420
|
-
};
|
|
2421
|
-
return this.persist(plan);
|
|
2422
|
-
}
|
|
2423
|
-
async locateCandidates(request, namespaces) {
|
|
2424
|
-
if (request.targetIds && request.targetIds.length > 0) {
|
|
2425
|
-
const targets = await this.deps.resolveTargets({
|
|
2426
|
-
targetIds: request.targetIds,
|
|
2427
|
-
namespaces
|
|
2428
|
-
});
|
|
2429
|
-
const seedIds2 = targets.map((c) => c.memoryId);
|
|
2430
|
-
const neighbors2 = await this.deps.expandNeighbors({
|
|
2431
|
-
seedIds: seedIds2,
|
|
2432
|
-
namespaces,
|
|
2433
|
-
limit: this.deps.maxAffected
|
|
2434
|
-
});
|
|
2435
|
-
return { candidates: mergeCandidates(targets, neighbors2).slice(0, this.deps.maxAffected) };
|
|
2436
|
-
}
|
|
2437
|
-
const searched = await this.deps.searchCorpus({
|
|
2438
|
-
text: request.text,
|
|
2439
|
-
namespaces,
|
|
2440
|
-
limit: this.deps.maxAffected
|
|
2441
|
-
});
|
|
2442
|
-
if (searched.length === 0) return { candidates: [] };
|
|
2443
|
-
const seedIds = searched.slice(0, Math.min(5, searched.length)).map((c) => c.memoryId);
|
|
2444
|
-
const neighbors = await this.deps.expandNeighbors({
|
|
2445
|
-
seedIds,
|
|
2446
|
-
namespaces,
|
|
2447
|
-
limit: this.deps.maxAffected
|
|
2448
|
-
});
|
|
2449
|
-
return { candidates: mergeCandidates(searched, neighbors).slice(0, this.deps.maxAffected) };
|
|
2450
|
-
}
|
|
2451
|
-
deriveAffected(candidates, llm) {
|
|
2452
|
-
const byId = new Map(candidates.map((c) => [c.memoryId, c]));
|
|
2453
|
-
const out = [];
|
|
2454
|
-
for (const rel of llm.relevance) {
|
|
2455
|
-
const c = byId.get(rel.memoryId);
|
|
2456
|
-
if (!c) continue;
|
|
2457
|
-
out.push({
|
|
2458
|
-
memoryId: c.memoryId,
|
|
2459
|
-
path: c.path,
|
|
2460
|
-
excerpt: c.excerpt,
|
|
2461
|
-
why: rel.why,
|
|
2462
|
-
...c.sourceQuote ? { sourceQuote: c.sourceQuote } : {}
|
|
2463
|
-
});
|
|
2464
|
-
}
|
|
2465
|
-
const annotated = new Set(out.map((e) => e.memoryId));
|
|
2466
|
-
for (const action of llm.actions) {
|
|
2467
|
-
const id = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : null;
|
|
2468
|
-
if (id && !annotated.has(id)) {
|
|
2469
|
-
const c = byId.get(id);
|
|
2470
|
-
if (c) {
|
|
2471
|
-
out.push({
|
|
2472
|
-
memoryId: c.memoryId,
|
|
2473
|
-
path: c.path,
|
|
2474
|
-
excerpt: c.excerpt,
|
|
2475
|
-
why: "touched by a drafted action",
|
|
2476
|
-
...c.sourceQuote ? { sourceQuote: c.sourceQuote } : {}
|
|
2477
|
-
});
|
|
2478
|
-
annotated.add(id);
|
|
2479
|
-
}
|
|
2480
|
-
}
|
|
2481
|
-
}
|
|
2482
|
-
return out;
|
|
2483
|
-
}
|
|
2484
|
-
emptyPlan(request, namespace, warning) {
|
|
2485
|
-
const createdAt = this.deps.now().toISOString();
|
|
2486
|
-
const expiresAt = new Date(
|
|
2487
|
-
this.deps.now().getTime() + this.deps.planTtlHours * 60 * 60 * 1e3
|
|
2488
|
-
).toISOString();
|
|
2489
|
-
return {
|
|
2490
|
-
planId: newPlanId(),
|
|
2491
|
-
request,
|
|
2492
|
-
namespace,
|
|
2493
|
-
affected: [],
|
|
2494
|
-
classification: "outdated",
|
|
2495
|
-
actions: [],
|
|
2496
|
-
diff: "",
|
|
2497
|
-
confidence: 0,
|
|
2498
|
-
warnings: [warning],
|
|
2499
|
-
createdAt,
|
|
2500
|
-
expiresAt,
|
|
2501
|
-
status: "pending"
|
|
2502
|
-
};
|
|
2503
|
-
}
|
|
2504
|
-
// -------------------------------------------------------------------------
|
|
2505
|
-
// Plan persistence — atomic write (rule 54), serialized per plan id (rule 40).
|
|
2506
|
-
// -------------------------------------------------------------------------
|
|
2507
|
-
/** Directory holding pending plans for one namespace. */
|
|
2508
|
-
async pendingDir(namespace) {
|
|
2509
|
-
return path4.join(await this.deps.storageDir(namespace), "state", "corrections", "pending");
|
|
2510
|
-
}
|
|
2511
|
-
async persist(plan) {
|
|
2512
|
-
const dir = await this.pendingDir(plan.namespace);
|
|
2513
|
-
const target = path4.join(dir, `${plan.planId}.json`);
|
|
2514
|
-
await serializeMutations(`correction-plan:${target}`, async () => {
|
|
2515
|
-
await mkdir2(dir, { recursive: true });
|
|
2516
|
-
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
2517
|
-
await writeFile2(tmp, `${JSON.stringify(plan)}
|
|
2518
|
-
`, "utf-8");
|
|
2519
|
-
await rename2(tmp, target);
|
|
2520
|
-
});
|
|
2521
|
-
return plan;
|
|
2522
|
-
}
|
|
2523
|
-
/** Load a pending plan by id (used by the service / executor). */
|
|
2524
|
-
async loadPlan(namespace, planId) {
|
|
2525
|
-
assertSafePlanId(planId);
|
|
2526
|
-
const file = path4.join(await this.pendingDir(namespace), `${planId}.json`);
|
|
2527
|
-
return serializeMutations(`correction-plan:${file}`, async () => {
|
|
2528
|
-
let raw;
|
|
2529
|
-
try {
|
|
2530
|
-
raw = await readFile3(file, "utf-8");
|
|
2531
|
-
} catch (err) {
|
|
2532
|
-
const code = err?.code;
|
|
2533
|
-
if (code === "ENOENT") return null;
|
|
2534
|
-
throw err;
|
|
2535
|
-
}
|
|
2536
|
-
return parsePlan(raw);
|
|
2537
|
-
});
|
|
2538
|
-
}
|
|
2539
|
-
/** List pending plans (newest first), excluding consumed (applied/discarded). */
|
|
2540
|
-
async listPending(namespace) {
|
|
2541
|
-
const dir = await this.pendingDir(namespace);
|
|
2542
|
-
let files;
|
|
2543
|
-
try {
|
|
2544
|
-
files = await readdir2(dir);
|
|
2545
|
-
} catch (err) {
|
|
2546
|
-
const code = err?.code;
|
|
2547
|
-
if (code === "ENOENT") return [];
|
|
2548
|
-
throw err;
|
|
2549
|
-
}
|
|
2550
|
-
const plans = [];
|
|
2551
|
-
for (const f of files) {
|
|
2552
|
-
if (!f.endsWith(".json")) continue;
|
|
2553
|
-
let plan = null;
|
|
2554
|
-
try {
|
|
2555
|
-
plan = await this.loadPlan(namespace, f.replace(/\.json$/, ""));
|
|
2556
|
-
} catch {
|
|
2557
|
-
continue;
|
|
2558
|
-
}
|
|
2559
|
-
if (plan && plan.status === "pending") plans.push(plan);
|
|
2560
|
-
}
|
|
2561
|
-
plans.sort((a, b) => a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0);
|
|
2562
|
-
return plans;
|
|
2563
|
-
}
|
|
2564
|
-
async markConsumed(namespace, planId, status) {
|
|
2565
|
-
assertSafePlanId(planId);
|
|
2566
|
-
const file = path4.join(await this.pendingDir(namespace), `${planId}.json`);
|
|
2567
|
-
await serializeMutations(`correction-plan:${file}`, async () => {
|
|
2568
|
-
let raw;
|
|
2569
|
-
try {
|
|
2570
|
-
raw = await readFile3(file, "utf-8");
|
|
2571
|
-
} catch (err) {
|
|
2572
|
-
const code = err?.code;
|
|
2573
|
-
if (code === "ENOENT") return;
|
|
2574
|
-
throw err;
|
|
2575
|
-
}
|
|
2576
|
-
const plan = parsePlan(raw);
|
|
2577
|
-
if (!plan) return;
|
|
2578
|
-
plan.status = status;
|
|
2579
|
-
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
2580
|
-
await writeFile2(tmp, `${JSON.stringify(plan)}
|
|
2581
|
-
`, "utf-8");
|
|
2582
|
-
await rename2(tmp, file);
|
|
2583
|
-
});
|
|
2584
|
-
}
|
|
2585
|
-
async deletePlan(namespace, planId) {
|
|
2586
|
-
assertSafePlanId(planId);
|
|
2587
|
-
const file = path4.join(await this.pendingDir(namespace), `${planId}.json`);
|
|
2588
|
-
await serializeMutations(`correction-plan:${file}`, async () => {
|
|
2589
|
-
try {
|
|
2590
|
-
await unlink(file);
|
|
2591
|
-
} catch (err) {
|
|
2592
|
-
const code = err?.code;
|
|
2593
|
-
if (code === "ENOENT") return;
|
|
2594
|
-
throw err;
|
|
2595
|
-
}
|
|
2596
|
-
});
|
|
2597
|
-
}
|
|
2598
|
-
};
|
|
2599
|
-
function assertSafePlanId(planId) {
|
|
2600
|
-
if (typeof planId !== "string" || planId.length === 0 || planId.includes("/") || planId.includes("\\") || planId.includes("\0") || planId === "." || planId === ".." || planId.startsWith(".") || planId.includes("..")) {
|
|
2601
|
-
throw new CorrectionContractError(
|
|
2602
|
-
`Invalid plan id: ${JSON.stringify(planId)} \u2014 must be a bare file basename with no path separators or parent segments.`
|
|
2603
|
-
);
|
|
2604
|
-
}
|
|
2605
|
-
}
|
|
2606
|
-
function clampConfidence(n) {
|
|
2607
|
-
if (!Number.isFinite(n)) return 0;
|
|
2608
|
-
return Math.min(1, Math.max(0, n));
|
|
2609
|
-
}
|
|
2610
|
-
function mergeCandidates(a, b) {
|
|
2611
|
-
const map = /* @__PURE__ */ new Map();
|
|
2612
|
-
for (const c of a) {
|
|
2613
|
-
const existing = map.get(c.memoryId);
|
|
2614
|
-
if (!existing || c.score > existing.score) map.set(c.memoryId, c);
|
|
2615
|
-
}
|
|
2616
|
-
for (const c of b) {
|
|
2617
|
-
const existing = map.get(c.memoryId);
|
|
2618
|
-
if (!existing || c.score > existing.score) map.set(c.memoryId, c);
|
|
2619
|
-
}
|
|
2620
|
-
return [...map.values()].sort((x, y) => y.score - x.score);
|
|
2621
|
-
}
|
|
2622
|
-
function parsePlan(raw) {
|
|
2623
|
-
let parsed;
|
|
2624
|
-
try {
|
|
2625
|
-
parsed = JSON.parse(raw);
|
|
2626
|
-
} catch {
|
|
2627
|
-
return null;
|
|
2628
|
-
}
|
|
2629
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
2630
|
-
const p = parsed;
|
|
2631
|
-
if (typeof p.planId !== "string" || typeof p.namespace !== "string") return null;
|
|
2632
|
-
if (typeof p.createdAt !== "string" || typeof p.expiresAt !== "string") return null;
|
|
2633
|
-
if (!Array.isArray(p.actions) || !Array.isArray(p.affected)) return null;
|
|
2634
|
-
for (const action of p.actions) {
|
|
2635
|
-
try {
|
|
2636
|
-
validateCorrectionAction(action);
|
|
2637
|
-
} catch {
|
|
2638
|
-
return null;
|
|
2639
|
-
}
|
|
2640
|
-
}
|
|
2641
|
-
return parsed;
|
|
2642
|
-
}
|
|
2643
|
-
|
|
2644
|
-
// src/correction/correction-executor.ts
|
|
2645
|
-
var CorrectionExecutor = class {
|
|
2646
|
-
constructor(deps, planner) {
|
|
2647
|
-
this.deps = deps;
|
|
2648
|
-
this.planner = planner;
|
|
2649
|
-
}
|
|
2650
|
-
deps;
|
|
2651
|
-
planner;
|
|
2652
|
-
/**
|
|
2653
|
-
* Apply a persisted plan by id. Idempotent-once: a second apply of the same
|
|
2654
|
-
* plan is rejected. Returns the {@link CorrectionOutcome}.
|
|
2655
|
-
*/
|
|
2656
|
-
async apply(namespace, planId, opts) {
|
|
2657
|
-
if (!opts.confirm) {
|
|
2658
|
-
throw new CorrectionContractError(
|
|
2659
|
-
"Correction apply requires explicit confirmation (correction.applyRequiresConfirm)."
|
|
2660
|
-
);
|
|
2661
|
-
}
|
|
2662
|
-
return serializeMutations(
|
|
2663
|
-
`correction-apply:${namespace}:${planId}`,
|
|
2664
|
-
() => this.applyInternal(namespace, planId, opts.canWriteDestination)
|
|
2665
|
-
);
|
|
2666
|
-
}
|
|
2667
|
-
async applyInternal(namespace, planId, canWriteDestination) {
|
|
2668
|
-
const plan = await this.planner.loadPlan(namespace, planId);
|
|
2669
|
-
if (!plan) {
|
|
2670
|
-
throw new CorrectionContractError(`Correction plan not found: ${planId}`);
|
|
2671
|
-
}
|
|
2672
|
-
if (plan.namespace !== namespace) {
|
|
2673
|
-
throw new CorrectionContractError(
|
|
2674
|
-
`Correction plan ${planId} belongs to namespace '${plan.namespace}', not '${namespace}'.`
|
|
2675
|
-
);
|
|
2676
|
-
}
|
|
2677
|
-
if (plan.status === "applied" || plan.status === "partial" || plan.status === "applying") {
|
|
2678
|
-
throw new CorrectionContractError(
|
|
2679
|
-
`Correction plan ${planId} has already been applied or is in progress (status=${plan.status}).`
|
|
2680
|
-
);
|
|
2681
|
-
}
|
|
2682
|
-
if (plan.status === "discarded") {
|
|
2683
|
-
throw new CorrectionContractError(`Correction plan ${planId} has been discarded.`);
|
|
2684
|
-
}
|
|
2685
|
-
if (this.deps.now().getTime() > new Date(plan.expiresAt).getTime()) {
|
|
2686
|
-
await this.planner.markConsumed(namespace, planId, "discarded");
|
|
2687
|
-
throw new CorrectionContractError(
|
|
2688
|
-
`Correction plan ${planId} expired at ${plan.expiresAt} and has been discarded.`
|
|
2689
|
-
);
|
|
2690
|
-
}
|
|
2691
|
-
for (const action of plan.actions) {
|
|
2692
|
-
validateCorrectionAction(action);
|
|
2693
|
-
if (action.kind === "redaction_rule") {
|
|
2694
|
-
validateRedactionPattern(action.pattern);
|
|
2695
|
-
}
|
|
2696
|
-
}
|
|
2697
|
-
try {
|
|
2698
|
-
await this.planner.markConsumed(namespace, planId, "applying");
|
|
2699
|
-
} catch {
|
|
2700
|
-
throw new CorrectionContractError(
|
|
2701
|
-
`Correction plan ${planId}: cannot mark in-progress (filesystem unwritable?) \u2014 aborting before any mutation.`
|
|
2702
|
-
);
|
|
2703
|
-
}
|
|
2704
|
-
const results = [];
|
|
2705
|
-
const appliedTouched = [];
|
|
2706
|
-
for (const action of plan.actions) {
|
|
2707
|
-
if (action.kind === "supersede" && action.replacement) {
|
|
2708
|
-
const loser = await this.deps.getMemory(namespace, action.loserId);
|
|
2709
|
-
if (!loser) {
|
|
2710
|
-
results.push({
|
|
2711
|
-
action,
|
|
2712
|
-
status: "failed",
|
|
2713
|
-
error: `supersede loser not found: ${action.loserId}`
|
|
2714
|
-
});
|
|
2715
|
-
continue;
|
|
2716
|
-
}
|
|
2717
|
-
try {
|
|
2718
|
-
const newId = await this.deps.writeReplacement(namespace, {
|
|
2719
|
-
content: action.replacement.content,
|
|
2720
|
-
...action.replacement.category ? { category: action.replacement.category } : {},
|
|
2721
|
-
...action.replacement.confidence !== void 0 ? { confidence: action.replacement.confidence } : {},
|
|
2722
|
-
...action.replacement.tags ? { tags: action.replacement.tags } : {},
|
|
2723
|
-
...action.replacement.entityRef ? { entityRef: action.replacement.entityRef } : {},
|
|
2724
|
-
...action.replacement.validAt ? { validAt: action.replacement.validAt } : {},
|
|
2725
|
-
...action.replacement.observedAt ? { observedAt: action.replacement.observedAt } : {},
|
|
2726
|
-
...action.replacement.structuredAttributes ? { structuredAttributes: action.replacement.structuredAttributes } : {},
|
|
2727
|
-
supersedes: action.loserId
|
|
2728
|
-
});
|
|
2729
|
-
results.push({ action, status: "applied", memoryId: newId });
|
|
2730
|
-
appliedTouched.push(newId);
|
|
2731
|
-
} catch (err) {
|
|
2732
|
-
results.push({
|
|
2733
|
-
action,
|
|
2734
|
-
status: "failed",
|
|
2735
|
-
error: errMsg(err)
|
|
2736
|
-
});
|
|
2737
|
-
}
|
|
2738
|
-
} else if (action.kind === "edit") {
|
|
2739
|
-
try {
|
|
2740
|
-
const editedId = await this.deps.applyEdit(namespace, action.memoryId, action.patch);
|
|
2741
|
-
results.push({ action, status: "applied", memoryId: editedId });
|
|
2742
|
-
appliedTouched.push(editedId);
|
|
2743
|
-
} catch (err) {
|
|
2744
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
2745
|
-
}
|
|
2746
|
-
} else if (action.kind === "redaction_rule") {
|
|
2747
|
-
try {
|
|
2748
|
-
await this.deps.registerRedactionRule(namespace, action.pattern);
|
|
2749
|
-
results.push({ action, status: "applied" });
|
|
2750
|
-
} catch (err) {
|
|
2751
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
2752
|
-
}
|
|
2753
|
-
}
|
|
2754
|
-
}
|
|
2755
|
-
for (const action of plan.actions) {
|
|
2756
|
-
if (action.kind === "supersede") {
|
|
2757
|
-
const replacementResult = results.find(
|
|
2758
|
-
(r) => r.action === action && r.status === "applied"
|
|
2759
|
-
);
|
|
2760
|
-
if (action.replacement && !replacementResult) {
|
|
2761
|
-
continue;
|
|
2762
|
-
}
|
|
2763
|
-
await this.retireAndTombstone(namespace, action, "supersession", results, appliedTouched, {
|
|
2764
|
-
supersededBy: replacementResult?.memoryId
|
|
2765
|
-
});
|
|
2766
|
-
} else if (action.kind === "retract") {
|
|
2767
|
-
await this.retireAndTombstone(namespace, action, "retraction", results, appliedTouched);
|
|
2768
|
-
} else if (action.kind === "rescope") {
|
|
2769
|
-
try {
|
|
2770
|
-
const allowed = canWriteDestination ? await canWriteDestination(action.toNamespace) : true;
|
|
2771
|
-
if (!allowed) {
|
|
2772
|
-
results.push({
|
|
2773
|
-
action,
|
|
2774
|
-
status: "failed",
|
|
2775
|
-
error: `rescope destination namespace not writable: ${action.toNamespace}`
|
|
2776
|
-
});
|
|
2777
|
-
continue;
|
|
2778
|
-
}
|
|
2779
|
-
const destId = await this.deps.rescopeMemory(namespace, action.memoryId, action.toNamespace);
|
|
2780
|
-
results.push({ action, status: "applied", memoryId: action.memoryId });
|
|
2781
|
-
appliedTouched.push(action.memoryId);
|
|
2782
|
-
try {
|
|
2783
|
-
await this.deps.propagate(action.toNamespace, [destId]);
|
|
2784
|
-
} catch {
|
|
2785
|
-
}
|
|
2786
|
-
} catch (err) {
|
|
2787
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
2788
|
-
}
|
|
2789
|
-
}
|
|
2790
|
-
}
|
|
2791
|
-
const propagationWarnings = [];
|
|
2792
|
-
if (appliedTouched.length > 0) {
|
|
2793
|
-
try {
|
|
2794
|
-
await this.deps.propagate(namespace, appliedTouched);
|
|
2795
|
-
} catch (err) {
|
|
2796
|
-
propagationWarnings.push(`propagation failed (non-fatal): ${errMsg(err)}`);
|
|
2797
|
-
}
|
|
2798
|
-
}
|
|
2799
|
-
const anyFailed = results.some((r) => r.status === "failed");
|
|
2800
|
-
const status = anyFailed ? "partial" : "applied";
|
|
2801
|
-
const appliedAt = this.deps.now().toISOString();
|
|
2802
|
-
const outcome = {
|
|
2803
|
-
planId,
|
|
2804
|
-
status,
|
|
2805
|
-
results,
|
|
2806
|
-
auditMemoryId: "",
|
|
2807
|
-
// filled after the audit write
|
|
2808
|
-
appliedAt
|
|
2809
|
-
};
|
|
2810
|
-
if (propagationWarnings.length > 0) {
|
|
2811
|
-
outcome.warnings = propagationWarnings;
|
|
2812
|
-
}
|
|
2813
|
-
try {
|
|
2814
|
-
const auditId = await this.deps.appendAuditRecord(namespace, {
|
|
2815
|
-
planId,
|
|
2816
|
-
classification: plan.classification,
|
|
2817
|
-
outcome,
|
|
2818
|
-
requestText: plan.request.text
|
|
2819
|
-
});
|
|
2820
|
-
outcome.auditMemoryId = auditId;
|
|
2821
|
-
} catch (err) {
|
|
2822
|
-
outcome.warnings = [
|
|
2823
|
-
...propagationWarnings,
|
|
2824
|
-
`audit record write failed (non-fatal): ${errMsg(err)}`
|
|
2825
|
-
];
|
|
2826
|
-
}
|
|
2827
|
-
try {
|
|
2828
|
-
await this.planner.markConsumed(namespace, planId, status);
|
|
2829
|
-
} catch (err) {
|
|
2830
|
-
const w = outcome;
|
|
2831
|
-
w.warnings = [...w.warnings ?? [], `plan mark-consumed failed (non-fatal): ${errMsg(err)}`];
|
|
2832
|
-
}
|
|
2833
|
-
return outcome;
|
|
2834
|
-
}
|
|
2835
|
-
async retireAndTombstone(namespace, action, reason, results, appliedTouched, opts = {}) {
|
|
2836
|
-
const memoryId = action.kind === "supersede" ? action.loserId : action.kind === "retract" ? action.memoryId : null;
|
|
2837
|
-
if (!memoryId) return;
|
|
2838
|
-
try {
|
|
2839
|
-
const memory = await this.deps.getMemory(namespace, memoryId);
|
|
2840
|
-
if (!memory) {
|
|
2841
|
-
results.push({
|
|
2842
|
-
action,
|
|
2843
|
-
status: "failed",
|
|
2844
|
-
error: `memory not found: ${memoryId}`
|
|
2845
|
-
});
|
|
2846
|
-
return;
|
|
2847
|
-
}
|
|
2848
|
-
const validUntil = this.deps.biTemporalEnabled ? this.deps.now().toISOString() : void 0;
|
|
2849
|
-
const tombstoneId = await this.deps.appendTombstone(namespace, {
|
|
2850
|
-
reason,
|
|
2851
|
-
sourceMemoryId: memoryId,
|
|
2852
|
-
rawContent: memory.rawContent,
|
|
2853
|
-
...memory.entityRef ? { entityRef: memory.entityRef } : {},
|
|
2854
|
-
...memory.supersessionKey ? { supersessionKey: memory.supersessionKey } : {}
|
|
2855
|
-
});
|
|
2856
|
-
await this.deps.retireMemory(namespace, memoryId, {
|
|
2857
|
-
status: reason === "supersession" ? "superseded" : "retracted",
|
|
2858
|
-
...opts.supersededBy ? { supersededBy: opts.supersededBy } : {},
|
|
2859
|
-
...validUntil ? { validUntil } : {}
|
|
2860
|
-
});
|
|
2861
|
-
results.push({
|
|
2862
|
-
action,
|
|
2863
|
-
status: "applied",
|
|
2864
|
-
memoryId,
|
|
2865
|
-
...tombstoneId ? { tombstoneId } : {}
|
|
2866
|
-
});
|
|
2867
|
-
appliedTouched.push(memoryId);
|
|
2868
|
-
} catch (err) {
|
|
2869
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
2870
|
-
}
|
|
2871
|
-
}
|
|
2872
|
-
};
|
|
2873
|
-
function errMsg(err) {
|
|
2874
|
-
if (err instanceof Error) return err.message;
|
|
2875
|
-
return String(err);
|
|
2876
|
-
}
|
|
2877
|
-
|
|
2878
|
-
// src/correction/correction-service.ts
|
|
2879
|
-
var CorrectionService = class {
|
|
2880
|
-
constructor(deps) {
|
|
2881
|
-
this.deps = deps;
|
|
2882
|
-
this.planner = new CorrectionPlanner(deps.plannerDeps());
|
|
2883
|
-
this.executor = new CorrectionExecutor(deps.executorDeps(), this.planner);
|
|
2884
|
-
}
|
|
2885
|
-
deps;
|
|
2886
|
-
planner;
|
|
2887
|
-
executor;
|
|
2888
|
-
/**
|
|
2889
|
-
* Plan a correction. Read-only — produces + persists a {@link CorrectionPlan}.
|
|
2890
|
-
* Safe to run with the gate ON (default) since the plan writes no memory state.
|
|
2891
|
-
*
|
|
2892
|
-
* The plan is stored under the AUTHORIZED (writable) namespace — the same
|
|
2893
|
-
* namespace apply/listPending/discard resolve — so the plan is always
|
|
2894
|
-
* found by the caller that created it (review threads: plan-stored-wrong-
|
|
2895
|
-
* namespace + cross-namespace candidate mismatch). Candidates are located
|
|
2896
|
-
* within that single namespace too: a correction can only affect memories
|
|
2897
|
-
* the principal can write, so reading from a non-writable namespace to
|
|
2898
|
-
* draft a correction that can never be applied would be misleading.
|
|
2899
|
-
*/
|
|
2900
|
-
async plan(request) {
|
|
2901
|
-
this.requireEnabled();
|
|
2902
|
-
const authorized = await this.deps.policy.resolveAuthorizedNamespace(request);
|
|
2903
|
-
return this.planner.plan(request, [authorized]);
|
|
2904
|
-
}
|
|
2905
|
-
/**
|
|
2906
|
-
* Apply a persisted plan by id. Requires `confirm: true` (or interactive
|
|
2907
|
-
* yes at the CLI) when `applyRequiresConfirm` is on (default).
|
|
2908
|
-
*/
|
|
2909
|
-
async apply(planId, opts) {
|
|
2910
|
-
this.requireEnabled();
|
|
2911
|
-
if (this.deps.applyRequiresConfirm() && opts.confirm !== true) {
|
|
2912
|
-
throw new CorrectionContractError(
|
|
2913
|
-
"Correction apply requires explicit confirmation (pass `confirm: true`)."
|
|
2914
|
-
);
|
|
2915
|
-
}
|
|
2916
|
-
const namespace = await this.deps.policy.resolveAuthorizedNamespace({
|
|
2917
|
-
...opts.namespace ? { namespace: opts.namespace } : {},
|
|
2918
|
-
...opts.sessionKey ? { sessionKey: opts.sessionKey } : {},
|
|
2919
|
-
...opts.principal ? { principal: opts.principal } : {}
|
|
2920
|
-
});
|
|
2921
|
-
return this.executor.apply(namespace, planId, {
|
|
2922
|
-
confirm: true,
|
|
2923
|
-
// Authorize rescope destinations through the namespace policy bound to
|
|
2924
|
-
// THIS caller's principal (review thread: authorize-rescope-destination).
|
|
2925
|
-
canWriteDestination: (dest) => this.deps.policy.canWriteNamespace({
|
|
2926
|
-
namespace: dest,
|
|
2927
|
-
...opts.sessionKey ? { sessionKey: opts.sessionKey } : {},
|
|
2928
|
-
...opts.principal ? { principal: opts.principal } : {}
|
|
2929
|
-
})
|
|
2930
|
-
});
|
|
2931
|
-
}
|
|
2932
|
-
/** List pending (not-yet-applied) plans for the caller's namespace. */
|
|
2933
|
-
async listPending(opts) {
|
|
2934
|
-
this.requireEnabled();
|
|
2935
|
-
const namespace = await this.deps.policy.resolveAuthorizedNamespace(opts);
|
|
2936
|
-
return this.planner.listPending(namespace);
|
|
2937
|
-
}
|
|
2938
|
-
/** Discard a pending plan. Idempotent. */
|
|
2939
|
-
async discard(planId, opts) {
|
|
2940
|
-
this.requireEnabled();
|
|
2941
|
-
const namespace = await this.deps.policy.resolveAuthorizedNamespace(opts);
|
|
2942
|
-
await this.planner.markConsumed(namespace, planId, "discarded");
|
|
2943
|
-
await this.planner.deletePlan(namespace, planId);
|
|
2944
|
-
}
|
|
2945
|
-
requireEnabled() {
|
|
2946
|
-
if (!this.deps.isEnabled()) {
|
|
2947
|
-
throw new CorrectionContractError(
|
|
2948
|
-
"Correction Contract is disabled (set correction.enabled = true to enable)."
|
|
2949
|
-
);
|
|
2950
|
-
}
|
|
2951
|
-
}
|
|
2952
|
-
};
|
|
2953
|
-
|
|
2954
|
-
// src/correction/correction-access-wiring.ts
|
|
2955
|
-
import path5 from "path";
|
|
2956
|
-
import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
|
|
2957
|
-
function createCorrectionService(wiring) {
|
|
2958
|
-
const cfg = wiring.orchestrator.config;
|
|
2959
|
-
const correctionEnabled = isCorrectionFeatureEnabled(cfg);
|
|
2960
|
-
const applyRequiresConfirm = typeof cfg.correctionApplyRequiresConfirm === "boolean" ? cfg.correctionApplyRequiresConfirm : readCorrectionFlag(cfg, "applyRequiresConfirm", true);
|
|
2961
|
-
const maxAffected = typeof cfg.correctionMaxAffected === "number" && cfg.correctionMaxAffected >= 1 ? Math.floor(cfg.correctionMaxAffected) : readCorrectionNumber(cfg, "maxAffected", 10);
|
|
2962
|
-
const planTtlHours = typeof cfg.correctionPlanTtlHours === "number" && cfg.correctionPlanTtlHours > 0 ? cfg.correctionPlanTtlHours : readCorrectionNumber(cfg, "planTtlHours", 24);
|
|
2963
|
-
const biTemporalEnabled = cfg.temporalBiTemporal === true;
|
|
2964
|
-
const serviceDeps = {
|
|
2965
|
-
policy: {
|
|
2966
|
-
resolveAuthorizedNamespace: (req) => wiring.resolveAuthorizedNamespace(req),
|
|
2967
|
-
canWriteNamespace: (req) => wiring.canWriteNamespace(req),
|
|
2968
|
-
readableNamespaces: (req) => Promise.resolve(wiring.resolveReadableNamespaces(req))
|
|
2969
|
-
},
|
|
2970
|
-
plannerDeps: () => makePlannerDeps(wiring, { maxAffected, planTtlHours }),
|
|
2971
|
-
executorDeps: () => makeExecutorDeps(wiring, { biTemporalEnabled }),
|
|
2972
|
-
isEnabled: () => correctionEnabled,
|
|
2973
|
-
applyRequiresConfirm: () => applyRequiresConfirm
|
|
2974
|
-
};
|
|
2975
|
-
return new CorrectionService(serviceDeps);
|
|
2976
|
-
}
|
|
2977
|
-
function makePlannerDeps(wiring, opts) {
|
|
2978
|
-
return {
|
|
2979
|
-
searchCorpus: async ({ text, namespaces, limit }) => searchMemories(wiring, text, namespaces, limit),
|
|
2980
|
-
resolveTargets: async ({ targetIds, namespaces }) => resolveTargetMemories(wiring, targetIds, namespaces),
|
|
2981
|
-
expandNeighbors: async ({ seedIds, namespaces, limit }) => expandEntityNeighbors(wiring, seedIds, namespaces, limit),
|
|
2982
|
-
classifyAndDraft: async ({ text, candidates }) => classifyAndDraft(wiring, text, candidates),
|
|
2983
|
-
renderDiff: async ({ candidates, actions }) => renderCorrectionDiff(wiring, candidates, actions),
|
|
2984
|
-
storageDir: async (namespace) => (await wiring.orchestrator.getStorage(namespace)).dir,
|
|
2985
|
-
maxAffected: opts.maxAffected,
|
|
2986
|
-
planTtlHours: opts.planTtlHours,
|
|
2987
|
-
now: () => /* @__PURE__ */ new Date()
|
|
2988
|
-
};
|
|
2989
|
-
}
|
|
2990
|
-
async function searchMemories(wiring, text, namespaces, limit) {
|
|
2991
|
-
const tokens = tokenize(text);
|
|
2992
|
-
if (tokens.length === 0) return [];
|
|
2993
|
-
const scored = [];
|
|
2994
|
-
for (const ns of namespaces) {
|
|
2995
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
2996
|
-
const all = await storage.readAllMemories();
|
|
2997
|
-
for (const m of all) {
|
|
2998
|
-
if (m.frontmatter.status && m.frontmatter.status !== "active") continue;
|
|
2999
|
-
const hay = `${m.content} ${m.frontmatter.tags?.join(" ") ?? ""}`.toLowerCase();
|
|
3000
|
-
let hits = 0;
|
|
3001
|
-
for (const tok of tokens) {
|
|
3002
|
-
if (hay.includes(tok)) hits++;
|
|
3003
|
-
}
|
|
3004
|
-
if (hits === 0) continue;
|
|
3005
|
-
scored.push({ m, ns, score: hits / tokens.length });
|
|
3006
|
-
}
|
|
3007
|
-
}
|
|
3008
|
-
scored.sort((a, b) => b.score - a.score);
|
|
3009
|
-
return scored.slice(0, limit).map((s, i) => toCandidate(s.m, s.ns, s.score - i * 0.01));
|
|
3010
|
-
}
|
|
3011
|
-
function tokenize(text) {
|
|
3012
|
-
const STOP = /* @__PURE__ */ new Set([
|
|
3013
|
-
"the",
|
|
3014
|
-
"a",
|
|
3015
|
-
"an",
|
|
3016
|
-
"is",
|
|
3017
|
-
"are",
|
|
3018
|
-
"was",
|
|
3019
|
-
"were",
|
|
3020
|
-
"be",
|
|
3021
|
-
"been",
|
|
3022
|
-
"being",
|
|
3023
|
-
"to",
|
|
3024
|
-
"of",
|
|
3025
|
-
"in",
|
|
3026
|
-
"on",
|
|
3027
|
-
"at",
|
|
3028
|
-
"by",
|
|
3029
|
-
"for",
|
|
3030
|
-
"with",
|
|
3031
|
-
"from",
|
|
3032
|
-
"into",
|
|
3033
|
-
"and",
|
|
3034
|
-
"or",
|
|
3035
|
-
"but",
|
|
3036
|
-
"not",
|
|
3037
|
-
"no",
|
|
3038
|
-
"yes",
|
|
3039
|
-
"this",
|
|
3040
|
-
"that",
|
|
3041
|
-
"these",
|
|
3042
|
-
"those",
|
|
3043
|
-
"it",
|
|
3044
|
-
"its",
|
|
3045
|
-
"we",
|
|
3046
|
-
"you",
|
|
3047
|
-
"i",
|
|
3048
|
-
"he",
|
|
3049
|
-
"she",
|
|
3050
|
-
"they",
|
|
3051
|
-
"them",
|
|
3052
|
-
"our",
|
|
3053
|
-
"your",
|
|
3054
|
-
"my",
|
|
3055
|
-
"his",
|
|
3056
|
-
"her",
|
|
3057
|
-
"their",
|
|
3058
|
-
"as",
|
|
3059
|
-
"so",
|
|
3060
|
-
"if",
|
|
3061
|
-
"then",
|
|
3062
|
-
"than",
|
|
3063
|
-
"too",
|
|
3064
|
-
"very",
|
|
3065
|
-
"can",
|
|
3066
|
-
"will",
|
|
3067
|
-
"just",
|
|
3068
|
-
"should",
|
|
3069
|
-
"now",
|
|
3070
|
-
"has",
|
|
3071
|
-
"have",
|
|
3072
|
-
"had",
|
|
3073
|
-
"do",
|
|
3074
|
-
"does",
|
|
3075
|
-
"did",
|
|
3076
|
-
"about",
|
|
3077
|
-
"which",
|
|
3078
|
-
"what",
|
|
3079
|
-
"who",
|
|
3080
|
-
"when",
|
|
3081
|
-
"where",
|
|
3082
|
-
"why",
|
|
3083
|
-
"how",
|
|
3084
|
-
"all",
|
|
3085
|
-
"each",
|
|
3086
|
-
"every",
|
|
3087
|
-
"both",
|
|
3088
|
-
"few",
|
|
3089
|
-
"more",
|
|
3090
|
-
"most",
|
|
3091
|
-
"other",
|
|
3092
|
-
"some",
|
|
3093
|
-
"such",
|
|
3094
|
-
"only",
|
|
3095
|
-
"own",
|
|
3096
|
-
"same",
|
|
3097
|
-
"up"
|
|
3098
|
-
]);
|
|
3099
|
-
const raw = text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
3100
|
-
const out = raw.filter((w) => w.length >= 3 && !STOP.has(w));
|
|
3101
|
-
return [...new Set(out)];
|
|
3102
|
-
}
|
|
3103
|
-
async function resolveTargetMemories(wiring, targetIds, namespaces) {
|
|
3104
|
-
const out = [];
|
|
3105
|
-
const missing = [];
|
|
3106
|
-
for (const id of targetIds) {
|
|
3107
|
-
let found = null;
|
|
3108
|
-
for (const ns of namespaces) {
|
|
3109
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
3110
|
-
const m = await storage.getMemoryById(id);
|
|
3111
|
-
if (m) {
|
|
3112
|
-
found = toCandidate(m, ns, 1);
|
|
3113
|
-
break;
|
|
3114
|
-
}
|
|
3115
|
-
}
|
|
3116
|
-
if (found) out.push(found);
|
|
3117
|
-
else missing.push(id);
|
|
3118
|
-
}
|
|
3119
|
-
if (missing.length > 0) {
|
|
3120
|
-
throw new CorrectionContractError(`target memory not found: ${missing[0]}`);
|
|
3121
|
-
}
|
|
3122
|
-
return out;
|
|
3123
|
-
}
|
|
3124
|
-
async function expandEntityNeighbors(wiring, seedIds, namespaces, limit) {
|
|
3125
|
-
if (seedIds.length === 0 || limit <= 0 || namespaces.length === 0) return [];
|
|
3126
|
-
const out = [];
|
|
3127
|
-
const seen = new Set(seedIds);
|
|
3128
|
-
const seedRefs = /* @__PURE__ */ new Set();
|
|
3129
|
-
for (const ns of namespaces) {
|
|
3130
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
3131
|
-
const all = await storage.readAllMemories();
|
|
3132
|
-
for (const m of all) {
|
|
3133
|
-
if (seedIds.includes(m.frontmatter.id) && m.frontmatter.entityRef) {
|
|
3134
|
-
seedRefs.add(m.frontmatter.entityRef);
|
|
3135
|
-
}
|
|
3136
|
-
}
|
|
3137
|
-
}
|
|
3138
|
-
if (seedRefs.size === 0) return [];
|
|
3139
|
-
for (const ns of namespaces) {
|
|
3140
|
-
if (out.length >= limit) break;
|
|
3141
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
3142
|
-
const all = await storage.readAllMemories();
|
|
3143
|
-
for (const m of all) {
|
|
3144
|
-
if (out.length >= limit) break;
|
|
3145
|
-
if (seen.has(m.frontmatter.id)) continue;
|
|
3146
|
-
if (m.frontmatter.status && m.frontmatter.status !== "active") continue;
|
|
3147
|
-
if (m.frontmatter.entityRef && seedRefs.has(m.frontmatter.entityRef)) {
|
|
3148
|
-
out.push(toCandidate(m, ns, 0.5));
|
|
3149
|
-
seen.add(m.frontmatter.id);
|
|
3150
|
-
}
|
|
3151
|
-
}
|
|
3152
|
-
}
|
|
3153
|
-
return out;
|
|
3154
|
-
}
|
|
3155
|
-
async function classifyAndDraft(wiring, text, candidates) {
|
|
3156
|
-
try {
|
|
3157
|
-
if (!wiring.llmComplete) {
|
|
3158
|
-
return fallbackClassification(candidates, "no LLM client available");
|
|
3159
|
-
}
|
|
3160
|
-
const user = buildClassifyPrompt(text, candidates);
|
|
3161
|
-
const raw = await wiring.llmComplete({ system: CLASSIFY_SYSTEM_PROMPT, user });
|
|
3162
|
-
return parseClassifyResponse(raw, candidates);
|
|
3163
|
-
} catch (err) {
|
|
3164
|
-
return fallbackClassification(candidates, `LLM unavailable: ${errMsg2(err)}`);
|
|
3165
|
-
}
|
|
3166
|
-
}
|
|
3167
|
-
async function renderCorrectionDiff(_wiring, candidates, actions) {
|
|
3168
|
-
const lines = [];
|
|
3169
|
-
for (const action of actions) {
|
|
3170
|
-
const id = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : null;
|
|
3171
|
-
const candidate = id ? candidates.find((c) => c.memoryId === id) : null;
|
|
3172
|
-
const before = candidate?.content ?? "(new)";
|
|
3173
|
-
const after = describeAfterState(action);
|
|
3174
|
-
lines.push(`--- ${id ?? "redaction-rule"} (${action.kind})`);
|
|
3175
|
-
lines.push(`- ${before.slice(0, 120)}`);
|
|
3176
|
-
lines.push(`+ ${after.slice(0, 120)}`);
|
|
3177
|
-
}
|
|
3178
|
-
return lines.join("\n");
|
|
3179
|
-
}
|
|
3180
|
-
function describeAfterState(action) {
|
|
3181
|
-
switch (action.kind) {
|
|
3182
|
-
case "supersede":
|
|
3183
|
-
return action.replacement?.content ?? "(superseded without replacement)";
|
|
3184
|
-
case "edit":
|
|
3185
|
-
return action.patch;
|
|
3186
|
-
case "retract":
|
|
3187
|
-
return "(retracted + tombstoned)";
|
|
3188
|
-
case "rescope":
|
|
3189
|
-
return `(moved to namespace '${action.toNamespace}')`;
|
|
3190
|
-
case "redaction_rule":
|
|
3191
|
-
return `(redaction rule persisted for pattern '${action.pattern}')`;
|
|
3192
|
-
}
|
|
3193
|
-
}
|
|
3194
|
-
function makeExecutorDeps(wiring, opts) {
|
|
3195
|
-
return {
|
|
3196
|
-
getMemory: async (namespace, memoryId) => getExecutorMemory(wiring, namespace, memoryId),
|
|
3197
|
-
writeReplacement: async (namespace, draft) => writeReplacementMemory(wiring, namespace, draft),
|
|
3198
|
-
applyEdit: async (namespace, memoryId, patch) => applyEditMemory(wiring, namespace, memoryId, patch),
|
|
3199
|
-
retireMemory: async (namespace, memoryId, retireOpts) => retireMemoryFn(wiring, namespace, memoryId, retireOpts),
|
|
3200
|
-
rescopeMemory: async (namespace, memoryId, toNamespace) => rescopeMemoryFn(wiring, namespace, memoryId, toNamespace),
|
|
3201
|
-
appendTombstone: async (namespace, input) => appendTombstoneFn(wiring, namespace, input),
|
|
3202
|
-
registerRedactionRule: async (namespace, pattern) => registerRedactionRuleFn(wiring, namespace, pattern),
|
|
3203
|
-
appendAuditRecord: async (namespace, record) => appendAuditRecordFn(wiring, namespace, record),
|
|
3204
|
-
propagate: async (namespace, touchedMemoryIds) => propagateFn(wiring, namespace, touchedMemoryIds),
|
|
3205
|
-
biTemporalEnabled: opts.biTemporalEnabled,
|
|
3206
|
-
now: () => /* @__PURE__ */ new Date()
|
|
3207
|
-
};
|
|
3208
|
-
}
|
|
3209
|
-
async function getExecutorMemory(wiring, namespace, memoryId) {
|
|
3210
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3211
|
-
const m = await storage.getMemoryById(memoryId);
|
|
3212
|
-
if (!m) return null;
|
|
3213
|
-
return toExecutorMemory(m);
|
|
3214
|
-
}
|
|
3215
|
-
async function writeReplacementMemory(wiring, namespace, draft) {
|
|
3216
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3217
|
-
const id = await storage.writeMemory(
|
|
3218
|
-
draft.category ?? "fact",
|
|
3219
|
-
draft.content,
|
|
3220
|
-
{
|
|
3221
|
-
source: "correction",
|
|
3222
|
-
confidence: draft.confidence ?? 0.9,
|
|
3223
|
-
tags: draft.tags ?? [],
|
|
3224
|
-
...draft.entityRef ? { entityRef: draft.entityRef } : {},
|
|
3225
|
-
...draft.validAt ? { validAt: draft.validAt } : {},
|
|
3226
|
-
...draft.observedAt ? { observedAt: draft.observedAt } : {},
|
|
3227
|
-
...draft.structuredAttributes ? { structuredAttributes: draft.structuredAttributes } : {},
|
|
3228
|
-
...draft.supersedes ? { supersedes: draft.supersedes } : {}
|
|
3229
|
-
}
|
|
3230
|
-
);
|
|
3231
|
-
return id;
|
|
3232
|
-
}
|
|
3233
|
-
async function applyEditMemory(wiring, namespace, memoryId, patch) {
|
|
3234
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3235
|
-
const existing = await storage.getMemoryById(memoryId);
|
|
3236
|
-
if (!existing) throw new CorrectionContractError(`memory not found for edit: ${memoryId}`);
|
|
3237
|
-
await storage.writeMemoryFrontmatter(
|
|
3238
|
-
{ ...existing, content: patch },
|
|
3239
|
-
{ updated: (/* @__PURE__ */ new Date()).toISOString() }
|
|
3240
|
-
);
|
|
3241
|
-
return memoryId;
|
|
3242
|
-
}
|
|
3243
|
-
async function retireMemoryFn(wiring, namespace, memoryId, opts) {
|
|
3244
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3245
|
-
const memory = await storage.getMemoryById(memoryId);
|
|
3246
|
-
if (!memory) throw new CorrectionContractError(`memory not found for retire: ${memoryId}`);
|
|
3247
|
-
const storageStatus = opts.status === "retracted" ? "forgotten" : "superseded";
|
|
3248
|
-
await storage.writeMemoryFrontmatter(memory, {
|
|
3249
|
-
status: storageStatus,
|
|
3250
|
-
...opts.supersededBy ? { supersededBy: opts.supersededBy } : {},
|
|
3251
|
-
...opts.status === "superseded" ? { supersededAt: (/* @__PURE__ */ new Date()).toISOString() } : {},
|
|
3252
|
-
// validUntil is the bi-temporal end; absent when the gate is off.
|
|
3253
|
-
...opts.validUntil ? { invalid_at: opts.validUntil } : {}
|
|
3254
|
-
});
|
|
3255
|
-
}
|
|
3256
|
-
async function rescopeMemoryFn(wiring, namespace, memoryId, toNamespace) {
|
|
3257
|
-
const sourceStorage = await wiring.orchestrator.getStorage(namespace);
|
|
3258
|
-
const memory = await sourceStorage.getMemoryById(memoryId);
|
|
3259
|
-
if (!memory) throw new CorrectionContractError(`memory not found for rescope: ${memoryId}`);
|
|
3260
|
-
if (memory.frontmatter.status && memory.frontmatter.status !== "active") {
|
|
3261
|
-
throw new CorrectionContractError(
|
|
3262
|
-
`cannot rescope memory ${memoryId}: source is ${memory.frontmatter.status}, not active`
|
|
3263
|
-
);
|
|
3264
|
-
}
|
|
3265
|
-
const destStorage = await wiring.orchestrator.getStorage(toNamespace);
|
|
3266
|
-
const fm = memory.frontmatter;
|
|
3267
|
-
const destContent = fm.structuredAttributes ? stripAttributesSuffix(memory.content) : memory.content;
|
|
3268
|
-
const destId = await destStorage.writeMemory(fm.category, destContent, {
|
|
3269
|
-
source: `correction:rescope:${namespace}`,
|
|
3270
|
-
...typeof fm.confidence === "number" ? { confidence: fm.confidence } : {},
|
|
3271
|
-
...Array.isArray(fm.tags) ? { tags: fm.tags } : {},
|
|
3272
|
-
...fm.entityRef ? { entityRef: fm.entityRef } : {},
|
|
3273
|
-
...fm.structuredAttributes ? { structuredAttributes: fm.structuredAttributes } : {},
|
|
3274
|
-
...fm.valid_at ? { validAt: fm.valid_at } : {},
|
|
3275
|
-
...fm.observedAt ? { observedAt: fm.observedAt } : {},
|
|
3276
|
-
...fm.memoryKind ? { memoryKind: fm.memoryKind } : {},
|
|
3277
|
-
...Array.isArray(fm.links) ? { links: fm.links } : {},
|
|
3278
|
-
...fm.intentGoal ? { intentGoal: fm.intentGoal } : {}
|
|
3279
|
-
});
|
|
3280
|
-
try {
|
|
3281
|
-
await sourceStorage.writeMemoryFrontmatter(memory, {
|
|
3282
|
-
status: "archived",
|
|
3283
|
-
archivedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3284
|
-
});
|
|
3285
|
-
} catch (err) {
|
|
3286
|
-
try {
|
|
3287
|
-
const destMem = await destStorage.getMemoryById(destId);
|
|
3288
|
-
if (destMem) {
|
|
3289
|
-
await destStorage.writeMemoryFrontmatter(destMem, {
|
|
3290
|
-
status: "archived",
|
|
3291
|
-
archivedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3292
|
-
});
|
|
3293
|
-
}
|
|
3294
|
-
} catch {
|
|
3295
|
-
}
|
|
3296
|
-
throw err;
|
|
3297
|
-
}
|
|
3298
|
-
return destId;
|
|
3299
|
-
}
|
|
3300
|
-
async function appendTombstoneFn(wiring, namespace, input) {
|
|
3301
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3302
|
-
const enabled = typeof storage.isTombstonesEnabled === "function" ? storage.isTombstonesEnabled() : true;
|
|
3303
|
-
const result = await storage.appendTombstone({
|
|
3304
|
-
reason: input.reason,
|
|
3305
|
-
createdBy: "user_correction",
|
|
3306
|
-
sourceMemoryId: input.sourceMemoryId,
|
|
3307
|
-
rawContent: input.rawContent,
|
|
3308
|
-
...input.entityRef ? { entityRef: input.entityRef } : {},
|
|
3309
|
-
...input.supersessionKey ? { supersessionKey: input.supersessionKey } : {}
|
|
3310
|
-
});
|
|
3311
|
-
if (result === null && enabled) {
|
|
3312
|
-
throw new CorrectionContractError(
|
|
3313
|
-
`tombstone persistence failed for memory ${input.sourceMemoryId} (tombstones enabled but store returned null \u2014 I/O error swallowed)`
|
|
3314
|
-
);
|
|
3315
|
-
}
|
|
3316
|
-
return result;
|
|
3317
|
-
}
|
|
3318
|
-
async function registerRedactionRuleFn(wiring, namespace, pattern) {
|
|
3319
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3320
|
-
const dir = path5.join(storage.dir, "state", "corrections", "redaction-rules");
|
|
3321
|
-
await mkdir3(dir, { recursive: true });
|
|
3322
|
-
const slug = pattern.replace(/[^a-zA-Z0-9]+/g, "-").slice(0, 64) || "rule";
|
|
3323
|
-
await writeFile3(
|
|
3324
|
-
path5.join(dir, `${slug}.json`),
|
|
3325
|
-
`${JSON.stringify({ pattern, namespace, createdAt: (/* @__PURE__ */ new Date()).toISOString() })}
|
|
3326
|
-
`,
|
|
3327
|
-
"utf-8"
|
|
3328
|
-
);
|
|
3329
|
-
}
|
|
3330
|
-
async function appendAuditRecordFn(wiring, namespace, record) {
|
|
3331
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3332
|
-
const id = await storage.writeMemory("correction", buildAuditBody(record), {
|
|
3333
|
-
source: "correction-contract",
|
|
3334
|
-
confidence: 1,
|
|
3335
|
-
tags: ["correction-audit", `plan:${record.planId}`, `classification:${record.classification}`]
|
|
3336
|
-
});
|
|
3337
|
-
return id;
|
|
3338
|
-
}
|
|
3339
|
-
function buildAuditBody(record) {
|
|
3340
|
-
const sensitive = record.classification === "never_store" || record.outcome.results.some((r) => r.action.kind === "redaction_rule");
|
|
3341
|
-
const safeRequest = sensitive ? "[redacted \u2014 never-store/redaction correction text withheld from the audit trail]" : record.requestText.slice(0, 200);
|
|
3342
|
-
const lines = [
|
|
3343
|
-
`Correction plan ${record.planId} applied (${record.outcome.status}).`,
|
|
3344
|
-
"",
|
|
3345
|
-
`Request: ${safeRequest}`,
|
|
3346
|
-
`Classification: ${record.classification}`,
|
|
3347
|
-
`Applied at: ${record.outcome.appliedAt}`,
|
|
3348
|
-
"",
|
|
3349
|
-
"Actions:"
|
|
3350
|
-
];
|
|
3351
|
-
for (const r of record.outcome.results) {
|
|
3352
|
-
const withhold = r.action.kind === "redaction_rule" || record.classification === "never_store";
|
|
3353
|
-
const errPart = r.error ? withhold ? " (error withheld)" : ` (${r.error})` : "";
|
|
3354
|
-
lines.push(` - ${r.action.kind}: ${r.status}${errPart}`);
|
|
3355
|
-
}
|
|
3356
|
-
return lines.join("\n");
|
|
3357
|
-
}
|
|
3358
|
-
async function propagateFn(wiring, namespace, touchedMemoryIds) {
|
|
3359
|
-
for (const id of touchedMemoryIds) {
|
|
3360
|
-
try {
|
|
3361
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
3362
|
-
const orchestrator = wiring.orchestrator;
|
|
3363
|
-
if (typeof orchestrator.indexPersistedMemory === "function") {
|
|
3364
|
-
await orchestrator.indexPersistedMemory(storage, id);
|
|
3365
|
-
}
|
|
3366
|
-
} catch {
|
|
3367
|
-
}
|
|
3368
|
-
}
|
|
3369
|
-
}
|
|
3370
|
-
function toCandidate(m, namespace, score) {
|
|
3371
|
-
return {
|
|
3372
|
-
memoryId: m.frontmatter.id,
|
|
3373
|
-
path: m.path,
|
|
3374
|
-
content: m.content,
|
|
3375
|
-
excerpt: m.content.slice(0, 160),
|
|
3376
|
-
...m.frontmatter.entityRef ? { entityRef: m.frontmatter.entityRef } : {},
|
|
3377
|
-
score
|
|
3378
|
-
// namespace is implicit (the planner scopes by namespace); keep it on the
|
|
3379
|
-
// candidate for diff rendering if needed.
|
|
3380
|
-
};
|
|
3381
|
-
}
|
|
3382
|
-
function toExecutorMemory(m) {
|
|
3383
|
-
const fm = m.frontmatter;
|
|
3384
|
-
const rawBody = fm.structuredAttributes ? stripAttributesSuffix(m.content) : m.content;
|
|
3385
|
-
return {
|
|
3386
|
-
memoryId: fm.id,
|
|
3387
|
-
content: m.content,
|
|
3388
|
-
category: fm.category,
|
|
3389
|
-
rawContent: rawBody,
|
|
3390
|
-
...fm.entityRef ? { entityRef: fm.entityRef } : {}
|
|
3391
|
-
};
|
|
3392
|
-
}
|
|
3393
|
-
function isCorrectionFeatureEnabled(config) {
|
|
3394
|
-
if (typeof config.correctionEnabled === "boolean") return config.correctionEnabled;
|
|
3395
|
-
const nested = config.correction;
|
|
3396
|
-
if (nested && typeof nested.enabled === "boolean") return nested.enabled;
|
|
3397
|
-
if (nested && typeof nested.enabled === "string") return nested.enabled === "true" || nested.enabled === "1";
|
|
3398
|
-
return readCorrectionFlag(config, "enabled", true);
|
|
3399
|
-
}
|
|
3400
|
-
function readCorrectionFlag(config, key, fallback) {
|
|
3401
|
-
const nested = config.correction;
|
|
3402
|
-
if (nested && typeof nested[key] === "boolean") return nested[key];
|
|
3403
|
-
if (nested && typeof nested[key] === "string") return nested[key] === "true" || nested[key] === "1";
|
|
3404
|
-
const raw = config[`correction${capitalize(key)}`];
|
|
3405
|
-
if (typeof raw === "boolean") return raw;
|
|
3406
|
-
if (typeof raw === "string") return raw === "true" || raw === "1";
|
|
3407
|
-
return fallback;
|
|
3408
|
-
}
|
|
3409
|
-
function readCorrectionNumber(config, key, fallback) {
|
|
3410
|
-
const nested = config.correction;
|
|
3411
|
-
if (nested) {
|
|
3412
|
-
const nv = nested[key];
|
|
3413
|
-
if (typeof nv === "number" && Number.isFinite(nv)) return nv;
|
|
3414
|
-
if (typeof nv === "string") {
|
|
3415
|
-
const nn = Number(nv);
|
|
3416
|
-
if (Number.isFinite(nn)) return nn;
|
|
3417
|
-
}
|
|
3418
|
-
}
|
|
3419
|
-
const raw = config[`correction${capitalize(key)}`];
|
|
3420
|
-
if (typeof raw === "number" && Number.isFinite(raw)) return raw;
|
|
3421
|
-
if (typeof raw === "string") {
|
|
3422
|
-
const n = Number(raw);
|
|
3423
|
-
if (Number.isFinite(n)) return n;
|
|
3424
|
-
}
|
|
3425
|
-
return fallback;
|
|
3426
|
-
}
|
|
3427
|
-
function capitalize(s) {
|
|
3428
|
-
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
3429
|
-
}
|
|
3430
|
-
function errMsg2(err) {
|
|
3431
|
-
if (err instanceof Error) return err.message;
|
|
3432
|
-
return String(err);
|
|
3433
|
-
}
|
|
3434
|
-
var CLASSIFY_SYSTEM_PROMPT = `You classify memory corrections and draft per-memory actions.
|
|
3435
|
-
|
|
3436
|
-
Given a correction statement and candidate memories, respond with a JSON object:
|
|
3437
|
-
{
|
|
3438
|
-
"classification": "wrong" | "outdated" | "incomplete" | "wrong_scope" | "never_store",
|
|
3439
|
-
"confidence": <number 0..1>,
|
|
3440
|
-
"actions": [<one or more correction actions>],
|
|
3441
|
-
"relevance": [{"memoryId": "<id>", "why": "<one short sentence>"}]
|
|
3442
|
-
}
|
|
3443
|
-
|
|
3444
|
-
Action shapes:
|
|
3445
|
-
- {"kind":"supersede","loserId":"<id>","replacement":{"content":"<new fact>"}}
|
|
3446
|
-
- {"kind":"edit","memoryId":"<id>","patch":"<new full content>"}
|
|
3447
|
-
- {"kind":"retract","memoryId":"<id>"}
|
|
3448
|
-
- {"kind":"rescope","memoryId":"<id>","toNamespace":"<ns>"}
|
|
3449
|
-
- {"kind":"redaction_rule","pattern":"<bounded literal or regex>"}
|
|
3450
|
-
|
|
3451
|
-
Only emit actions you are confident in. If uncertain, return confidence < 0.5 and few actions.`;
|
|
3452
|
-
function buildClassifyPrompt(text, candidates) {
|
|
3453
|
-
const lines = [
|
|
3454
|
-
`Correction: ${text}`,
|
|
3455
|
-
"",
|
|
3456
|
-
"Candidate memories:"
|
|
3457
|
-
];
|
|
3458
|
-
for (const c of candidates.slice(0, 20)) {
|
|
3459
|
-
lines.push(`[${c.memoryId}] ${c.excerpt}`);
|
|
3460
|
-
}
|
|
3461
|
-
lines.push("", "Respond with the JSON object only.");
|
|
3462
|
-
return lines.join("\n");
|
|
3463
|
-
}
|
|
3464
|
-
function parseClassifyResponse(raw, candidates) {
|
|
3465
|
-
let parsed;
|
|
3466
|
-
try {
|
|
3467
|
-
parsed = JSON.parse(raw);
|
|
3468
|
-
} catch {
|
|
3469
|
-
return fallbackClassification(candidates, "LLM returned non-JSON response");
|
|
3470
|
-
}
|
|
3471
|
-
if (!parsed || typeof parsed !== "object") {
|
|
3472
|
-
return fallbackClassification(candidates, "LLM returned non-object response");
|
|
3473
|
-
}
|
|
3474
|
-
const obj = parsed;
|
|
3475
|
-
const classification = isClassification(obj.classification) ? obj.classification : "outdated";
|
|
3476
|
-
const confidence = typeof obj.confidence === "number" ? Math.min(1, Math.max(0, obj.confidence)) : 0.5;
|
|
3477
|
-
const rawActions = Array.isArray(obj.actions) ? obj.actions : [];
|
|
3478
|
-
const actions = [];
|
|
3479
|
-
const warnings = [];
|
|
3480
|
-
for (const rawAction of rawActions) {
|
|
3481
|
-
try {
|
|
3482
|
-
validateCorrectionAction(rawAction);
|
|
3483
|
-
actions.push(rawAction);
|
|
3484
|
-
} catch (err) {
|
|
3485
|
-
warnings.push(`dropped malformed action: ${errMsg2(err)}`);
|
|
3486
|
-
}
|
|
3487
|
-
}
|
|
3488
|
-
const relevance = Array.isArray(obj.relevance) ? obj.relevance.filter((r) => !!r && typeof r === "object").map((r) => ({
|
|
3489
|
-
memoryId: typeof r.memoryId === "string" ? r.memoryId : "",
|
|
3490
|
-
why: typeof r.why === "string" ? r.why : ""
|
|
3491
|
-
})).filter((r) => r.memoryId.length > 0) : [];
|
|
3492
|
-
return {
|
|
3493
|
-
classification,
|
|
3494
|
-
confidence,
|
|
3495
|
-
actions,
|
|
3496
|
-
relevance,
|
|
3497
|
-
warnings
|
|
3498
|
-
};
|
|
3499
|
-
}
|
|
3500
|
-
function isClassification(value) {
|
|
3501
|
-
return value === "wrong" || value === "outdated" || value === "incomplete" || value === "wrong_scope" || value === "never_store";
|
|
3502
|
-
}
|
|
3503
|
-
function fallbackClassification(candidates, reason) {
|
|
3504
|
-
return {
|
|
3505
|
-
classification: "outdated",
|
|
3506
|
-
confidence: 0,
|
|
3507
|
-
actions: [],
|
|
3508
|
-
relevance: candidates.map((c) => ({ memoryId: c.memoryId, why: "located for review" })),
|
|
3509
|
-
warnings: [reason],
|
|
3510
|
-
fallback: true
|
|
3511
|
-
};
|
|
3512
|
-
}
|
|
3513
|
-
|
|
3514
2142
|
// src/procedural/procedure-miner.ts
|
|
3515
2143
|
import { createHash as createHash2 } from "crypto";
|
|
3516
|
-
import { mkdir as
|
|
3517
|
-
import
|
|
2144
|
+
import { mkdir as mkdir2, rm, stat } from "fs/promises";
|
|
2145
|
+
import path4 from "path";
|
|
3518
2146
|
var PROCEDURE_CLUSTER_ATTR_MAX = 500;
|
|
3519
2147
|
var PROCEDURE_CLUSTER_LOCK_STALE_MS = 12e4;
|
|
3520
2148
|
var PROCEDURE_CLUSTER_LOCK_TIMEOUT_MS = 3e4;
|
|
@@ -3534,14 +2162,14 @@ function sleep(ms) {
|
|
|
3534
2162
|
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
3535
2163
|
}
|
|
3536
2164
|
async function acquireClusterWriteLock(memoryDir, clusterHash) {
|
|
3537
|
-
const lockRoot =
|
|
3538
|
-
const lockDir =
|
|
3539
|
-
await
|
|
2165
|
+
const lockRoot = path4.join(path4.resolve(memoryDir), "state", "procedure-miner-locks");
|
|
2166
|
+
const lockDir = path4.join(lockRoot, `${clusterHash}.lock`);
|
|
2167
|
+
await mkdir2(lockRoot, { recursive: true });
|
|
3540
2168
|
const startedAt = Date.now();
|
|
3541
2169
|
let attempts = 0;
|
|
3542
2170
|
while (true) {
|
|
3543
2171
|
try {
|
|
3544
|
-
await
|
|
2172
|
+
await mkdir2(lockDir);
|
|
3545
2173
|
return async () => {
|
|
3546
2174
|
await rm(lockDir, { recursive: true, force: true });
|
|
3547
2175
|
};
|
|
@@ -3566,7 +2194,7 @@ async function acquireClusterWriteLock(memoryDir, clusterHash) {
|
|
|
3566
2194
|
}
|
|
3567
2195
|
}
|
|
3568
2196
|
async function withClusterWriteLock(memoryDir, clusterHash, fn) {
|
|
3569
|
-
const inProcessKey = `${
|
|
2197
|
+
const inProcessKey = `${path4.resolve(memoryDir)}:${clusterHash}`;
|
|
3570
2198
|
const previous = inProcessClusterWriteLocks.get(inProcessKey) ?? Promise.resolve();
|
|
3571
2199
|
let releaseInProcess;
|
|
3572
2200
|
const current = previous.catch(() => void 0).then(
|
|
@@ -3805,7 +2433,7 @@ function formatProcedureStatsText(report) {
|
|
|
3805
2433
|
}
|
|
3806
2434
|
|
|
3807
2435
|
// src/admin/admin-surfaces.ts
|
|
3808
|
-
import
|
|
2436
|
+
import path5 from "path";
|
|
3809
2437
|
var REDACTED = "<redacted>";
|
|
3810
2438
|
var SENSITIVE_KEY_RE = /(token|secret|password|api[_-]?key|bearer|authorization|credential|private[_-]?key)/i;
|
|
3811
2439
|
var BEARER_VALUE_RE = /^(bearer|sk-|pk-|xox[bp]-|AKIA)/i;
|
|
@@ -4036,7 +2664,7 @@ async function auditTranscripts(memoryDir) {
|
|
|
4036
2664
|
movedEntries: file.groups.reduce((sum, group) => sum + group.entryCount, 0),
|
|
4037
2665
|
unmovableLines: file.unmovableLines
|
|
4038
2666
|
}));
|
|
4039
|
-
const mixedOtherDefault = files.some((file) => file.sourceRelPath.split(
|
|
2667
|
+
const mixedOtherDefault = files.some((file) => file.sourceRelPath.split(path5.sep).includes("other"));
|
|
4040
2668
|
const summary = plan.movedEntries === 0 ? "No mixed-session transcript data detected; nothing to migrate." : `Found ${plan.movedEntries} entries across ${plan.distinctSessions} distinct sessions stranded in shared/legacy directories. Run the CLI migration command to re-home them.`;
|
|
4041
2669
|
return {
|
|
4042
2670
|
generatedAt: plan.generatedAt,
|
|
@@ -8851,7 +7479,7 @@ ${next}`);
|
|
|
8851
7479
|
const resolvedNs = this.writableNamespaceFor(request.namespace, request.sessionKey, request.principal);
|
|
8852
7480
|
const storage = await this.orchestrator.getStorage(resolvedNs);
|
|
8853
7481
|
const storageDir = storage.dir;
|
|
8854
|
-
const { writeFile:
|
|
7482
|
+
const { writeFile: writeFile2, mkdir: mkdir3 } = await import("fs/promises");
|
|
8855
7483
|
const { join: join2, resolve: resolve2 } = await import("path");
|
|
8856
7484
|
const safeKey = request.sessionKey.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
8857
7485
|
if (!safeKey) throw new EngramAccessInputError("sessionKey is required");
|
|
@@ -8860,10 +7488,10 @@ ${next}`);
|
|
|
8860
7488
|
if (!resolved.startsWith(resolve2(storageDir))) {
|
|
8861
7489
|
throw new EngramAccessInputError("Invalid sessionKey");
|
|
8862
7490
|
}
|
|
8863
|
-
await
|
|
7491
|
+
await mkdir3(checkpointDir, { recursive: true });
|
|
8864
7492
|
const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
|
|
8865
7493
|
const filePath = join2(checkpointDir, `checkpoint-${ts}.md`);
|
|
8866
|
-
await
|
|
7494
|
+
await writeFile2(filePath, request.context, "utf-8");
|
|
8867
7495
|
return { saved: true };
|
|
8868
7496
|
}
|
|
8869
7497
|
async lcmStatus() {
|
|
@@ -9752,7 +8380,6 @@ export {
|
|
|
9752
8380
|
DECISION_SUBCOMMANDS,
|
|
9753
8381
|
isCodegraphToolName,
|
|
9754
8382
|
DELTA_SUBCOMMANDS,
|
|
9755
|
-
CorrectionContractError,
|
|
9756
8383
|
computeProcedureStats,
|
|
9757
8384
|
formatProcedureStatsText,
|
|
9758
8385
|
EngramAccessInputError,
|
|
@@ -9760,4 +8387,4 @@ export {
|
|
|
9760
8387
|
shapeMemorySummary,
|
|
9761
8388
|
EngramAccessService
|
|
9762
8389
|
};
|
|
9763
|
-
//# sourceMappingURL=chunk-
|
|
8390
|
+
//# sourceMappingURL=chunk-F3PVXKHP.js.map
|