@remnic/core 9.3.744 → 9.3.745
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 +17 -15
- package/dist/access-boundary.js +14 -15
- package/dist/access-cli.js +92 -33
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +17 -15
- package/dist/access-http.js +20 -21
- package/dist/access-mcp.d.ts +17 -15
- package/dist/access-mcp.js +18 -19
- package/dist/access-operations-batch.js +16 -17
- package/dist/access-operations.d.ts +17 -15
- package/dist/access-operations.js +17 -18
- package/dist/access-schema.js +3 -3
- package/dist/{access-service-OT3Gk79W.d.ts → access-service-CdY88L86.d.ts} +3 -30
- package/dist/access-service.d.ts +7 -5
- package/dist/access-service.js +13 -14
- package/dist/access-surface-catalog.d.ts +17 -15
- 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/{auto-sync-XHSKKQAH.js → auto-sync-IEBKPGAM.js} +2 -2
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +6 -4
- package/dist/briefing.d.ts +1 -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-CX0CjOaf.d.ts → catalog-D_ZDxu8Y.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/causal-trajectory-graph.d.ts +1 -1
- package/dist/{chunk-WPLRJ4XM.js → chunk-24YDB5QP.js} +2098 -230
- package/dist/chunk-24YDB5QP.js.map +1 -0
- package/dist/{chunk-6XG3NQRC.js → chunk-3IJGF6K2.js} +2 -2
- package/dist/{chunk-U5WVRMCA.js → chunk-5IN26V6W.js} +2 -2
- package/dist/{chunk-XEADGIAA.js → chunk-DIHCFJVV.js} +7 -7
- package/dist/{chunk-C7LDPZJJ.js → chunk-EHYB325U.js} +227 -227
- package/dist/chunk-EHYB325U.js.map +1 -0
- package/dist/{chunk-E7RGJQWP.js → chunk-HIHCB2S6.js} +2 -2
- package/dist/{chunk-JFCS6PQU.js → chunk-JHQUIH3W.js} +5 -5
- package/dist/{chunk-MXDG6SRH.js → chunk-JRDPT6DA.js} +2 -2
- package/dist/{chunk-BYLC4DKI.js → chunk-KMNYXLPL.js} +2 -2
- package/dist/{chunk-TQPSOTC7.js → chunk-L4N7SVNN.js} +8 -10
- package/dist/{chunk-TQPSOTC7.js.map → chunk-L4N7SVNN.js.map} +1 -1
- package/dist/{chunk-DYK27X7V.js → chunk-LMFS64GY.js} +3 -3
- package/dist/{chunk-FWXLKH2H.js → chunk-NVYF5OB6.js} +3 -3
- package/dist/{chunk-G5FP7VSQ.js → chunk-P4FW3ZU5.js} +58 -60
- package/dist/{chunk-G5FP7VSQ.js.map → chunk-P4FW3ZU5.js.map} +1 -1
- package/dist/{chunk-56F6EAQ6.js → chunk-Q3X7GUAQ.js} +2 -2
- package/dist/{chunk-7N7S2RKF.js → chunk-R2OAN6IP.js} +2 -2
- package/dist/{chunk-CHELXDTO.js → chunk-RB6A7OUN.js} +2 -2
- package/dist/{chunk-3EA5LIFJ.js → chunk-SIV3JZPP.js} +2 -2
- package/dist/{chunk-IP5SANO2.js → chunk-UIKZZ242.js} +2 -2
- package/dist/{chunk-UGFPGWJB.js → chunk-URQLO7BX.js} +2 -2
- package/dist/{chunk-5UNSGRCR.js → chunk-WK3NK6SP.js} +162 -16
- package/dist/chunk-WK3NK6SP.js.map +1 -0
- package/dist/{chunk-VE54E6RP.js → chunk-WWVXXSLF.js} +4 -6
- package/dist/{chunk-VE54E6RP.js.map → chunk-WWVXXSLF.js.map} +1 -1
- package/dist/{chunk-WO22UEM3.js → chunk-XTEWVF3C.js} +2 -2
- package/dist/{chunk-SODQQCAZ.js → chunk-YQX63P3W.js} +18011 -12597
- package/dist/chunk-YQX63P3W.js.map +1 -0
- package/dist/{chunk-FCQ7ZYCQ.js → chunk-ZGAJB74V.js} +2 -2
- package/dist/{chunk-NBP3YHHS.js → chunk-ZGZNLRKF.js} +2 -2
- package/dist/{chunk-C7C5WIIF.js → chunk-ZPZ4VVLT.js} +2 -2
- package/dist/{cli-BQiTZ7Zs.d.ts → cli-BNJtn0R0.d.ts} +3 -3
- package/dist/cli.d.ts +9 -7
- package/dist/cli.js +44 -46
- 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/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/contradiction/index.js +4 -4
- 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 +6 -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/graph-dashboard-diff.d.ts +1 -1
- package/dist/graph-dashboard-key.d.ts +1 -1
- package/dist/graph-dashboard-parser.d.ts +1 -1
- package/dist/graph-edge-reinforcement.d.ts +1 -1
- package/dist/graph-snapshot.d.ts +1 -1
- package/dist/graph.d.ts +1 -1
- package/dist/identity-continuity.d.ts +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/index.d.ts +12 -10
- package/dist/index.js +271 -5362
- package/dist/index.js.map +1 -1
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/local-model-endpoint.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 +16 -14
- 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 +10 -11
- package/dist/orchestration/compression-guideline-coordinator.d.ts +1 -1
- package/dist/orchestration/maintenance.d.ts +2 -2
- package/dist/orchestration/maintenance.js +5 -5
- package/dist/{orchestrator-BPQGHpJz.d.ts → orchestrator-BBGXLd20.d.ts} +169 -7
- package/dist/orchestrator.d.ts +6 -4
- package/dist/orchestrator.js +119 -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-planner-llm.d.ts +1 -1
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray.d.ts +1 -1
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/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-ByzGwC9c.d.ts → semantic-consolidation-D3aSiu9t.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/backup.js +2 -2
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/capsule-import.js +1 -1
- package/dist/trust-score-stage.d.ts +1 -1
- package/dist/trust-score.d.ts +1 -1
- package/dist/{types-5Jik3r4G.d.ts → types-CZm6rx9-.d.ts} +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/dist/verified-recall.js +3 -3
- package/package.json +2 -2
- package/src/index.ts +2 -0
- package/src/orchestration/extraction-persist.ts +2785 -0
- package/src/orchestration/extraction-run.ts +874 -0
- package/src/orchestrator.ts +167 -3277
- package/dist/chunk-5UNSGRCR.js.map +0 -1
- package/dist/chunk-A2KKLCOS.js +0 -1889
- package/dist/chunk-A2KKLCOS.js.map +0 -1
- package/dist/chunk-AVBT5WEW.js +0 -153
- package/dist/chunk-AVBT5WEW.js.map +0 -1
- package/dist/chunk-C7LDPZJJ.js.map +0 -1
- package/dist/chunk-SODQQCAZ.js.map +0 -1
- package/dist/chunk-WPLRJ4XM.js.map +0 -1
- /package/dist/{auto-sync-XHSKKQAH.js.map → auto-sync-IEBKPGAM.js.map} +0 -0
- /package/dist/{chunk-6XG3NQRC.js.map → chunk-3IJGF6K2.js.map} +0 -0
- /package/dist/{chunk-U5WVRMCA.js.map → chunk-5IN26V6W.js.map} +0 -0
- /package/dist/{chunk-XEADGIAA.js.map → chunk-DIHCFJVV.js.map} +0 -0
- /package/dist/{chunk-E7RGJQWP.js.map → chunk-HIHCB2S6.js.map} +0 -0
- /package/dist/{chunk-JFCS6PQU.js.map → chunk-JHQUIH3W.js.map} +0 -0
- /package/dist/{chunk-MXDG6SRH.js.map → chunk-JRDPT6DA.js.map} +0 -0
- /package/dist/{chunk-BYLC4DKI.js.map → chunk-KMNYXLPL.js.map} +0 -0
- /package/dist/{chunk-DYK27X7V.js.map → chunk-LMFS64GY.js.map} +0 -0
- /package/dist/{chunk-FWXLKH2H.js.map → chunk-NVYF5OB6.js.map} +0 -0
- /package/dist/{chunk-56F6EAQ6.js.map → chunk-Q3X7GUAQ.js.map} +0 -0
- /package/dist/{chunk-7N7S2RKF.js.map → chunk-R2OAN6IP.js.map} +0 -0
- /package/dist/{chunk-CHELXDTO.js.map → chunk-RB6A7OUN.js.map} +0 -0
- /package/dist/{chunk-3EA5LIFJ.js.map → chunk-SIV3JZPP.js.map} +0 -0
- /package/dist/{chunk-IP5SANO2.js.map → chunk-UIKZZ242.js.map} +0 -0
- /package/dist/{chunk-UGFPGWJB.js.map → chunk-URQLO7BX.js.map} +0 -0
- /package/dist/{chunk-WO22UEM3.js.map → chunk-XTEWVF3C.js.map} +0 -0
- /package/dist/{chunk-FCQ7ZYCQ.js.map → chunk-ZGAJB74V.js.map} +0 -0
- /package/dist/{chunk-NBP3YHHS.js.map → chunk-ZGZNLRKF.js.map} +0 -0
- /package/dist/{chunk-C7C5WIIF.js.map → chunk-ZPZ4VVLT.js.map} +0 -0
package/dist/chunk-A2KKLCOS.js
DELETED
|
@@ -1,1889 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
enqueuePassiveCorrectionNotification
|
|
3
|
-
} from "./chunk-6XG3NQRC.js";
|
|
4
|
-
import {
|
|
5
|
-
stripAttributesSuffix
|
|
6
|
-
} from "./chunk-SVOZFLIQ.js";
|
|
7
|
-
import {
|
|
8
|
-
serializeMutations
|
|
9
|
-
} from "./chunk-LTJAMRGI.js";
|
|
10
|
-
import {
|
|
11
|
-
supersessionKeysForFact
|
|
12
|
-
} from "./chunk-TKZ3AL5V.js";
|
|
13
|
-
import {
|
|
14
|
-
computeContentHash
|
|
15
|
-
} from "./chunk-W5H6ZRPT.js";
|
|
16
|
-
import {
|
|
17
|
-
resolveRecallAuxiliaryCapabilities
|
|
18
|
-
} from "./chunk-VSF7AAGE.js";
|
|
19
|
-
import {
|
|
20
|
-
sanitizeMemoryContent
|
|
21
|
-
} from "./chunk-5GKPFL3S.js";
|
|
22
|
-
import {
|
|
23
|
-
log
|
|
24
|
-
} from "./chunk-NU3CSQ4H.js";
|
|
25
|
-
|
|
26
|
-
// src/correction/correction-contract.ts
|
|
27
|
-
var MEMORY_CATEGORIES = [
|
|
28
|
-
"fact",
|
|
29
|
-
"preference",
|
|
30
|
-
"correction",
|
|
31
|
-
"entity",
|
|
32
|
-
"decision",
|
|
33
|
-
"relationship",
|
|
34
|
-
"principle",
|
|
35
|
-
"commitment",
|
|
36
|
-
"moment",
|
|
37
|
-
"skill",
|
|
38
|
-
"rule",
|
|
39
|
-
"procedure",
|
|
40
|
-
"reasoning_trace"
|
|
41
|
-
];
|
|
42
|
-
var CORRECTION_ACTION_KINDS = [
|
|
43
|
-
"supersede",
|
|
44
|
-
"edit",
|
|
45
|
-
"retract",
|
|
46
|
-
"rescope",
|
|
47
|
-
"redaction_rule"
|
|
48
|
-
];
|
|
49
|
-
var CORRECTION_TEXT_MAX = 1e4;
|
|
50
|
-
var REDACTION_PATTERN_MAX = 256;
|
|
51
|
-
function validateCorrectionRequest(request) {
|
|
52
|
-
if (!request || typeof request !== "object") {
|
|
53
|
-
throw new CorrectionContractError("CorrectionRequest must be an object.");
|
|
54
|
-
}
|
|
55
|
-
const text = typeof request.text === "string" ? request.text.trim() : "";
|
|
56
|
-
if (text.length === 0) {
|
|
57
|
-
throw new CorrectionContractError("CorrectionRequest.text is required and must be non-empty.");
|
|
58
|
-
}
|
|
59
|
-
if (text.length > CORRECTION_TEXT_MAX) {
|
|
60
|
-
throw new CorrectionContractError(
|
|
61
|
-
`CorrectionRequest.text exceeds the ${CORRECTION_TEXT_MAX}-character limit (${text.length}).`
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
const targetIds = Array.isArray(request.targetIds) ? request.targetIds.filter((id) => typeof id === "string" && id.length > 0) : void 0;
|
|
65
|
-
if (targetIds !== void 0 && targetIds.length === 0) {
|
|
66
|
-
return {
|
|
67
|
-
text,
|
|
68
|
-
...request.sessionKey ? { sessionKey: request.sessionKey } : {},
|
|
69
|
-
...request.principal ? { principal: request.principal } : {},
|
|
70
|
-
...request.namespace ? { namespace: request.namespace } : {}
|
|
71
|
-
};
|
|
72
|
-
}
|
|
73
|
-
return {
|
|
74
|
-
text,
|
|
75
|
-
...targetIds ? { targetIds } : {},
|
|
76
|
-
...request.sessionKey ? { sessionKey: request.sessionKey } : {},
|
|
77
|
-
...request.principal ? { principal: request.principal } : {},
|
|
78
|
-
...request.namespace ? { namespace: request.namespace } : {}
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
function validateRedactionPattern(pattern) {
|
|
82
|
-
if (typeof pattern !== "string") {
|
|
83
|
-
throw new CorrectionContractError("redaction_rule.pattern must be a string.");
|
|
84
|
-
}
|
|
85
|
-
const trimmed = pattern.trim();
|
|
86
|
-
if (trimmed.length === 0) {
|
|
87
|
-
throw new CorrectionContractError("redaction_rule.pattern is required.");
|
|
88
|
-
}
|
|
89
|
-
if (trimmed.length > REDACTION_PATTERN_MAX) {
|
|
90
|
-
throw new CorrectionContractError(
|
|
91
|
-
`redaction_rule.pattern exceeds the ${REDACTION_PATTERN_MAX}-character bound.`
|
|
92
|
-
);
|
|
93
|
-
}
|
|
94
|
-
if (isRegexLike(trimmed) && isUnsafeRedactionRegex(trimmed)) {
|
|
95
|
-
throw new CorrectionContractError(
|
|
96
|
-
"redaction_rule.pattern is unsafe \u2014 use a bounded literal or a regex without nested quantifiers / overlapping alternation."
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
if (isRegexLike(trimmed)) {
|
|
100
|
-
const regexBody = trimmed.slice(1, -1);
|
|
101
|
-
if (regexBody.length === 0) {
|
|
102
|
-
throw new CorrectionContractError("redaction_rule.pattern body is empty \u2014 use a non-empty regex.");
|
|
103
|
-
}
|
|
104
|
-
try {
|
|
105
|
-
if (new RegExp(regexBody).test("")) {
|
|
106
|
-
throw new CorrectionContractError(
|
|
107
|
-
"redaction_rule.pattern matches the empty string \u2014 it would withhold every fact."
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
} catch (e) {
|
|
111
|
-
if (e instanceof CorrectionContractError) throw e;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
return trimmed;
|
|
115
|
-
}
|
|
116
|
-
function isRegexLike(pattern) {
|
|
117
|
-
return pattern.startsWith("/") && pattern.endsWith("/") && pattern.length >= 2;
|
|
118
|
-
}
|
|
119
|
-
function isUnsafeRedactionRegex(pattern) {
|
|
120
|
-
const body = pattern.startsWith("/") && pattern.endsWith("/") ? pattern.slice(1, -1) : pattern;
|
|
121
|
-
if (/(?:^|[^\\])\(\.\*\)|(?:^|[^\\])\.\*|(?:^|[^\\])\.\+|^\.([^*+]?)$/.test(body)) {
|
|
122
|
-
return true;
|
|
123
|
-
}
|
|
124
|
-
if (body.length > 512) return true;
|
|
125
|
-
for (let i = 0; i < body.length; i++) {
|
|
126
|
-
if (body[i] !== "(") continue;
|
|
127
|
-
let depth = 1;
|
|
128
|
-
let j = i + 1;
|
|
129
|
-
while (j < body.length && depth > 0) {
|
|
130
|
-
if (body[j] === "\\") {
|
|
131
|
-
j += 2;
|
|
132
|
-
continue;
|
|
133
|
-
}
|
|
134
|
-
if (body[j] === "(") depth++;
|
|
135
|
-
else if (body[j] === ")") depth--;
|
|
136
|
-
j++;
|
|
137
|
-
}
|
|
138
|
-
if (depth !== 0) continue;
|
|
139
|
-
const afterGroup = body[j];
|
|
140
|
-
if (afterGroup !== "+" && afterGroup !== "*" && afterGroup !== "{") continue;
|
|
141
|
-
const groupBody = body.slice(i + 1, j - 1);
|
|
142
|
-
if (/[+*?]$/.test(groupBody) || /\{\d+,?\d*\}[+*?]?$/.test(groupBody)) {
|
|
143
|
-
return true;
|
|
144
|
-
}
|
|
145
|
-
if (groupBody.includes("|")) {
|
|
146
|
-
const branches = groupBody.split("|");
|
|
147
|
-
if (branches.length >= 2) {
|
|
148
|
-
const firstChars = new Set(branches.map((b) => b[0]).filter(Boolean));
|
|
149
|
-
if (firstChars.size < branches.filter((b) => b.length > 0).length) {
|
|
150
|
-
return true;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
i = j;
|
|
155
|
-
}
|
|
156
|
-
return false;
|
|
157
|
-
}
|
|
158
|
-
function validateCorrectionAction(action) {
|
|
159
|
-
if (!action || typeof action !== "object") {
|
|
160
|
-
throw new CorrectionContractError("CorrectionAction must be an object.");
|
|
161
|
-
}
|
|
162
|
-
const a = action;
|
|
163
|
-
if (typeof a.kind !== "string" || !CORRECTION_ACTION_KINDS.includes(a.kind)) {
|
|
164
|
-
throw new CorrectionContractError(
|
|
165
|
-
`CorrectionAction.kind must be one of: ${CORRECTION_ACTION_KINDS.join(", ")}.`
|
|
166
|
-
);
|
|
167
|
-
}
|
|
168
|
-
switch (a.kind) {
|
|
169
|
-
case "supersede":
|
|
170
|
-
if (typeof a.loserId !== "string" || a.loserId.length === 0) {
|
|
171
|
-
throw new CorrectionContractError("supersede.loserId is required.");
|
|
172
|
-
}
|
|
173
|
-
if (a.replacement !== void 0 && a.replacement !== null) {
|
|
174
|
-
validateMemoryDraft(a.replacement);
|
|
175
|
-
}
|
|
176
|
-
break;
|
|
177
|
-
case "edit":
|
|
178
|
-
if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
|
|
179
|
-
throw new CorrectionContractError("edit.memoryId is required.");
|
|
180
|
-
}
|
|
181
|
-
if (typeof a.patch !== "string" || a.patch.length === 0) {
|
|
182
|
-
throw new CorrectionContractError("edit.patch is required and must be non-empty.");
|
|
183
|
-
}
|
|
184
|
-
break;
|
|
185
|
-
case "retract":
|
|
186
|
-
if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
|
|
187
|
-
throw new CorrectionContractError("retract.memoryId is required.");
|
|
188
|
-
}
|
|
189
|
-
break;
|
|
190
|
-
case "rescope":
|
|
191
|
-
if (typeof a.memoryId !== "string" || a.memoryId.length === 0) {
|
|
192
|
-
throw new CorrectionContractError("rescope.memoryId is required.");
|
|
193
|
-
}
|
|
194
|
-
if (typeof a.toNamespace !== "string" || a.toNamespace.trim().length === 0) {
|
|
195
|
-
throw new CorrectionContractError("rescope.toNamespace is required.");
|
|
196
|
-
}
|
|
197
|
-
break;
|
|
198
|
-
case "redaction_rule":
|
|
199
|
-
if (typeof a.pattern !== "string") {
|
|
200
|
-
throw new CorrectionContractError("redaction_rule.pattern is required.");
|
|
201
|
-
}
|
|
202
|
-
validateRedactionPattern(a.pattern);
|
|
203
|
-
break;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
function validateMemoryDraft(draft) {
|
|
207
|
-
if (!draft || typeof draft !== "object") {
|
|
208
|
-
throw new CorrectionContractError("MemoryDraft must be an object.");
|
|
209
|
-
}
|
|
210
|
-
const d = draft;
|
|
211
|
-
if (typeof d.content !== "string" || d.content.trim().length === 0) {
|
|
212
|
-
throw new CorrectionContractError("MemoryDraft.content is required and must be non-empty.");
|
|
213
|
-
}
|
|
214
|
-
if (d.category !== void 0) {
|
|
215
|
-
if (typeof d.category !== "string" || !MEMORY_CATEGORIES.includes(d.category)) {
|
|
216
|
-
throw new CorrectionContractError(
|
|
217
|
-
`MemoryDraft.category must be one of: ${MEMORY_CATEGORIES.join(", ")}.`
|
|
218
|
-
);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
if (d.confidence !== void 0 && (typeof d.confidence !== "number" || d.confidence < 0 || d.confidence > 1)) {
|
|
222
|
-
throw new CorrectionContractError("MemoryDraft.confidence must be a number in [0, 1].");
|
|
223
|
-
}
|
|
224
|
-
if (d.tags !== void 0 && !Array.isArray(d.tags)) {
|
|
225
|
-
throw new CorrectionContractError("MemoryDraft.tags must be an array.");
|
|
226
|
-
}
|
|
227
|
-
if (d.structuredAttributes !== void 0 && (typeof d.structuredAttributes !== "object" || d.structuredAttributes === null)) {
|
|
228
|
-
throw new CorrectionContractError("MemoryDraft.structuredAttributes must be an object.");
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
function deterministicFallbackPlan(args) {
|
|
232
|
-
return {
|
|
233
|
-
planId: newPlanId(),
|
|
234
|
-
request: args.request,
|
|
235
|
-
namespace: args.namespace,
|
|
236
|
-
affected: args.affected,
|
|
237
|
-
classification: "outdated",
|
|
238
|
-
actions: [],
|
|
239
|
-
diff: "",
|
|
240
|
-
confidence: 0,
|
|
241
|
-
warnings: [...args.warnings, "planner LLM unavailable \u2014 manual action selection required"],
|
|
242
|
-
createdAt: args.createdAt,
|
|
243
|
-
expiresAt: args.expiresAt,
|
|
244
|
-
status: "pending"
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
function newPlanId() {
|
|
248
|
-
return `corr-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
249
|
-
}
|
|
250
|
-
var CorrectionContractError = class extends Error {
|
|
251
|
-
constructor(message) {
|
|
252
|
-
super(message);
|
|
253
|
-
this.name = "CorrectionContractError";
|
|
254
|
-
}
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
// src/correction/correction-access-wiring.ts
|
|
258
|
-
import path2 from "path";
|
|
259
|
-
import { createHash } from "crypto";
|
|
260
|
-
import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
|
|
261
|
-
|
|
262
|
-
// src/correction/correction-planner.ts
|
|
263
|
-
import { mkdir, readFile, rename, unlink, readdir, writeFile } from "fs/promises";
|
|
264
|
-
import path from "path";
|
|
265
|
-
var REDACTED_REQUEST_TEXT = "[redacted \u2014 never-store/redaction correction text withheld from the pending-plan file]";
|
|
266
|
-
var CorrectionPlanner = class _CorrectionPlanner {
|
|
267
|
-
constructor(deps) {
|
|
268
|
-
this.deps = deps;
|
|
269
|
-
}
|
|
270
|
-
deps;
|
|
271
|
-
/**
|
|
272
|
-
* Plan a correction. `readableNamespaces` is the AUTHORIZED read scope the
|
|
273
|
-
* service resolved for this caller; the planner never trusts a caller string.
|
|
274
|
-
*/
|
|
275
|
-
async plan(request, readableNamespaces) {
|
|
276
|
-
const cleaned = validateCorrectionRequest(request);
|
|
277
|
-
if (cleaned.text.length > CORRECTION_TEXT_MAX) {
|
|
278
|
-
throw new CorrectionContractError("CorrectionRequest.text too long.");
|
|
279
|
-
}
|
|
280
|
-
if (cleaned.targetIds && cleaned.targetIds.length > this.deps.maxAffected) {
|
|
281
|
-
throw new CorrectionContractError(
|
|
282
|
-
`Correction target list (${cleaned.targetIds.length}) exceeds maxAffected (${this.deps.maxAffected}) \u2014 narrow the target set.`
|
|
283
|
-
);
|
|
284
|
-
}
|
|
285
|
-
const namespaces = readableNamespaces;
|
|
286
|
-
if (namespaces.length === 0) {
|
|
287
|
-
throw new CorrectionContractError(
|
|
288
|
-
"Correction requires at least one readable namespace \u2014 principal has no read scope."
|
|
289
|
-
);
|
|
290
|
-
}
|
|
291
|
-
const located = await this.locateCandidates(cleaned, namespaces);
|
|
292
|
-
if (located.candidates.length === 0) {
|
|
293
|
-
return this.persist(
|
|
294
|
-
this.emptyPlan(cleaned, namespaces[0], "no matching memories found for the correction text")
|
|
295
|
-
);
|
|
296
|
-
}
|
|
297
|
-
const llm = await this.deps.classifyAndDraft({
|
|
298
|
-
text: cleaned.text,
|
|
299
|
-
candidates: located.candidates
|
|
300
|
-
});
|
|
301
|
-
for (const action of llm.actions) {
|
|
302
|
-
validateCorrectionAction(action);
|
|
303
|
-
if (action.kind === "redaction_rule") {
|
|
304
|
-
validateRedactionPattern(action.pattern);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
const affected = this.deriveAffected(located.candidates, llm);
|
|
308
|
-
const touchedCount = new Set(
|
|
309
|
-
llm.actions.map(
|
|
310
|
-
(a) => a.kind === "supersede" ? a.loserId : a.kind === "edit" || a.kind === "retract" || a.kind === "rescope" ? a.memoryId : null
|
|
311
|
-
).filter((id) => id !== null)
|
|
312
|
-
).size;
|
|
313
|
-
if (touchedCount > this.deps.maxAffected) {
|
|
314
|
-
throw new CorrectionContractError(
|
|
315
|
-
`Correction touches ${touchedCount} memories, exceeding the maxAffected limit of ${this.deps.maxAffected}. Narrow the correction text or supply explicit targetIds.`
|
|
316
|
-
);
|
|
317
|
-
}
|
|
318
|
-
const candidateIds = new Set(located.candidates.map((c) => c.memoryId));
|
|
319
|
-
if (llm.actions.length > 0 && candidateIds.size > 0) {
|
|
320
|
-
const filtered = llm.actions.filter((action) => {
|
|
321
|
-
const id = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : null;
|
|
322
|
-
return id === null || candidateIds.has(id);
|
|
323
|
-
});
|
|
324
|
-
if (filtered.length < llm.actions.length) {
|
|
325
|
-
const dropped = llm.actions.length - filtered.length;
|
|
326
|
-
llm.warnings = [...llm.warnings, `${dropped} action(s) targeted memories outside the located candidate set and were dropped (prompt-injection guard).`];
|
|
327
|
-
llm.actions = filtered;
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
const diff = llm.fallback ? "" : await this.deps.renderDiff({ candidates: located.candidates, actions: llm.actions });
|
|
331
|
-
const createdAt = this.deps.now().toISOString();
|
|
332
|
-
const expiresAt = new Date(
|
|
333
|
-
this.deps.now().getTime() + this.deps.planTtlHours * 60 * 60 * 1e3
|
|
334
|
-
).toISOString();
|
|
335
|
-
const plan = llm.fallback ? deterministicFallbackPlan({
|
|
336
|
-
request: cleaned,
|
|
337
|
-
namespace: namespaces[0],
|
|
338
|
-
affected,
|
|
339
|
-
warnings: llm.warnings,
|
|
340
|
-
createdAt,
|
|
341
|
-
expiresAt
|
|
342
|
-
}) : {
|
|
343
|
-
planId: newPlanId(),
|
|
344
|
-
request: cleaned,
|
|
345
|
-
namespace: namespaces[0],
|
|
346
|
-
affected,
|
|
347
|
-
classification: llm.classification,
|
|
348
|
-
actions: llm.actions,
|
|
349
|
-
diff,
|
|
350
|
-
confidence: clampConfidence(llm.confidence),
|
|
351
|
-
warnings: llm.warnings,
|
|
352
|
-
createdAt,
|
|
353
|
-
expiresAt,
|
|
354
|
-
status: "pending"
|
|
355
|
-
};
|
|
356
|
-
return this.persist(plan);
|
|
357
|
-
}
|
|
358
|
-
async locateCandidates(request, namespaces) {
|
|
359
|
-
if (request.targetIds && request.targetIds.length > 0) {
|
|
360
|
-
const targets = await this.deps.resolveTargets({
|
|
361
|
-
targetIds: request.targetIds,
|
|
362
|
-
namespaces
|
|
363
|
-
});
|
|
364
|
-
const seedIds2 = targets.map((c) => c.memoryId);
|
|
365
|
-
const neighbors2 = await this.deps.expandNeighbors({
|
|
366
|
-
seedIds: seedIds2,
|
|
367
|
-
namespaces,
|
|
368
|
-
limit: this.deps.maxAffected
|
|
369
|
-
});
|
|
370
|
-
return { candidates: mergeCandidates(targets, neighbors2).slice(0, this.deps.maxAffected) };
|
|
371
|
-
}
|
|
372
|
-
const searched = await this.deps.searchCorpus({
|
|
373
|
-
text: request.text,
|
|
374
|
-
namespaces,
|
|
375
|
-
limit: this.deps.maxAffected
|
|
376
|
-
});
|
|
377
|
-
if (searched.length === 0) return { candidates: [] };
|
|
378
|
-
const seedIds = searched.slice(0, Math.min(5, searched.length)).map((c) => c.memoryId);
|
|
379
|
-
const neighbors = await this.deps.expandNeighbors({
|
|
380
|
-
seedIds,
|
|
381
|
-
namespaces,
|
|
382
|
-
limit: this.deps.maxAffected
|
|
383
|
-
});
|
|
384
|
-
return { candidates: mergeCandidates(searched, neighbors).slice(0, this.deps.maxAffected) };
|
|
385
|
-
}
|
|
386
|
-
deriveAffected(candidates, llm) {
|
|
387
|
-
const byId = new Map(candidates.map((c) => [c.memoryId, c]));
|
|
388
|
-
const out = [];
|
|
389
|
-
for (const rel of llm.relevance) {
|
|
390
|
-
const c = byId.get(rel.memoryId);
|
|
391
|
-
if (!c) continue;
|
|
392
|
-
out.push({
|
|
393
|
-
memoryId: c.memoryId,
|
|
394
|
-
path: c.path,
|
|
395
|
-
excerpt: c.excerpt,
|
|
396
|
-
why: rel.why,
|
|
397
|
-
...c.sourceQuote ? { sourceQuote: c.sourceQuote } : {}
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
const annotated = new Set(out.map((e) => e.memoryId));
|
|
401
|
-
for (const action of llm.actions) {
|
|
402
|
-
const id = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : null;
|
|
403
|
-
if (id && !annotated.has(id)) {
|
|
404
|
-
const c = byId.get(id);
|
|
405
|
-
if (c) {
|
|
406
|
-
out.push({
|
|
407
|
-
memoryId: c.memoryId,
|
|
408
|
-
path: c.path,
|
|
409
|
-
excerpt: c.excerpt,
|
|
410
|
-
why: "touched by a drafted action",
|
|
411
|
-
...c.sourceQuote ? { sourceQuote: c.sourceQuote } : {}
|
|
412
|
-
});
|
|
413
|
-
annotated.add(id);
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
return out;
|
|
418
|
-
}
|
|
419
|
-
emptyPlan(request, namespace, warning) {
|
|
420
|
-
const createdAt = this.deps.now().toISOString();
|
|
421
|
-
const expiresAt = new Date(
|
|
422
|
-
this.deps.now().getTime() + this.deps.planTtlHours * 60 * 60 * 1e3
|
|
423
|
-
).toISOString();
|
|
424
|
-
return {
|
|
425
|
-
planId: newPlanId(),
|
|
426
|
-
request,
|
|
427
|
-
namespace,
|
|
428
|
-
affected: [],
|
|
429
|
-
classification: "outdated",
|
|
430
|
-
actions: [],
|
|
431
|
-
diff: "",
|
|
432
|
-
confidence: 0,
|
|
433
|
-
warnings: [warning],
|
|
434
|
-
createdAt,
|
|
435
|
-
expiresAt,
|
|
436
|
-
status: "pending"
|
|
437
|
-
};
|
|
438
|
-
}
|
|
439
|
-
// -------------------------------------------------------------------------
|
|
440
|
-
// Plan persistence — atomic write (rule 54), serialized per plan id (rule 40).
|
|
441
|
-
// -------------------------------------------------------------------------
|
|
442
|
-
/** Directory holding pending plans for one namespace. */
|
|
443
|
-
async pendingDir(namespace) {
|
|
444
|
-
return path.join(await this.deps.storageDir(namespace), "state", "corrections", "pending");
|
|
445
|
-
}
|
|
446
|
-
async persist(plan) {
|
|
447
|
-
const dir = await this.pendingDir(plan.namespace);
|
|
448
|
-
const target = path.join(dir, `${plan.planId}.json`);
|
|
449
|
-
const sensitive = plan.classification === "never_store" || plan.actions.some((a) => a.kind === "redaction_rule");
|
|
450
|
-
const persistedPlan = sensitive ? { ...plan, request: { ...plan.request, text: REDACTED_REQUEST_TEXT } } : plan;
|
|
451
|
-
await serializeMutations(`correction-plan:${target}`, async () => {
|
|
452
|
-
await mkdir(dir, { recursive: true });
|
|
453
|
-
const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
454
|
-
await writeFile(tmp, `${JSON.stringify(persistedPlan)}
|
|
455
|
-
`, "utf-8");
|
|
456
|
-
await rename(tmp, target);
|
|
457
|
-
});
|
|
458
|
-
return plan;
|
|
459
|
-
}
|
|
460
|
-
/** Load a pending plan by id (used by the service / executor). */
|
|
461
|
-
async loadPlan(namespace, planId) {
|
|
462
|
-
assertSafePlanId(planId);
|
|
463
|
-
const file = path.join(await this.pendingDir(namespace), `${planId}.json`);
|
|
464
|
-
return serializeMutations(`correction-plan:${file}`, async () => {
|
|
465
|
-
let raw;
|
|
466
|
-
try {
|
|
467
|
-
raw = await readFile(file, "utf-8");
|
|
468
|
-
} catch (err) {
|
|
469
|
-
const code = err?.code;
|
|
470
|
-
if (code === "ENOENT") return null;
|
|
471
|
-
throw err;
|
|
472
|
-
}
|
|
473
|
-
return parsePlan(raw);
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
/** List pending plans (newest first), excluding consumed (applied/discarded). */
|
|
477
|
-
async listPending(namespace) {
|
|
478
|
-
const dir = await this.pendingDir(namespace);
|
|
479
|
-
let files;
|
|
480
|
-
try {
|
|
481
|
-
files = await readdir(dir);
|
|
482
|
-
} catch (err) {
|
|
483
|
-
const code = err?.code;
|
|
484
|
-
if (code === "ENOENT") return [];
|
|
485
|
-
throw err;
|
|
486
|
-
}
|
|
487
|
-
const plans = [];
|
|
488
|
-
for (const f of files) {
|
|
489
|
-
if (!f.endsWith(".json")) continue;
|
|
490
|
-
let plan = null;
|
|
491
|
-
try {
|
|
492
|
-
plan = await this.loadPlan(namespace, f.replace(/\.json$/, ""));
|
|
493
|
-
} catch {
|
|
494
|
-
continue;
|
|
495
|
-
}
|
|
496
|
-
if (plan && plan.status === "pending") plans.push(plan);
|
|
497
|
-
}
|
|
498
|
-
plans.sort((a, b) => a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0);
|
|
499
|
-
return plans;
|
|
500
|
-
}
|
|
501
|
-
async markConsumed(namespace, planId, status) {
|
|
502
|
-
assertSafePlanId(planId);
|
|
503
|
-
const file = path.join(await this.pendingDir(namespace), `${planId}.json`);
|
|
504
|
-
await serializeMutations(`correction-plan:${file}`, async () => {
|
|
505
|
-
let raw;
|
|
506
|
-
try {
|
|
507
|
-
raw = await readFile(file, "utf-8");
|
|
508
|
-
} catch (err) {
|
|
509
|
-
const code = err?.code;
|
|
510
|
-
if (code === "ENOENT") return;
|
|
511
|
-
throw err;
|
|
512
|
-
}
|
|
513
|
-
const plan = parsePlan(raw);
|
|
514
|
-
if (!plan) return;
|
|
515
|
-
plan.status = status;
|
|
516
|
-
if (status === "applying") {
|
|
517
|
-
plan.applyingAt = this.deps.now().toISOString();
|
|
518
|
-
} else {
|
|
519
|
-
delete plan.applyingAt;
|
|
520
|
-
}
|
|
521
|
-
if (status !== "applying") {
|
|
522
|
-
plan.actions = plan.actions.map(
|
|
523
|
-
(a) => a.kind === "redaction_rule" ? { ...a, pattern: "[redacted \u2014 pattern applied]" } : a
|
|
524
|
-
);
|
|
525
|
-
}
|
|
526
|
-
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
527
|
-
await writeFile(tmp, `${JSON.stringify(plan)}
|
|
528
|
-
`, "utf-8");
|
|
529
|
-
await rename(tmp, file);
|
|
530
|
-
});
|
|
531
|
-
}
|
|
532
|
-
async deletePlan(namespace, planId) {
|
|
533
|
-
assertSafePlanId(planId);
|
|
534
|
-
const file = path.join(await this.pendingDir(namespace), `${planId}.json`);
|
|
535
|
-
await serializeMutations(`correction-plan:${file}`, async () => {
|
|
536
|
-
try {
|
|
537
|
-
await unlink(file);
|
|
538
|
-
} catch (err) {
|
|
539
|
-
const code = err?.code;
|
|
540
|
-
if (code === "ENOENT") return;
|
|
541
|
-
throw err;
|
|
542
|
-
}
|
|
543
|
-
});
|
|
544
|
-
}
|
|
545
|
-
/**
|
|
546
|
-
* Stale-applying TTL: a plan in `applying` state longer than this is
|
|
547
|
-
* assumed to be from a crashed process and is recovered on startup
|
|
548
|
-
* (#1713 Item 2). 10 minutes is generous for an apply that normally
|
|
549
|
-
* completes in seconds, yet short enough to avoid leaving stale state.
|
|
550
|
-
*/
|
|
551
|
-
static STALE_APPLYING_TTL_MS = 10 * 60 * 1e3;
|
|
552
|
-
/**
|
|
553
|
-
* Recover stale `applying` plans past the stale-applying TTL (#1713 Item 2).
|
|
554
|
-
*
|
|
555
|
-
* A plan stuck in `applying` means the process died mid-apply. Re-applying
|
|
556
|
-
* wholesale would duplicate succeeded actions (replacements, tombstones,
|
|
557
|
-
* audits), so recovery discards + scrubs the plan instead. The operator
|
|
558
|
-
* inspects the outcome and files a NEW plan for any actions that did not
|
|
559
|
-
* complete. Plans without `applyingAt` (predating this fix) are recovered
|
|
560
|
-
* when they are past their `expiresAt` timestamp.
|
|
561
|
-
*
|
|
562
|
-
* @returns the ids of recovered (discarded) plans.
|
|
563
|
-
*/
|
|
564
|
-
async recoverStaleApplyingPlans(namespace, opts) {
|
|
565
|
-
const ttl = opts?.ttlMs ?? _CorrectionPlanner.STALE_APPLYING_TTL_MS;
|
|
566
|
-
const now = (opts?.now ?? this.deps.now()).getTime();
|
|
567
|
-
const dir = await this.pendingDir(namespace);
|
|
568
|
-
let files;
|
|
569
|
-
try {
|
|
570
|
-
files = await readdir(dir);
|
|
571
|
-
} catch (err) {
|
|
572
|
-
const code = err?.code;
|
|
573
|
-
if (code === "ENOENT") return [];
|
|
574
|
-
throw err;
|
|
575
|
-
}
|
|
576
|
-
const recovered = [];
|
|
577
|
-
for (const f of files) {
|
|
578
|
-
if (!f.endsWith(".json")) continue;
|
|
579
|
-
const planId = f.replace(/\.json$/, "");
|
|
580
|
-
let plan;
|
|
581
|
-
try {
|
|
582
|
-
plan = await this.loadPlan(namespace, planId);
|
|
583
|
-
} catch {
|
|
584
|
-
continue;
|
|
585
|
-
}
|
|
586
|
-
if (!plan || plan.status !== "applying") continue;
|
|
587
|
-
const stale = plan.applyingAt ? now - new Date(plan.applyingAt).getTime() >= ttl : now >= new Date(plan.expiresAt).getTime();
|
|
588
|
-
if (!stale) continue;
|
|
589
|
-
try {
|
|
590
|
-
await this.markConsumed(namespace, planId, "discarded");
|
|
591
|
-
recovered.push(planId);
|
|
592
|
-
} catch {
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
return recovered;
|
|
596
|
-
}
|
|
597
|
-
};
|
|
598
|
-
function assertSafePlanId(planId) {
|
|
599
|
-
if (typeof planId !== "string" || planId.length === 0 || planId.includes("/") || planId.includes("\\") || planId.includes("\0") || planId === "." || planId === ".." || planId.startsWith(".") || planId.includes("..")) {
|
|
600
|
-
throw new CorrectionContractError(
|
|
601
|
-
`Invalid plan id: ${JSON.stringify(planId)} \u2014 must be a bare file basename with no path separators or parent segments.`
|
|
602
|
-
);
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
function clampConfidence(n) {
|
|
606
|
-
if (!Number.isFinite(n)) return 0;
|
|
607
|
-
return Math.min(1, Math.max(0, n));
|
|
608
|
-
}
|
|
609
|
-
function mergeCandidates(a, b) {
|
|
610
|
-
const map = /* @__PURE__ */ new Map();
|
|
611
|
-
for (const c of a) {
|
|
612
|
-
const existing = map.get(c.memoryId);
|
|
613
|
-
if (!existing || c.score > existing.score) map.set(c.memoryId, c);
|
|
614
|
-
}
|
|
615
|
-
for (const c of b) {
|
|
616
|
-
const existing = map.get(c.memoryId);
|
|
617
|
-
if (!existing || c.score > existing.score) map.set(c.memoryId, c);
|
|
618
|
-
}
|
|
619
|
-
return [...map.values()].sort((x, y) => y.score - x.score);
|
|
620
|
-
}
|
|
621
|
-
function parsePlan(raw) {
|
|
622
|
-
let parsed;
|
|
623
|
-
try {
|
|
624
|
-
parsed = JSON.parse(raw);
|
|
625
|
-
} catch {
|
|
626
|
-
return null;
|
|
627
|
-
}
|
|
628
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
629
|
-
const p = parsed;
|
|
630
|
-
if (typeof p.planId !== "string" || typeof p.namespace !== "string") return null;
|
|
631
|
-
if (typeof p.createdAt !== "string" || typeof p.expiresAt !== "string") return null;
|
|
632
|
-
if (!Array.isArray(p.actions) || !Array.isArray(p.affected)) return null;
|
|
633
|
-
for (const action of p.actions) {
|
|
634
|
-
try {
|
|
635
|
-
validateCorrectionAction(action);
|
|
636
|
-
} catch {
|
|
637
|
-
return null;
|
|
638
|
-
}
|
|
639
|
-
}
|
|
640
|
-
return parsed;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
// src/correction/correction-executor.ts
|
|
644
|
-
var CorrectionExecutor = class {
|
|
645
|
-
constructor(deps, planner) {
|
|
646
|
-
this.deps = deps;
|
|
647
|
-
this.planner = planner;
|
|
648
|
-
}
|
|
649
|
-
deps;
|
|
650
|
-
planner;
|
|
651
|
-
/**
|
|
652
|
-
* Apply a persisted plan by id. Idempotent-once: a second apply of the same
|
|
653
|
-
* plan is rejected. Returns the {@link CorrectionOutcome}.
|
|
654
|
-
*/
|
|
655
|
-
async apply(namespace, planId, opts) {
|
|
656
|
-
if (!opts.confirm) {
|
|
657
|
-
throw new CorrectionContractError(
|
|
658
|
-
"Correction apply requires explicit confirmation (correction.applyRequiresConfirm)."
|
|
659
|
-
);
|
|
660
|
-
}
|
|
661
|
-
return serializeMutations(
|
|
662
|
-
`correction-apply:${namespace}:${planId}`,
|
|
663
|
-
() => this.applyInternal(namespace, planId, opts.canWriteDestination)
|
|
664
|
-
);
|
|
665
|
-
}
|
|
666
|
-
async applyInternal(namespace, planId, canWriteDestination) {
|
|
667
|
-
const plan = await this.planner.loadPlan(namespace, planId);
|
|
668
|
-
if (!plan) {
|
|
669
|
-
throw new CorrectionContractError(`Correction plan not found: ${planId}`);
|
|
670
|
-
}
|
|
671
|
-
if (plan.namespace !== namespace) {
|
|
672
|
-
throw new CorrectionContractError(
|
|
673
|
-
`Correction plan ${planId} belongs to namespace '${plan.namespace}', not '${namespace}'.`
|
|
674
|
-
);
|
|
675
|
-
}
|
|
676
|
-
if (plan.status === "applied" || plan.status === "partial" || plan.status === "applying") {
|
|
677
|
-
throw new CorrectionContractError(
|
|
678
|
-
`Correction plan ${planId} has already been applied or is in progress (status=${plan.status}).`
|
|
679
|
-
);
|
|
680
|
-
}
|
|
681
|
-
if (plan.status === "discarded") {
|
|
682
|
-
throw new CorrectionContractError(`Correction plan ${planId} has been discarded.`);
|
|
683
|
-
}
|
|
684
|
-
if (this.deps.now().getTime() > new Date(plan.expiresAt).getTime()) {
|
|
685
|
-
await this.planner.markConsumed(namespace, planId, "discarded");
|
|
686
|
-
throw new CorrectionContractError(
|
|
687
|
-
`Correction plan ${planId} expired at ${plan.expiresAt} and has been discarded.`
|
|
688
|
-
);
|
|
689
|
-
}
|
|
690
|
-
for (const action of plan.actions) {
|
|
691
|
-
validateCorrectionAction(action);
|
|
692
|
-
if (action.kind === "redaction_rule") {
|
|
693
|
-
validateRedactionPattern(action.pattern);
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
try {
|
|
697
|
-
await this.planner.markConsumed(namespace, planId, "applying");
|
|
698
|
-
} catch {
|
|
699
|
-
throw new CorrectionContractError(
|
|
700
|
-
`Correction plan ${planId}: cannot mark in-progress (filesystem unwritable?) \u2014 aborting before any mutation.`
|
|
701
|
-
);
|
|
702
|
-
}
|
|
703
|
-
const results = [];
|
|
704
|
-
const appliedTouched = [];
|
|
705
|
-
for (const action of plan.actions) {
|
|
706
|
-
if (action.kind === "supersede" && action.replacement) {
|
|
707
|
-
const loser = await this.deps.getMemory(namespace, action.loserId);
|
|
708
|
-
if (!loser) {
|
|
709
|
-
results.push({
|
|
710
|
-
action,
|
|
711
|
-
status: "failed",
|
|
712
|
-
error: `supersede loser not found: ${action.loserId}`
|
|
713
|
-
});
|
|
714
|
-
continue;
|
|
715
|
-
}
|
|
716
|
-
try {
|
|
717
|
-
const newId = await this.deps.writeReplacement(namespace, {
|
|
718
|
-
content: action.replacement.content,
|
|
719
|
-
...action.replacement.category ? { category: action.replacement.category } : {},
|
|
720
|
-
...action.replacement.confidence !== void 0 ? { confidence: action.replacement.confidence } : {},
|
|
721
|
-
...action.replacement.tags ? { tags: action.replacement.tags } : {},
|
|
722
|
-
...action.replacement.entityRef ? { entityRef: action.replacement.entityRef } : {},
|
|
723
|
-
...action.replacement.validAt ? { validAt: action.replacement.validAt } : {},
|
|
724
|
-
...action.replacement.observedAt ? { observedAt: action.replacement.observedAt } : {},
|
|
725
|
-
...action.replacement.structuredAttributes ? { structuredAttributes: action.replacement.structuredAttributes } : {},
|
|
726
|
-
supersedes: action.loserId
|
|
727
|
-
});
|
|
728
|
-
results.push({ action, status: "applied", memoryId: newId });
|
|
729
|
-
appliedTouched.push(newId);
|
|
730
|
-
} catch (err) {
|
|
731
|
-
results.push({
|
|
732
|
-
action,
|
|
733
|
-
status: "failed",
|
|
734
|
-
error: errMsg(err)
|
|
735
|
-
});
|
|
736
|
-
}
|
|
737
|
-
} else if (action.kind === "edit") {
|
|
738
|
-
try {
|
|
739
|
-
const editedId = await this.deps.applyEdit(namespace, action.memoryId, action.patch);
|
|
740
|
-
results.push({ action, status: "applied", memoryId: editedId });
|
|
741
|
-
appliedTouched.push(editedId);
|
|
742
|
-
} catch (err) {
|
|
743
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
744
|
-
}
|
|
745
|
-
} else if (action.kind === "redaction_rule") {
|
|
746
|
-
try {
|
|
747
|
-
await this.deps.registerRedactionRule(namespace, action.pattern);
|
|
748
|
-
results.push({ action, status: "applied" });
|
|
749
|
-
} catch (err) {
|
|
750
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
for (const action of plan.actions) {
|
|
755
|
-
if (action.kind === "supersede") {
|
|
756
|
-
const replacementResult = results.find(
|
|
757
|
-
(r) => r.action === action && r.status === "applied"
|
|
758
|
-
);
|
|
759
|
-
if (action.replacement && !replacementResult) {
|
|
760
|
-
continue;
|
|
761
|
-
}
|
|
762
|
-
await this.retireAndTombstone(namespace, action, "supersession", results, appliedTouched, {
|
|
763
|
-
supersededBy: replacementResult?.memoryId
|
|
764
|
-
});
|
|
765
|
-
} else if (action.kind === "retract") {
|
|
766
|
-
await this.retireAndTombstone(namespace, action, "retraction", results, appliedTouched);
|
|
767
|
-
} else if (action.kind === "rescope") {
|
|
768
|
-
try {
|
|
769
|
-
const allowed = canWriteDestination ? await canWriteDestination(action.toNamespace) : true;
|
|
770
|
-
if (!allowed) {
|
|
771
|
-
results.push({
|
|
772
|
-
action,
|
|
773
|
-
status: "failed",
|
|
774
|
-
error: `rescope destination namespace not writable: ${action.toNamespace}`
|
|
775
|
-
});
|
|
776
|
-
continue;
|
|
777
|
-
}
|
|
778
|
-
const destId = await this.deps.rescopeMemory(namespace, action.memoryId, action.toNamespace);
|
|
779
|
-
results.push({ action, status: "applied", memoryId: destId });
|
|
780
|
-
appliedTouched.push(action.memoryId);
|
|
781
|
-
try {
|
|
782
|
-
await this.deps.propagate(action.toNamespace, [destId]);
|
|
783
|
-
} catch {
|
|
784
|
-
}
|
|
785
|
-
} catch (err) {
|
|
786
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
const propagationWarnings = [];
|
|
791
|
-
if (appliedTouched.length > 0) {
|
|
792
|
-
try {
|
|
793
|
-
await this.deps.propagate(namespace, appliedTouched);
|
|
794
|
-
} catch (err) {
|
|
795
|
-
propagationWarnings.push(`propagation failed (non-fatal): ${errMsg(err)}`);
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
const anyFailed = results.some((r) => r.status === "failed");
|
|
799
|
-
const status = anyFailed ? "partial" : "applied";
|
|
800
|
-
const appliedAt = this.deps.now().toISOString();
|
|
801
|
-
const outcome = {
|
|
802
|
-
planId,
|
|
803
|
-
status,
|
|
804
|
-
results,
|
|
805
|
-
auditMemoryId: "",
|
|
806
|
-
// filled after the audit write
|
|
807
|
-
appliedAt
|
|
808
|
-
};
|
|
809
|
-
if (propagationWarnings.length > 0) {
|
|
810
|
-
outcome.warnings = propagationWarnings;
|
|
811
|
-
}
|
|
812
|
-
try {
|
|
813
|
-
const auditId = await this.deps.appendAuditRecord(namespace, {
|
|
814
|
-
planId,
|
|
815
|
-
classification: plan.classification,
|
|
816
|
-
outcome,
|
|
817
|
-
requestText: plan.request.text
|
|
818
|
-
});
|
|
819
|
-
outcome.auditMemoryId = auditId;
|
|
820
|
-
} catch (err) {
|
|
821
|
-
outcome.warnings = [
|
|
822
|
-
...propagationWarnings,
|
|
823
|
-
`audit record write failed (non-fatal): ${errMsg(err)}`
|
|
824
|
-
];
|
|
825
|
-
}
|
|
826
|
-
try {
|
|
827
|
-
await this.planner.markConsumed(namespace, planId, status);
|
|
828
|
-
} catch (err) {
|
|
829
|
-
const w = outcome;
|
|
830
|
-
w.warnings = [...w.warnings ?? [], `plan mark-consumed failed (non-fatal): ${errMsg(err)}`];
|
|
831
|
-
}
|
|
832
|
-
return outcome;
|
|
833
|
-
}
|
|
834
|
-
async retireAndTombstone(namespace, action, reason, results, appliedTouched, opts = {}) {
|
|
835
|
-
const memoryId = action.kind === "supersede" ? action.loserId : action.kind === "retract" ? action.memoryId : null;
|
|
836
|
-
if (!memoryId) return;
|
|
837
|
-
try {
|
|
838
|
-
const memory = await this.deps.getMemory(namespace, memoryId);
|
|
839
|
-
if (!memory) {
|
|
840
|
-
results.push({
|
|
841
|
-
action,
|
|
842
|
-
status: "failed",
|
|
843
|
-
error: `memory not found: ${memoryId}`
|
|
844
|
-
});
|
|
845
|
-
return;
|
|
846
|
-
}
|
|
847
|
-
const validUntil = this.deps.biTemporalEnabled ? this.deps.now().toISOString() : void 0;
|
|
848
|
-
const tombstoneId = await this.deps.appendTombstone(namespace, {
|
|
849
|
-
reason,
|
|
850
|
-
sourceMemoryId: memoryId,
|
|
851
|
-
rawContent: memory.rawContent,
|
|
852
|
-
...memory.entityRef ? { entityRef: memory.entityRef } : {},
|
|
853
|
-
...memory.supersessionKey ? { supersessionKey: memory.supersessionKey } : {},
|
|
854
|
-
// #1672 item 4: carry the canonical contentHash (exact tier) and the
|
|
855
|
-
// full supersession-key set (keyed tier) so paraphrased re-observations
|
|
856
|
-
// of the same supersession identity are blocked, not just the literal
|
|
857
|
-
// body. Without these the tombstone projected from a structured fact
|
|
858
|
-
// dropped both fields and the fact could resurrect.
|
|
859
|
-
...memory.contentHash ? { contentHash: memory.contentHash } : {},
|
|
860
|
-
...memory.supersessionKeys && memory.supersessionKeys.length > 0 ? { supersessionKeys: memory.supersessionKeys } : {}
|
|
861
|
-
});
|
|
862
|
-
await this.deps.retireMemory(namespace, memoryId, {
|
|
863
|
-
status: reason === "supersession" ? "superseded" : "retracted",
|
|
864
|
-
...opts.supersededBy ? { supersededBy: opts.supersededBy } : {},
|
|
865
|
-
...validUntil ? { validUntil } : {}
|
|
866
|
-
});
|
|
867
|
-
results.push({
|
|
868
|
-
action,
|
|
869
|
-
status: "applied",
|
|
870
|
-
memoryId,
|
|
871
|
-
...tombstoneId ? { tombstoneId } : {}
|
|
872
|
-
});
|
|
873
|
-
appliedTouched.push(memoryId);
|
|
874
|
-
} catch (err) {
|
|
875
|
-
results.push({ action, status: "failed", error: errMsg(err) });
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
};
|
|
879
|
-
var CORRECTION_ERROR_MAX = 500;
|
|
880
|
-
function sanitizeErrorMessage(raw) {
|
|
881
|
-
const stripped = raw.replace(/(^|[\s:'"(])\/(?:[^\s'">)\\]+\/)+[^\s'">)\\]*/g, "$1<path>").replace(/(^|[\s:'"(])[A-Za-z]:\\[^\s'">)\\]+(?:\\[^\s'">) ]*)*/g, "$1<path>");
|
|
882
|
-
const trimmed = stripped.trim();
|
|
883
|
-
return trimmed.length > CORRECTION_ERROR_MAX ? `${trimmed.slice(0, CORRECTION_ERROR_MAX)}\u2026` : trimmed;
|
|
884
|
-
}
|
|
885
|
-
function errMsg(err) {
|
|
886
|
-
const raw = err instanceof Error ? err.message : String(err);
|
|
887
|
-
return sanitizeErrorMessage(raw);
|
|
888
|
-
}
|
|
889
|
-
|
|
890
|
-
// src/correction/correction-service.ts
|
|
891
|
-
var CorrectionService = class {
|
|
892
|
-
constructor(deps) {
|
|
893
|
-
this.deps = deps;
|
|
894
|
-
this.planner = new CorrectionPlanner(deps.plannerDeps());
|
|
895
|
-
this.executor = new CorrectionExecutor(deps.executorDeps(), this.planner);
|
|
896
|
-
}
|
|
897
|
-
deps;
|
|
898
|
-
planner;
|
|
899
|
-
executor;
|
|
900
|
-
/**
|
|
901
|
-
* Plan a correction. Read-only — produces + persists a {@link CorrectionPlan}.
|
|
902
|
-
* Safe to run with the gate ON (default) since the plan writes no memory state.
|
|
903
|
-
*
|
|
904
|
-
* The plan is stored under the AUTHORIZED (writable) namespace — the same
|
|
905
|
-
* namespace apply/listPending/discard resolve — so the plan is always
|
|
906
|
-
* found by the caller that created it (review threads: plan-stored-wrong-
|
|
907
|
-
* namespace + cross-namespace candidate mismatch). Candidates are located
|
|
908
|
-
* within that single namespace too: a correction can only affect memories
|
|
909
|
-
* the principal can write, so reading from a non-writable namespace to
|
|
910
|
-
* draft a correction that can never be applied would be misleading.
|
|
911
|
-
*/
|
|
912
|
-
async plan(request) {
|
|
913
|
-
this.requireEnabled();
|
|
914
|
-
const authorized = await this.deps.policy.resolveAuthorizedNamespace(request);
|
|
915
|
-
return this.planner.plan(request, [authorized]);
|
|
916
|
-
}
|
|
917
|
-
/**
|
|
918
|
-
* Apply a persisted plan by id. Requires `confirm: true` (or interactive
|
|
919
|
-
* yes at the CLI) when `applyRequiresConfirm` is on (default).
|
|
920
|
-
*/
|
|
921
|
-
async apply(planId, opts) {
|
|
922
|
-
this.requireEnabled();
|
|
923
|
-
if (this.deps.applyRequiresConfirm() && opts.confirm !== true) {
|
|
924
|
-
throw new CorrectionContractError(
|
|
925
|
-
"Correction apply requires explicit confirmation (pass `confirm: true`)."
|
|
926
|
-
);
|
|
927
|
-
}
|
|
928
|
-
const namespace = await this.deps.policy.resolveAuthorizedNamespace({
|
|
929
|
-
...opts.namespace ? { namespace: opts.namespace } : {},
|
|
930
|
-
...opts.sessionKey ? { sessionKey: opts.sessionKey } : {},
|
|
931
|
-
...opts.principal ? { principal: opts.principal } : {}
|
|
932
|
-
});
|
|
933
|
-
return this.executor.apply(namespace, planId, {
|
|
934
|
-
confirm: true,
|
|
935
|
-
// Authorize rescope destinations through the namespace policy bound to
|
|
936
|
-
// THIS caller's principal (review thread: authorize-rescope-destination).
|
|
937
|
-
canWriteDestination: (dest) => this.deps.policy.canWriteNamespace({
|
|
938
|
-
namespace: dest,
|
|
939
|
-
...opts.sessionKey ? { sessionKey: opts.sessionKey } : {},
|
|
940
|
-
...opts.principal ? { principal: opts.principal } : {}
|
|
941
|
-
})
|
|
942
|
-
});
|
|
943
|
-
}
|
|
944
|
-
/** List pending (not-yet-applied) plans for the caller's namespace. */
|
|
945
|
-
async listPending(opts) {
|
|
946
|
-
this.requireEnabled();
|
|
947
|
-
const namespace = await this.deps.policy.resolveAuthorizedNamespace(opts);
|
|
948
|
-
return this.planner.listPending(namespace);
|
|
949
|
-
}
|
|
950
|
-
/** Discard a pending plan. Idempotent. */
|
|
951
|
-
async discard(planId, opts) {
|
|
952
|
-
this.requireEnabled();
|
|
953
|
-
const namespace = await this.deps.policy.resolveAuthorizedNamespace(opts);
|
|
954
|
-
await this.planner.markConsumed(namespace, planId, "discarded");
|
|
955
|
-
await this.planner.deletePlan(namespace, planId);
|
|
956
|
-
}
|
|
957
|
-
/**
|
|
958
|
-
* Recover stale `applying` plans across the given namespaces (#1713 Item 2).
|
|
959
|
-
*
|
|
960
|
-
* Startup maintenance: scans each namespace for plans stuck in `applying`
|
|
961
|
-
* past the stale-applying TTL (process died mid-apply) and discards+scrubs
|
|
962
|
-
* them. Unlike plan/apply/listPending, this is NOT a per-caller request —
|
|
963
|
-
* it operates on all supplied namespaces directly because it is an
|
|
964
|
-
* internal maintenance operation invoked by the orchestrator at init.
|
|
965
|
-
*
|
|
966
|
-
* @returns the total count of recovered plans across all namespaces.
|
|
967
|
-
*/
|
|
968
|
-
async recoverStaleApplyingPlans(namespaces) {
|
|
969
|
-
let recovered = 0;
|
|
970
|
-
for (const namespace of namespaces) {
|
|
971
|
-
try {
|
|
972
|
-
const ids = await this.planner.recoverStaleApplyingPlans(namespace);
|
|
973
|
-
recovered += ids.length;
|
|
974
|
-
} catch {
|
|
975
|
-
}
|
|
976
|
-
}
|
|
977
|
-
return recovered;
|
|
978
|
-
}
|
|
979
|
-
requireEnabled() {
|
|
980
|
-
if (!this.deps.isEnabled()) {
|
|
981
|
-
throw new CorrectionContractError(
|
|
982
|
-
"Correction Contract is disabled (set correction.enabled = true to enable)."
|
|
983
|
-
);
|
|
984
|
-
}
|
|
985
|
-
}
|
|
986
|
-
};
|
|
987
|
-
|
|
988
|
-
// src/correction/correction-access-wiring.ts
|
|
989
|
-
function createCorrectionService(wiring) {
|
|
990
|
-
const cfg = wiring.orchestrator.config;
|
|
991
|
-
const correctionEnabled = isCorrectionFeatureEnabled(cfg);
|
|
992
|
-
const applyRequiresConfirm = typeof cfg.correctionApplyRequiresConfirm === "boolean" ? cfg.correctionApplyRequiresConfirm : readCorrectionFlag(cfg, "applyRequiresConfirm", true);
|
|
993
|
-
const maxAffected = typeof cfg.correctionMaxAffected === "number" && cfg.correctionMaxAffected >= 1 ? Math.floor(cfg.correctionMaxAffected) : readCorrectionNumber(cfg, "maxAffected", 10);
|
|
994
|
-
const planTtlHours = typeof cfg.correctionPlanTtlHours === "number" && cfg.correctionPlanTtlHours > 0 ? cfg.correctionPlanTtlHours : readCorrectionNumber(cfg, "planTtlHours", 24);
|
|
995
|
-
const biTemporalEnabled = cfg.temporalBiTemporal === true;
|
|
996
|
-
const serviceDeps = {
|
|
997
|
-
policy: {
|
|
998
|
-
resolveAuthorizedNamespace: (req) => wiring.resolveAuthorizedNamespace(req),
|
|
999
|
-
canWriteNamespace: (req) => wiring.canWriteNamespace(req),
|
|
1000
|
-
readableNamespaces: (req) => Promise.resolve(wiring.resolveReadableNamespaces(req))
|
|
1001
|
-
},
|
|
1002
|
-
plannerDeps: () => makePlannerDeps(wiring, { maxAffected, planTtlHours }),
|
|
1003
|
-
executorDeps: () => makeExecutorDeps(wiring, { biTemporalEnabled }),
|
|
1004
|
-
isEnabled: () => correctionEnabled,
|
|
1005
|
-
applyRequiresConfirm: () => applyRequiresConfirm
|
|
1006
|
-
};
|
|
1007
|
-
return new CorrectionService(serviceDeps);
|
|
1008
|
-
}
|
|
1009
|
-
function makePlannerDeps(wiring, opts) {
|
|
1010
|
-
return {
|
|
1011
|
-
searchCorpus: async ({ text, namespaces, limit }) => searchMemories(wiring, text, namespaces, limit),
|
|
1012
|
-
resolveTargets: async ({ targetIds, namespaces }) => resolveTargetMemories(wiring, targetIds, namespaces),
|
|
1013
|
-
expandNeighbors: async ({ seedIds, namespaces, limit }) => expandEntityNeighbors(wiring, seedIds, namespaces, limit),
|
|
1014
|
-
classifyAndDraft: async ({ text, candidates }) => classifyAndDraft(wiring, text, candidates),
|
|
1015
|
-
renderDiff: async ({ candidates, actions }) => renderCorrectionDiff(wiring, candidates, actions),
|
|
1016
|
-
storageDir: async (namespace) => (await wiring.orchestrator.getStorage(namespace)).dir,
|
|
1017
|
-
maxAffected: opts.maxAffected,
|
|
1018
|
-
planTtlHours: opts.planTtlHours,
|
|
1019
|
-
now: () => /* @__PURE__ */ new Date()
|
|
1020
|
-
};
|
|
1021
|
-
}
|
|
1022
|
-
async function searchMemories(wiring, text, namespaces, limit) {
|
|
1023
|
-
const tokens = tokenize(text);
|
|
1024
|
-
if (tokens.length === 0) return [];
|
|
1025
|
-
const scored = [];
|
|
1026
|
-
for (const ns of namespaces) {
|
|
1027
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
1028
|
-
const all = await storage.readAllMemories();
|
|
1029
|
-
for (const m of all) {
|
|
1030
|
-
if (!isEligibleCorrectionCandidate(m)) continue;
|
|
1031
|
-
const hay = `${m.content} ${m.frontmatter.tags?.join(" ") ?? ""}`.toLowerCase();
|
|
1032
|
-
let hits = 0;
|
|
1033
|
-
for (const tok of tokens) {
|
|
1034
|
-
if (hay.includes(tok)) hits++;
|
|
1035
|
-
}
|
|
1036
|
-
if (hits === 0) continue;
|
|
1037
|
-
scored.push({ m, ns, score: hits / tokens.length });
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
scored.sort((a, b) => b.score - a.score);
|
|
1041
|
-
return scored.slice(0, limit).map((s, i) => toCandidate(s.m, s.ns, s.score - i * 0.01));
|
|
1042
|
-
}
|
|
1043
|
-
function tokenize(text) {
|
|
1044
|
-
const STOP = /* @__PURE__ */ new Set([
|
|
1045
|
-
"the",
|
|
1046
|
-
"a",
|
|
1047
|
-
"an",
|
|
1048
|
-
"is",
|
|
1049
|
-
"are",
|
|
1050
|
-
"was",
|
|
1051
|
-
"were",
|
|
1052
|
-
"be",
|
|
1053
|
-
"been",
|
|
1054
|
-
"being",
|
|
1055
|
-
"to",
|
|
1056
|
-
"of",
|
|
1057
|
-
"in",
|
|
1058
|
-
"on",
|
|
1059
|
-
"at",
|
|
1060
|
-
"by",
|
|
1061
|
-
"for",
|
|
1062
|
-
"with",
|
|
1063
|
-
"from",
|
|
1064
|
-
"into",
|
|
1065
|
-
"and",
|
|
1066
|
-
"or",
|
|
1067
|
-
"but",
|
|
1068
|
-
"not",
|
|
1069
|
-
"no",
|
|
1070
|
-
"yes",
|
|
1071
|
-
"this",
|
|
1072
|
-
"that",
|
|
1073
|
-
"these",
|
|
1074
|
-
"those",
|
|
1075
|
-
"it",
|
|
1076
|
-
"its",
|
|
1077
|
-
"we",
|
|
1078
|
-
"you",
|
|
1079
|
-
"i",
|
|
1080
|
-
"he",
|
|
1081
|
-
"she",
|
|
1082
|
-
"they",
|
|
1083
|
-
"them",
|
|
1084
|
-
"our",
|
|
1085
|
-
"your",
|
|
1086
|
-
"my",
|
|
1087
|
-
"his",
|
|
1088
|
-
"her",
|
|
1089
|
-
"their",
|
|
1090
|
-
"as",
|
|
1091
|
-
"so",
|
|
1092
|
-
"if",
|
|
1093
|
-
"then",
|
|
1094
|
-
"than",
|
|
1095
|
-
"too",
|
|
1096
|
-
"very",
|
|
1097
|
-
"can",
|
|
1098
|
-
"will",
|
|
1099
|
-
"just",
|
|
1100
|
-
"should",
|
|
1101
|
-
"now",
|
|
1102
|
-
"has",
|
|
1103
|
-
"have",
|
|
1104
|
-
"had",
|
|
1105
|
-
"do",
|
|
1106
|
-
"does",
|
|
1107
|
-
"did",
|
|
1108
|
-
"about",
|
|
1109
|
-
"which",
|
|
1110
|
-
"what",
|
|
1111
|
-
"who",
|
|
1112
|
-
"when",
|
|
1113
|
-
"where",
|
|
1114
|
-
"why",
|
|
1115
|
-
"how",
|
|
1116
|
-
"all",
|
|
1117
|
-
"each",
|
|
1118
|
-
"every",
|
|
1119
|
-
"both",
|
|
1120
|
-
"few",
|
|
1121
|
-
"more",
|
|
1122
|
-
"most",
|
|
1123
|
-
"other",
|
|
1124
|
-
"some",
|
|
1125
|
-
"such",
|
|
1126
|
-
"only",
|
|
1127
|
-
"own",
|
|
1128
|
-
"same",
|
|
1129
|
-
"up"
|
|
1130
|
-
]);
|
|
1131
|
-
const raw = text.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
1132
|
-
const out = raw.filter((w) => w.length >= 3 && !STOP.has(w));
|
|
1133
|
-
return [...new Set(out)];
|
|
1134
|
-
}
|
|
1135
|
-
async function resolveTargetMemories(wiring, targetIds, namespaces) {
|
|
1136
|
-
const out = [];
|
|
1137
|
-
const missing = [];
|
|
1138
|
-
for (const id of targetIds) {
|
|
1139
|
-
let found = null;
|
|
1140
|
-
for (const ns of namespaces) {
|
|
1141
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
1142
|
-
const m = await storage.getMemoryById(id);
|
|
1143
|
-
if (m) {
|
|
1144
|
-
found = toCandidate(m, ns, 1);
|
|
1145
|
-
break;
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
if (found) out.push(found);
|
|
1149
|
-
else missing.push(id);
|
|
1150
|
-
}
|
|
1151
|
-
if (missing.length > 0) {
|
|
1152
|
-
throw new CorrectionContractError(`target memory not found: ${missing[0]}`);
|
|
1153
|
-
}
|
|
1154
|
-
return out;
|
|
1155
|
-
}
|
|
1156
|
-
async function expandEntityNeighbors(wiring, seedIds, namespaces, limit) {
|
|
1157
|
-
if (seedIds.length === 0 || limit <= 0 || namespaces.length === 0) return [];
|
|
1158
|
-
const out = [];
|
|
1159
|
-
const seen = new Set(seedIds);
|
|
1160
|
-
const seedRefs = /* @__PURE__ */ new Set();
|
|
1161
|
-
for (const ns of namespaces) {
|
|
1162
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
1163
|
-
const all = await storage.readAllMemories();
|
|
1164
|
-
for (const m of all) {
|
|
1165
|
-
if (seedIds.includes(m.frontmatter.id) && m.frontmatter.entityRef) {
|
|
1166
|
-
seedRefs.add(m.frontmatter.entityRef);
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
if (seedRefs.size === 0) return [];
|
|
1171
|
-
for (const ns of namespaces) {
|
|
1172
|
-
if (out.length >= limit) break;
|
|
1173
|
-
const storage = await wiring.orchestrator.getStorage(ns);
|
|
1174
|
-
const all = await storage.readAllMemories();
|
|
1175
|
-
for (const m of all) {
|
|
1176
|
-
if (out.length >= limit) break;
|
|
1177
|
-
if (seen.has(m.frontmatter.id)) continue;
|
|
1178
|
-
if (!isEligibleCorrectionCandidate(m)) continue;
|
|
1179
|
-
if (m.frontmatter.entityRef && seedRefs.has(m.frontmatter.entityRef)) {
|
|
1180
|
-
out.push(toCandidate(m, ns, 0.5));
|
|
1181
|
-
seen.add(m.frontmatter.id);
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
}
|
|
1185
|
-
return out;
|
|
1186
|
-
}
|
|
1187
|
-
async function classifyAndDraft(wiring, text, candidates) {
|
|
1188
|
-
try {
|
|
1189
|
-
if (!wiring.llmComplete) {
|
|
1190
|
-
return fallbackClassification(candidates, "no LLM client available");
|
|
1191
|
-
}
|
|
1192
|
-
const user = buildClassifyPrompt(text, candidates);
|
|
1193
|
-
const raw = await wiring.llmComplete({ system: CLASSIFY_SYSTEM_PROMPT, user });
|
|
1194
|
-
return parseClassifyResponse(raw, candidates);
|
|
1195
|
-
} catch (err) {
|
|
1196
|
-
return fallbackClassification(candidates, `LLM unavailable: ${errMsg2(err)}`);
|
|
1197
|
-
}
|
|
1198
|
-
}
|
|
1199
|
-
async function renderCorrectionDiff(_wiring, candidates, actions) {
|
|
1200
|
-
const lines = [];
|
|
1201
|
-
for (const action of actions) {
|
|
1202
|
-
const id = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : null;
|
|
1203
|
-
const candidate = id ? candidates.find((c) => c.memoryId === id) : null;
|
|
1204
|
-
const before = candidate?.content ?? "(new)";
|
|
1205
|
-
const after = describeAfterState(action);
|
|
1206
|
-
lines.push(`--- ${id ?? "redaction-rule"} (${action.kind})`);
|
|
1207
|
-
lines.push(`- ${before.slice(0, 120)}`);
|
|
1208
|
-
lines.push(`+ ${after.slice(0, 120)}`);
|
|
1209
|
-
}
|
|
1210
|
-
return lines.join("\n");
|
|
1211
|
-
}
|
|
1212
|
-
function describeAfterState(action) {
|
|
1213
|
-
switch (action.kind) {
|
|
1214
|
-
case "supersede":
|
|
1215
|
-
return action.replacement?.content ?? "(superseded without replacement)";
|
|
1216
|
-
case "edit":
|
|
1217
|
-
return action.patch;
|
|
1218
|
-
case "retract":
|
|
1219
|
-
return "(retracted + tombstoned)";
|
|
1220
|
-
case "rescope":
|
|
1221
|
-
return `(moved to namespace '${action.toNamespace}')`;
|
|
1222
|
-
case "redaction_rule":
|
|
1223
|
-
return `(redaction rule persisted for pattern '${action.pattern}')`;
|
|
1224
|
-
}
|
|
1225
|
-
}
|
|
1226
|
-
function makeExecutorDeps(wiring, opts) {
|
|
1227
|
-
return {
|
|
1228
|
-
getMemory: async (namespace, memoryId) => getExecutorMemory(wiring, namespace, memoryId),
|
|
1229
|
-
writeReplacement: async (namespace, draft) => writeReplacementMemory(wiring, namespace, draft),
|
|
1230
|
-
applyEdit: async (namespace, memoryId, patch) => applyEditMemory(wiring, namespace, memoryId, patch),
|
|
1231
|
-
retireMemory: async (namespace, memoryId, retireOpts) => retireMemoryFn(wiring, namespace, memoryId, retireOpts),
|
|
1232
|
-
rescopeMemory: async (namespace, memoryId, toNamespace) => rescopeMemoryFn(wiring, namespace, memoryId, toNamespace),
|
|
1233
|
-
appendTombstone: async (namespace, input) => appendTombstoneFn(wiring, namespace, input),
|
|
1234
|
-
registerRedactionRule: async (namespace, pattern) => registerRedactionRuleFn(wiring, namespace, pattern),
|
|
1235
|
-
appendAuditRecord: async (namespace, record) => appendAuditRecordFn(wiring, namespace, record),
|
|
1236
|
-
propagate: async (namespace, touchedMemoryIds) => propagateFn(wiring, namespace, touchedMemoryIds),
|
|
1237
|
-
biTemporalEnabled: opts.biTemporalEnabled,
|
|
1238
|
-
now: () => /* @__PURE__ */ new Date()
|
|
1239
|
-
};
|
|
1240
|
-
}
|
|
1241
|
-
async function getExecutorMemory(wiring, namespace, memoryId) {
|
|
1242
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1243
|
-
const m = await storage.getMemoryById(memoryId);
|
|
1244
|
-
if (!m) return null;
|
|
1245
|
-
return toExecutorMemory(m);
|
|
1246
|
-
}
|
|
1247
|
-
async function writeReplacementMemory(wiring, namespace, draft) {
|
|
1248
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1249
|
-
const { id, tombstoneBlocked } = await storage.writeMemory(
|
|
1250
|
-
draft.category ?? "fact",
|
|
1251
|
-
draft.content,
|
|
1252
|
-
{
|
|
1253
|
-
source: "correction",
|
|
1254
|
-
confidence: draft.confidence ?? 0.9,
|
|
1255
|
-
tags: draft.tags ?? [],
|
|
1256
|
-
...draft.entityRef ? { entityRef: draft.entityRef } : {},
|
|
1257
|
-
...draft.validAt ? { validAt: draft.validAt } : {},
|
|
1258
|
-
...draft.observedAt ? { observedAt: draft.observedAt } : {},
|
|
1259
|
-
...draft.structuredAttributes ? { structuredAttributes: draft.structuredAttributes } : {},
|
|
1260
|
-
...draft.supersedes ? { supersedes: draft.supersedes } : {}
|
|
1261
|
-
}
|
|
1262
|
-
);
|
|
1263
|
-
if (tombstoneBlocked) {
|
|
1264
|
-
throw new CorrectionContractError(
|
|
1265
|
-
`correction replacement was tombstone-blocked (pending_review ${id}) \u2014 cannot supersede with a non-active replacement`
|
|
1266
|
-
);
|
|
1267
|
-
}
|
|
1268
|
-
return id;
|
|
1269
|
-
}
|
|
1270
|
-
async function applyEditMemory(wiring, namespace, memoryId, patch) {
|
|
1271
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1272
|
-
const existing = await storage.getMemoryById(memoryId);
|
|
1273
|
-
if (!existing) throw new CorrectionContractError(`memory not found for edit: ${memoryId}`);
|
|
1274
|
-
const contentHashForPatch = existing.frontmatter.category === "fact" ? computeContentHash(sanitizeMemoryContent(patch).text) : void 0;
|
|
1275
|
-
await storage.writeMemoryFrontmatter(
|
|
1276
|
-
{ ...existing, content: patch },
|
|
1277
|
-
{
|
|
1278
|
-
updated: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1279
|
-
...contentHashForPatch ? { contentHash: contentHashForPatch } : {}
|
|
1280
|
-
}
|
|
1281
|
-
);
|
|
1282
|
-
return memoryId;
|
|
1283
|
-
}
|
|
1284
|
-
async function retireMemoryFn(wiring, namespace, memoryId, opts) {
|
|
1285
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1286
|
-
const memory = await storage.getMemoryById(memoryId);
|
|
1287
|
-
if (!memory) throw new CorrectionContractError(`memory not found for retire: ${memoryId}`);
|
|
1288
|
-
const storageStatus = opts.status === "retracted" ? "forgotten" : "superseded";
|
|
1289
|
-
await storage.writeMemoryFrontmatter(memory, {
|
|
1290
|
-
status: storageStatus,
|
|
1291
|
-
...opts.supersededBy ? { supersededBy: opts.supersededBy } : {},
|
|
1292
|
-
...opts.status === "superseded" ? { supersededAt: (/* @__PURE__ */ new Date()).toISOString() } : {},
|
|
1293
|
-
// validUntil is the bi-temporal end; absent when the gate is off.
|
|
1294
|
-
...opts.validUntil ? { invalid_at: opts.validUntil } : {}
|
|
1295
|
-
});
|
|
1296
|
-
}
|
|
1297
|
-
async function rescopeMemoryFn(wiring, namespace, memoryId, toNamespace) {
|
|
1298
|
-
const sourceStorage = await wiring.orchestrator.getStorage(namespace);
|
|
1299
|
-
const memory = await sourceStorage.getMemoryById(memoryId);
|
|
1300
|
-
if (!memory) throw new CorrectionContractError(`memory not found for rescope: ${memoryId}`);
|
|
1301
|
-
if (memory.frontmatter.status && memory.frontmatter.status !== "active") {
|
|
1302
|
-
throw new CorrectionContractError(
|
|
1303
|
-
`cannot rescope memory ${memoryId}: source is ${memory.frontmatter.status}, not active`
|
|
1304
|
-
);
|
|
1305
|
-
}
|
|
1306
|
-
const destStorage = await wiring.orchestrator.getStorage(toNamespace);
|
|
1307
|
-
const fm = memory.frontmatter;
|
|
1308
|
-
const destContent = fm.structuredAttributes ? stripAttributesSuffix(memory.content) : memory.content;
|
|
1309
|
-
const { id: destId, tombstoneBlocked: destBlocked } = await destStorage.writeMemory(fm.category, destContent, {
|
|
1310
|
-
source: `correction:rescope:${namespace}`,
|
|
1311
|
-
...typeof fm.confidence === "number" ? { confidence: fm.confidence } : {},
|
|
1312
|
-
...Array.isArray(fm.tags) ? { tags: fm.tags } : {},
|
|
1313
|
-
...fm.entityRef ? { entityRef: fm.entityRef } : {},
|
|
1314
|
-
...fm.structuredAttributes ? { structuredAttributes: fm.structuredAttributes } : {},
|
|
1315
|
-
...fm.valid_at ? { validAt: fm.valid_at } : {},
|
|
1316
|
-
...fm.observedAt ? { observedAt: fm.observedAt } : {},
|
|
1317
|
-
...fm.memoryKind ? { memoryKind: fm.memoryKind } : {},
|
|
1318
|
-
...Array.isArray(fm.links) ? { links: fm.links } : {},
|
|
1319
|
-
...fm.intentGoal ? { intentGoal: fm.intentGoal } : {}
|
|
1320
|
-
});
|
|
1321
|
-
if (destBlocked) {
|
|
1322
|
-
throw new CorrectionContractError(
|
|
1323
|
-
`rescope of ${memoryId} into "${toNamespace}" was tombstone-blocked (pending_review ${destId}) \u2014 keeping source active`
|
|
1324
|
-
);
|
|
1325
|
-
}
|
|
1326
|
-
try {
|
|
1327
|
-
await sourceStorage.writeMemoryFrontmatter(memory, {
|
|
1328
|
-
status: "archived",
|
|
1329
|
-
archivedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1330
|
-
});
|
|
1331
|
-
} catch (err) {
|
|
1332
|
-
try {
|
|
1333
|
-
const destMem = await destStorage.getMemoryById(destId);
|
|
1334
|
-
if (destMem) {
|
|
1335
|
-
await destStorage.writeMemoryFrontmatter(destMem, {
|
|
1336
|
-
status: "archived",
|
|
1337
|
-
archivedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1338
|
-
});
|
|
1339
|
-
}
|
|
1340
|
-
} catch {
|
|
1341
|
-
}
|
|
1342
|
-
throw err;
|
|
1343
|
-
}
|
|
1344
|
-
return destId;
|
|
1345
|
-
}
|
|
1346
|
-
async function appendTombstoneFn(wiring, namespace, input) {
|
|
1347
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1348
|
-
const enabled = typeof storage.isTombstonesEnabled === "function" ? storage.isTombstonesEnabled() : true;
|
|
1349
|
-
const keys = input.supersessionKeys && input.supersessionKeys.length > 0 ? input.supersessionKeys : input.supersessionKey ? [input.supersessionKey] : [void 0];
|
|
1350
|
-
const writtenIds = [];
|
|
1351
|
-
let firstId = null;
|
|
1352
|
-
for (const key of keys) {
|
|
1353
|
-
const result = await storage.appendTombstone({
|
|
1354
|
-
reason: input.reason,
|
|
1355
|
-
createdBy: "user_correction",
|
|
1356
|
-
sourceMemoryId: input.sourceMemoryId,
|
|
1357
|
-
rawContent: input.rawContent,
|
|
1358
|
-
...input.entityRef ? { entityRef: input.entityRef } : {},
|
|
1359
|
-
...key ? { supersessionKey: key } : {},
|
|
1360
|
-
...input.contentHash ? { contentHash: input.contentHash } : {}
|
|
1361
|
-
});
|
|
1362
|
-
if (result === null && enabled) {
|
|
1363
|
-
for (const id of writtenIds) {
|
|
1364
|
-
try {
|
|
1365
|
-
await storage.revokeTombstone(id, "user_correction");
|
|
1366
|
-
} catch {
|
|
1367
|
-
}
|
|
1368
|
-
}
|
|
1369
|
-
throw new CorrectionContractError(
|
|
1370
|
-
`tombstone persistence failed for memory ${input.sourceMemoryId} (tombstones enabled but store returned null \u2014 I/O error swallowed)`
|
|
1371
|
-
);
|
|
1372
|
-
}
|
|
1373
|
-
if (firstId === null) firstId = result;
|
|
1374
|
-
if (result) writtenIds.push(result);
|
|
1375
|
-
}
|
|
1376
|
-
return firstId;
|
|
1377
|
-
}
|
|
1378
|
-
async function registerRedactionRuleFn(wiring, namespace, pattern) {
|
|
1379
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1380
|
-
const dir = path2.join(storage.dir, "state", "corrections", "redaction-rules");
|
|
1381
|
-
await mkdir2(dir, { recursive: true });
|
|
1382
|
-
const slugBase = pattern.replace(/[^a-zA-Z0-9]+/g, "-").slice(0, 48) || "rule";
|
|
1383
|
-
const patternHash = createHash("sha256").update(pattern).digest("hex").slice(0, 16);
|
|
1384
|
-
const slug = `${slugBase}-${patternHash}`;
|
|
1385
|
-
await writeFile2(
|
|
1386
|
-
path2.join(dir, `${slug}.json`),
|
|
1387
|
-
`${JSON.stringify({ pattern, namespace, createdAt: (/* @__PURE__ */ new Date()).toISOString() })}
|
|
1388
|
-
`,
|
|
1389
|
-
"utf-8"
|
|
1390
|
-
);
|
|
1391
|
-
}
|
|
1392
|
-
async function appendAuditRecordFn(wiring, namespace, record) {
|
|
1393
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1394
|
-
const { id } = await storage.writeMemory("correction", buildAuditBody(record), {
|
|
1395
|
-
source: "correction-contract",
|
|
1396
|
-
confidence: 1,
|
|
1397
|
-
tags: ["correction-audit", `plan:${record.planId}`, `classification:${record.classification}`]
|
|
1398
|
-
});
|
|
1399
|
-
return id;
|
|
1400
|
-
}
|
|
1401
|
-
function buildAuditBody(record) {
|
|
1402
|
-
const sensitive = record.classification === "never_store" || record.outcome.results.some((r) => r.action.kind === "redaction_rule");
|
|
1403
|
-
const safeRequest = sensitive ? "[redacted \u2014 never-store/redaction correction text withheld from the audit trail]" : record.requestText.slice(0, 200);
|
|
1404
|
-
const lines = [
|
|
1405
|
-
`Correction plan ${record.planId} applied (${record.outcome.status}).`,
|
|
1406
|
-
"",
|
|
1407
|
-
`Request: ${safeRequest}`,
|
|
1408
|
-
`Classification: ${record.classification}`,
|
|
1409
|
-
`Applied at: ${record.outcome.appliedAt}`,
|
|
1410
|
-
"",
|
|
1411
|
-
"Actions:"
|
|
1412
|
-
];
|
|
1413
|
-
for (const r of record.outcome.results) {
|
|
1414
|
-
const withhold = r.action.kind === "redaction_rule" || record.classification === "never_store";
|
|
1415
|
-
const errPart = r.error ? withhold ? " (error withheld)" : ` (${r.error})` : "";
|
|
1416
|
-
lines.push(` - ${r.action.kind}: ${r.status}${errPart}`);
|
|
1417
|
-
}
|
|
1418
|
-
return lines.join("\n");
|
|
1419
|
-
}
|
|
1420
|
-
async function propagateFn(wiring, namespace, touchedMemoryIds) {
|
|
1421
|
-
for (const id of touchedMemoryIds) {
|
|
1422
|
-
try {
|
|
1423
|
-
const storage = await wiring.orchestrator.getStorage(namespace);
|
|
1424
|
-
const orchestrator = wiring.orchestrator;
|
|
1425
|
-
if (typeof orchestrator.indexPersistedMemory === "function") {
|
|
1426
|
-
await orchestrator.indexPersistedMemory(storage, id);
|
|
1427
|
-
}
|
|
1428
|
-
} catch {
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
}
|
|
1432
|
-
function toCandidate(m, namespace, score) {
|
|
1433
|
-
return {
|
|
1434
|
-
memoryId: m.frontmatter.id,
|
|
1435
|
-
path: m.path,
|
|
1436
|
-
content: m.content,
|
|
1437
|
-
excerpt: m.content.slice(0, 160),
|
|
1438
|
-
...m.frontmatter.entityRef ? { entityRef: m.frontmatter.entityRef } : {},
|
|
1439
|
-
score
|
|
1440
|
-
// namespace is implicit (the planner scopes by namespace); keep it on the
|
|
1441
|
-
// candidate for diff rendering if needed.
|
|
1442
|
-
};
|
|
1443
|
-
}
|
|
1444
|
-
function isEligibleCorrectionCandidate(m) {
|
|
1445
|
-
if (m.frontmatter.status && m.frontmatter.status !== "active") return false;
|
|
1446
|
-
if (typeof m.frontmatter.archivedAt === "string" && m.frontmatter.archivedAt.length > 0) return false;
|
|
1447
|
-
return true;
|
|
1448
|
-
}
|
|
1449
|
-
function toExecutorMemory(m) {
|
|
1450
|
-
const fm = m.frontmatter;
|
|
1451
|
-
const rawBody = fm.structuredAttributes ? stripAttributesSuffix(m.content) : m.content;
|
|
1452
|
-
const supersessionKeys = supersessionKeysForFact({
|
|
1453
|
-
entityRef: fm.entityRef,
|
|
1454
|
-
structuredAttributes: fm.structuredAttributes
|
|
1455
|
-
});
|
|
1456
|
-
return {
|
|
1457
|
-
memoryId: fm.id,
|
|
1458
|
-
content: m.content,
|
|
1459
|
-
category: fm.category,
|
|
1460
|
-
rawContent: rawBody,
|
|
1461
|
-
...fm.entityRef ? { entityRef: fm.entityRef } : {},
|
|
1462
|
-
...supersessionKeys.length > 0 ? { supersessionKeys } : {},
|
|
1463
|
-
...supersessionKeys.length > 0 ? { supersessionKey: supersessionKeys[0] } : {},
|
|
1464
|
-
...typeof fm.contentHash === "string" && fm.contentHash.length > 0 ? { contentHash: fm.contentHash } : {}
|
|
1465
|
-
};
|
|
1466
|
-
}
|
|
1467
|
-
function isCorrectionFeatureEnabled(config) {
|
|
1468
|
-
if (typeof resolveRecallAuxiliaryCapabilities(config).correction === "boolean") return resolveRecallAuxiliaryCapabilities(config).correction;
|
|
1469
|
-
const nested = config.correction;
|
|
1470
|
-
if (nested && typeof nested.enabled === "boolean") return nested.enabled;
|
|
1471
|
-
if (nested && typeof nested.enabled === "string") return nested.enabled === "true" || nested.enabled === "1";
|
|
1472
|
-
return readCorrectionFlag(config, "enabled", true);
|
|
1473
|
-
}
|
|
1474
|
-
function readCorrectionFlag(config, key, fallback) {
|
|
1475
|
-
const nested = config.correction;
|
|
1476
|
-
if (nested && typeof nested[key] === "boolean") return nested[key];
|
|
1477
|
-
if (nested && typeof nested[key] === "string") return nested[key] === "true" || nested[key] === "1";
|
|
1478
|
-
const raw = config[`correction${capitalize(key)}`];
|
|
1479
|
-
if (typeof raw === "boolean") return raw;
|
|
1480
|
-
if (typeof raw === "string") return raw === "true" || raw === "1";
|
|
1481
|
-
return fallback;
|
|
1482
|
-
}
|
|
1483
|
-
function readCorrectionNumber(config, key, fallback) {
|
|
1484
|
-
const nested = config.correction;
|
|
1485
|
-
if (nested) {
|
|
1486
|
-
const nv = nested[key];
|
|
1487
|
-
if (typeof nv === "number" && Number.isFinite(nv)) return nv;
|
|
1488
|
-
if (typeof nv === "string") {
|
|
1489
|
-
const nn = Number(nv);
|
|
1490
|
-
if (Number.isFinite(nn)) return nn;
|
|
1491
|
-
}
|
|
1492
|
-
}
|
|
1493
|
-
const raw = config[`correction${capitalize(key)}`];
|
|
1494
|
-
if (typeof raw === "number" && Number.isFinite(raw)) return raw;
|
|
1495
|
-
if (typeof raw === "string") {
|
|
1496
|
-
const n = Number(raw);
|
|
1497
|
-
if (Number.isFinite(n)) return n;
|
|
1498
|
-
}
|
|
1499
|
-
return fallback;
|
|
1500
|
-
}
|
|
1501
|
-
function capitalize(s) {
|
|
1502
|
-
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
1503
|
-
}
|
|
1504
|
-
function errMsg2(err) {
|
|
1505
|
-
if (err instanceof Error) return err.message;
|
|
1506
|
-
return String(err);
|
|
1507
|
-
}
|
|
1508
|
-
var CLASSIFY_SYSTEM_PROMPT = `You classify memory corrections and draft per-memory actions.
|
|
1509
|
-
|
|
1510
|
-
Given a correction statement and candidate memories, respond with a JSON object:
|
|
1511
|
-
{
|
|
1512
|
-
"classification": "wrong" | "outdated" | "incomplete" | "wrong_scope" | "never_store",
|
|
1513
|
-
"confidence": <number 0..1>,
|
|
1514
|
-
"actions": [<one or more correction actions>],
|
|
1515
|
-
"relevance": [{"memoryId": "<id>", "why": "<one short sentence>"}]
|
|
1516
|
-
}
|
|
1517
|
-
|
|
1518
|
-
Action shapes:
|
|
1519
|
-
- {"kind":"supersede","loserId":"<id>","replacement":{"content":"<new fact>"}}
|
|
1520
|
-
- {"kind":"edit","memoryId":"<id>","patch":"<new full content>"}
|
|
1521
|
-
- {"kind":"retract","memoryId":"<id>"}
|
|
1522
|
-
- {"kind":"rescope","memoryId":"<id>","toNamespace":"<ns>"}
|
|
1523
|
-
- {"kind":"redaction_rule","pattern":"<bounded literal or regex>"}
|
|
1524
|
-
|
|
1525
|
-
Only emit actions you are confident in. If uncertain, return confidence < 0.5 and few actions.`;
|
|
1526
|
-
function buildClassifyPrompt(text, candidates) {
|
|
1527
|
-
const lines = [
|
|
1528
|
-
`Correction: ${text}`,
|
|
1529
|
-
"",
|
|
1530
|
-
"Candidate memories:"
|
|
1531
|
-
];
|
|
1532
|
-
for (const c of candidates.slice(0, 20)) {
|
|
1533
|
-
lines.push(`[${c.memoryId}] ${c.excerpt}`);
|
|
1534
|
-
}
|
|
1535
|
-
lines.push("", "Respond with the JSON object only.");
|
|
1536
|
-
return lines.join("\n");
|
|
1537
|
-
}
|
|
1538
|
-
function parseClassifyResponse(raw, candidates) {
|
|
1539
|
-
let parsed;
|
|
1540
|
-
try {
|
|
1541
|
-
parsed = JSON.parse(raw);
|
|
1542
|
-
} catch {
|
|
1543
|
-
return fallbackClassification(candidates, "LLM returned non-JSON response");
|
|
1544
|
-
}
|
|
1545
|
-
if (!parsed || typeof parsed !== "object") {
|
|
1546
|
-
return fallbackClassification(candidates, "LLM returned non-object response");
|
|
1547
|
-
}
|
|
1548
|
-
const obj = parsed;
|
|
1549
|
-
const classification = isClassification(obj.classification) ? obj.classification : "outdated";
|
|
1550
|
-
const confidence = typeof obj.confidence === "number" ? Math.min(1, Math.max(0, obj.confidence)) : 0.5;
|
|
1551
|
-
const rawActions = Array.isArray(obj.actions) ? obj.actions : [];
|
|
1552
|
-
const actions = [];
|
|
1553
|
-
const warnings = [];
|
|
1554
|
-
for (const rawAction of rawActions) {
|
|
1555
|
-
try {
|
|
1556
|
-
validateCorrectionAction(rawAction);
|
|
1557
|
-
actions.push(rawAction);
|
|
1558
|
-
} catch (err) {
|
|
1559
|
-
warnings.push(`dropped malformed action: ${errMsg2(err)}`);
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1562
|
-
const relevance = Array.isArray(obj.relevance) ? obj.relevance.filter((r) => !!r && typeof r === "object").map((r) => ({
|
|
1563
|
-
memoryId: typeof r.memoryId === "string" ? r.memoryId : "",
|
|
1564
|
-
why: typeof r.why === "string" ? r.why : ""
|
|
1565
|
-
})).filter((r) => r.memoryId.length > 0) : [];
|
|
1566
|
-
return {
|
|
1567
|
-
classification,
|
|
1568
|
-
confidence,
|
|
1569
|
-
actions,
|
|
1570
|
-
relevance,
|
|
1571
|
-
warnings
|
|
1572
|
-
};
|
|
1573
|
-
}
|
|
1574
|
-
function isClassification(value) {
|
|
1575
|
-
return value === "wrong" || value === "outdated" || value === "incomplete" || value === "wrong_scope" || value === "never_store";
|
|
1576
|
-
}
|
|
1577
|
-
function fallbackClassification(candidates, reason) {
|
|
1578
|
-
return {
|
|
1579
|
-
classification: "outdated",
|
|
1580
|
-
confidence: 0,
|
|
1581
|
-
actions: [],
|
|
1582
|
-
relevance: candidates.map((c) => ({ memoryId: c.memoryId, why: "located for review" })),
|
|
1583
|
-
warnings: [reason],
|
|
1584
|
-
fallback: true
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
|
|
1588
|
-
// src/correction/passive-correction-detector.ts
|
|
1589
|
-
var PATTERNS = [
|
|
1590
|
-
// ── update: new fact replaces / corrects an old one ──────────────────────
|
|
1591
|
-
{
|
|
1592
|
-
polarity: "update",
|
|
1593
|
-
// "actually, it's X not Y" / "actually we use X now"
|
|
1594
|
-
regex: /\bactually[,\s]+(?:it'?s|we|the|i|our|my|\[m:)/i,
|
|
1595
|
-
confidence: 0.85
|
|
1596
|
-
},
|
|
1597
|
-
{
|
|
1598
|
-
polarity: "update",
|
|
1599
|
-
// "we switched/switching/switched to X"
|
|
1600
|
-
regex: /\bwe\b\s*(?:(?:'re|'ve|are|have)\s+)?(?:switch(?:ed|ing)?|migrat(?:ed|ing)?|mov(?:ed|ing)?|chang(?:ed|ing)?)\s+(?:to|over to|from)\b/i,
|
|
1601
|
-
confidence: 0.9
|
|
1602
|
-
},
|
|
1603
|
-
{
|
|
1604
|
-
polarity: "update",
|
|
1605
|
-
// "we renamed X to Y" / "i renamed"
|
|
1606
|
-
regex: /\b(?:we|i)\s+renam(?:ed|ing)\b/i,
|
|
1607
|
-
confidence: 0.9
|
|
1608
|
-
},
|
|
1609
|
-
{
|
|
1610
|
-
polarity: "update",
|
|
1611
|
-
// "it's now X" / "the deadline moved to X" / "the date changed to X"
|
|
1612
|
-
regex: /\b(?:it'?s now|the\s+(?:deadline|date|meeting|standup|review)\s+(?:moved|chang(?:ed|ing))?\s*to)\b/i,
|
|
1613
|
-
confidence: 0.85
|
|
1614
|
-
},
|
|
1615
|
-
{
|
|
1616
|
-
polarity: "update",
|
|
1617
|
-
// "no, " at the start of a turn or clause — strong correction signal
|
|
1618
|
-
regex: /(?:^|\.\s+|\n)\s*no[,\s]+(?:we|i|it|the|our|my|that)\b/i,
|
|
1619
|
-
confidence: 0.8
|
|
1620
|
-
},
|
|
1621
|
-
{
|
|
1622
|
-
polarity: "update",
|
|
1623
|
-
// "no longer" / "not anymore" + an activity
|
|
1624
|
-
regex: /\b(?:no longer|not anymore)\b/i,
|
|
1625
|
-
confidence: 0.8
|
|
1626
|
-
},
|
|
1627
|
-
{
|
|
1628
|
-
polarity: "update",
|
|
1629
|
-
// Standalone "outdated" — catches "are both outdated", "is outdated", etc.
|
|
1630
|
-
regex: /\boutdated\b/i,
|
|
1631
|
-
confidence: 0.75
|
|
1632
|
-
},
|
|
1633
|
-
{
|
|
1634
|
-
polarity: "update",
|
|
1635
|
-
// "that's outdated" / "that's old"
|
|
1636
|
-
regex: /\bthat'?s\s+(?:outdated|old|no longer (?:true|correct|accurate))\b/i,
|
|
1637
|
-
confidence: 0.85
|
|
1638
|
-
},
|
|
1639
|
-
// ── retract: user says a fact is simply wrong ────────────────────────────
|
|
1640
|
-
{
|
|
1641
|
-
polarity: "retract",
|
|
1642
|
-
regex: /\bthat'?s\s+(?:wrong|not right|incorrect|not true|false)\b/i,
|
|
1643
|
-
confidence: 0.85
|
|
1644
|
-
},
|
|
1645
|
-
{
|
|
1646
|
-
polarity: "retract",
|
|
1647
|
-
// "we don't use X anymore" / "I don't use X anymore"
|
|
1648
|
-
regex: /\b(?:we|i)\s+don'?t\s+use\s+\S+\s+anymore\b/i,
|
|
1649
|
-
confidence: 0.9
|
|
1650
|
-
},
|
|
1651
|
-
{
|
|
1652
|
-
polarity: "retract",
|
|
1653
|
-
regex: /\bforget about\b/i,
|
|
1654
|
-
confidence: 0.8
|
|
1655
|
-
},
|
|
1656
|
-
// ── stop_storing: user wants the agent to stop a behavior ────────────────
|
|
1657
|
-
{
|
|
1658
|
-
polarity: "stop_storing",
|
|
1659
|
-
regex: /\bstop\s+(?:suggesting|bringing\s+up|recommending|reminding\s+me\s+(?:about)?)\b/i,
|
|
1660
|
-
confidence: 0.9
|
|
1661
|
-
},
|
|
1662
|
-
{
|
|
1663
|
-
polarity: "stop_storing",
|
|
1664
|
-
regex: /\b(?:don'?t|never)\s+(?:mention|suggest|recommend|store|bring\s+up)\b/i,
|
|
1665
|
-
confidence: 0.85
|
|
1666
|
-
}
|
|
1667
|
-
];
|
|
1668
|
-
var HYPOTHETICAL_REGEX = /\b(?:if\s+(?:we|you|i|they)\s+(?:ever|were|could|might|should|decide)|what\s+if|suppose|hypothetically|in\s+(?:theory|principle)|let'?s\s+say|imagine\s+if)\b/i;
|
|
1669
|
-
var THIRD_PARTY_REGEX = /\b(?:tell\s+\w+\s+(?:he|she|they|you)'?re?\s+wrong|he'?s\s+wrong\s+about|she'?s\s+wrong\s+about|they'?re\s+wrong\s+about|correct\s+\w+\s+on)\b/i;
|
|
1670
|
-
var TOOL_OUTPUT_REGEX = /\b(?:the\s+(?:output|result|response|error|log)|your\s+(?:output|result|response|code|answer))\s+(?:is\s+)?(?:wrong|incorrect|bad|off)\b/i;
|
|
1671
|
-
var SELF_RESOLVE_REGEX = /(?:actually|wait|no)[,\s]+(?:never\s*mind|forget\s*(?:that|it)|the\s+(?:original|first)\s+(?:was|is)\s+(?:right|correct)|scratch\s+that|disregard)/i;
|
|
1672
|
-
function extractHandles(text) {
|
|
1673
|
-
const matches = text.match(/\[m:[0-9a-fA-F]{4,}\]/g);
|
|
1674
|
-
return matches ?? [];
|
|
1675
|
-
}
|
|
1676
|
-
function extractTargetHint(text, match) {
|
|
1677
|
-
const matchStart = match.index ?? 0;
|
|
1678
|
-
const start = Math.max(0, matchStart - 20);
|
|
1679
|
-
const end = Math.min(text.length, matchStart + match[0].length + 60);
|
|
1680
|
-
const window = text.slice(start, end).replace(/\s+/g, " ").trim();
|
|
1681
|
-
return window.length > 80 ? window.slice(0, 77) + "..." : window;
|
|
1682
|
-
}
|
|
1683
|
-
function extractCorrectedAssertion(text, polarity) {
|
|
1684
|
-
if (polarity === "retract") return "";
|
|
1685
|
-
const trimmed = text.replace(/\s+/g, " ").trim();
|
|
1686
|
-
return trimmed.length > 200 ? trimmed.slice(0, 197) + "..." : trimmed;
|
|
1687
|
-
}
|
|
1688
|
-
function isWithinQuotes(text, matchIndex) {
|
|
1689
|
-
let inQuote = false;
|
|
1690
|
-
for (let i = 0; i < matchIndex && i < text.length; i++) {
|
|
1691
|
-
const c = text[i];
|
|
1692
|
-
if (c === '"' || c === "\u201C" || c === "\u201D") {
|
|
1693
|
-
inQuote = !inQuote;
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
return inQuote;
|
|
1697
|
-
}
|
|
1698
|
-
function detectAntiFixture(text) {
|
|
1699
|
-
if (SELF_RESOLVE_REGEX.test(text)) return "self_resolving";
|
|
1700
|
-
if (HYPOTHETICAL_REGEX.test(text)) return "hypothetical";
|
|
1701
|
-
if (THIRD_PARTY_REGEX.test(text)) return "third_party";
|
|
1702
|
-
if (TOOL_OUTPUT_REGEX.test(text)) return "tool_output";
|
|
1703
|
-
return null;
|
|
1704
|
-
}
|
|
1705
|
-
function detectPassiveCorrections(turns) {
|
|
1706
|
-
const results = [];
|
|
1707
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1708
|
-
for (let i = 0; i < turns.length; i++) {
|
|
1709
|
-
const turn = turns[i];
|
|
1710
|
-
if (turn.role !== "user") continue;
|
|
1711
|
-
const content = turn.content?.trim();
|
|
1712
|
-
if (!content) continue;
|
|
1713
|
-
const guard = detectAntiFixture(content);
|
|
1714
|
-
if (guard) continue;
|
|
1715
|
-
const handles = extractHandles(content);
|
|
1716
|
-
for (const pattern of PATTERNS) {
|
|
1717
|
-
const match = pattern.regex.exec(content);
|
|
1718
|
-
if (!match) continue;
|
|
1719
|
-
if (match.index !== void 0 && isWithinQuotes(content, match.index)) {
|
|
1720
|
-
continue;
|
|
1721
|
-
}
|
|
1722
|
-
const targetHint = extractTargetHint(content, match);
|
|
1723
|
-
const correctedAssertion = extractCorrectedAssertion(content, pattern.polarity);
|
|
1724
|
-
const dedupKey = `${i}:${targetHint}`;
|
|
1725
|
-
if (seen.has(dedupKey)) continue;
|
|
1726
|
-
seen.add(dedupKey);
|
|
1727
|
-
results.push({
|
|
1728
|
-
targetHint,
|
|
1729
|
-
correctedAssertion,
|
|
1730
|
-
polarity: pattern.polarity,
|
|
1731
|
-
handles,
|
|
1732
|
-
confidence: pattern.confidence,
|
|
1733
|
-
sourceExcerpt: content.slice(0, 200),
|
|
1734
|
-
turnIndex: i
|
|
1735
|
-
});
|
|
1736
|
-
}
|
|
1737
|
-
}
|
|
1738
|
-
return results;
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
// src/correction/passive-capture.ts
|
|
1742
|
-
function emptyTelemetry() {
|
|
1743
|
-
return { detected: 0, queued: 0, autoApplied: 0, suppressedReasons: {} };
|
|
1744
|
-
}
|
|
1745
|
-
function normalizeForFingerprint(text) {
|
|
1746
|
-
return text.toLowerCase().replace(/[^\w\s]/g, "").replace(/\s+/g, " ").trim().slice(0, 200);
|
|
1747
|
-
}
|
|
1748
|
-
function correctionFingerprint(bufferKey, correction) {
|
|
1749
|
-
return `${bufferKey}::${correction.polarity}::${normalizeForFingerprint(correction.targetHint)}`;
|
|
1750
|
-
}
|
|
1751
|
-
var AUTO_APPLICABLE_ACTION_KINDS = /* @__PURE__ */ new Set(["supersede", "edit", "retract"]);
|
|
1752
|
-
var AUTO_APPLICABLE_CLASSIFICATIONS = /* @__PURE__ */ new Set(["outdated", "wrong"]);
|
|
1753
|
-
function evaluateAutoApplyGuards(plan, config, isLiveSession) {
|
|
1754
|
-
if (!isLiveSession) return "non_live_session";
|
|
1755
|
-
if (plan.confidence < config.confidenceFloor) return "confidence_below_floor";
|
|
1756
|
-
if (!AUTO_APPLICABLE_CLASSIFICATIONS.has(plan.classification)) {
|
|
1757
|
-
return "classification_not_allowed";
|
|
1758
|
-
}
|
|
1759
|
-
if (plan.affected.length > config.autoApplyMaxAffected) {
|
|
1760
|
-
return "affected_too_large";
|
|
1761
|
-
}
|
|
1762
|
-
if (plan.actions.length === 0) {
|
|
1763
|
-
return "empty_plan";
|
|
1764
|
-
}
|
|
1765
|
-
for (const action of plan.actions) {
|
|
1766
|
-
if (!AUTO_APPLICABLE_ACTION_KINDS.has(action.kind)) {
|
|
1767
|
-
return "disallowed_action_kind";
|
|
1768
|
-
}
|
|
1769
|
-
}
|
|
1770
|
-
return null;
|
|
1771
|
-
}
|
|
1772
|
-
async function capturePassiveCorrections(corrections, ctx, config, deps, dedupState) {
|
|
1773
|
-
const telemetry = emptyTelemetry();
|
|
1774
|
-
const plans = [];
|
|
1775
|
-
telemetry.detected = corrections.length;
|
|
1776
|
-
for (const correction of corrections) {
|
|
1777
|
-
const fp = correctionFingerprint(ctx.bufferKey, correction);
|
|
1778
|
-
if (dedupState.has(fp)) {
|
|
1779
|
-
continue;
|
|
1780
|
-
}
|
|
1781
|
-
let targetIds;
|
|
1782
|
-
if (correction.handles.length > 0 && deps.resolveHandle && ctx.sessionKey) {
|
|
1783
|
-
const resolved = [];
|
|
1784
|
-
for (const handle of correction.handles) {
|
|
1785
|
-
const id = deps.resolveHandle(handle, ctx.sessionKey);
|
|
1786
|
-
if (id) resolved.push(id);
|
|
1787
|
-
}
|
|
1788
|
-
if (resolved.length > 0) targetIds = resolved;
|
|
1789
|
-
}
|
|
1790
|
-
const request = {
|
|
1791
|
-
text: correction.correctedAssertion || correction.sourceExcerpt,
|
|
1792
|
-
...targetIds ? { targetIds } : {},
|
|
1793
|
-
...ctx.sessionKey ? { sessionKey: ctx.sessionKey } : {},
|
|
1794
|
-
...ctx.principal ? { principal: ctx.principal } : {},
|
|
1795
|
-
namespace: ctx.namespace
|
|
1796
|
-
};
|
|
1797
|
-
let plan;
|
|
1798
|
-
try {
|
|
1799
|
-
plan = await deps.planCorrection(request);
|
|
1800
|
-
} catch (err) {
|
|
1801
|
-
log.warn(
|
|
1802
|
-
`passive-correction: planning failed for "${correction.targetHint.slice(0, 60)}": ${err instanceof Error ? err.message : String(err)}`
|
|
1803
|
-
);
|
|
1804
|
-
continue;
|
|
1805
|
-
}
|
|
1806
|
-
plans.push(plan);
|
|
1807
|
-
dedupState.add(fp);
|
|
1808
|
-
if (config.mode === "queue") {
|
|
1809
|
-
telemetry.queued += 1;
|
|
1810
|
-
continue;
|
|
1811
|
-
}
|
|
1812
|
-
const suppression = evaluateAutoApplyGuards(plan, config, ctx.isLiveSession);
|
|
1813
|
-
if (suppression) {
|
|
1814
|
-
telemetry.suppressedReasons[suppression] = (telemetry.suppressedReasons[suppression] ?? 0) + 1;
|
|
1815
|
-
telemetry.queued += 1;
|
|
1816
|
-
continue;
|
|
1817
|
-
}
|
|
1818
|
-
try {
|
|
1819
|
-
const outcome = await deps.applyCorrection(plan.planId, {
|
|
1820
|
-
confirm: true,
|
|
1821
|
-
namespace: ctx.namespace,
|
|
1822
|
-
...ctx.sessionKey ? { sessionKey: ctx.sessionKey } : {},
|
|
1823
|
-
...ctx.principal ? { principal: ctx.principal } : {}
|
|
1824
|
-
});
|
|
1825
|
-
if (outcome.status !== "applied") {
|
|
1826
|
-
log.warn(
|
|
1827
|
-
`passive-correction: plan ${plan.planId} applied partially \u2014 some actions failed (see audit record)`
|
|
1828
|
-
);
|
|
1829
|
-
continue;
|
|
1830
|
-
}
|
|
1831
|
-
telemetry.autoApplied += 1;
|
|
1832
|
-
try {
|
|
1833
|
-
const dir = await deps.storageDir(ctx.namespace);
|
|
1834
|
-
await enqueuePassiveCorrectionNotification(dir, {
|
|
1835
|
-
planId: plan.planId,
|
|
1836
|
-
summary: buildNotificationSummary(plan),
|
|
1837
|
-
undoCommand: `auto-applied (plan ${plan.planId})`,
|
|
1838
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1839
|
-
});
|
|
1840
|
-
} catch (err) {
|
|
1841
|
-
log.debug(`passive-correction: notification enqueue failed (non-fatal): ${err}`);
|
|
1842
|
-
}
|
|
1843
|
-
} catch (err) {
|
|
1844
|
-
log.warn(
|
|
1845
|
-
`passive-correction: auto-apply failed for plan ${plan.planId}: ${err instanceof Error ? err.message : String(err)} \u2014 plan left in queue`
|
|
1846
|
-
);
|
|
1847
|
-
telemetry.queued += 1;
|
|
1848
|
-
}
|
|
1849
|
-
}
|
|
1850
|
-
return { telemetry, plans };
|
|
1851
|
-
}
|
|
1852
|
-
function buildNotificationSummary(plan) {
|
|
1853
|
-
const action = plan.actions[0];
|
|
1854
|
-
if (!action) {
|
|
1855
|
-
return plan.request.text.slice(0, 80);
|
|
1856
|
-
}
|
|
1857
|
-
const target = action.kind === "supersede" ? action.loserId : action.kind === "edit" || action.kind === "retract" || action.kind === "rescope" ? action.memoryId : "pattern";
|
|
1858
|
-
return `${plan.classification}: ${plan.request.text.slice(0, 60)}${plan.request.text.length > 60 ? "..." : ""} (${target})`;
|
|
1859
|
-
}
|
|
1860
|
-
|
|
1861
|
-
// src/procedural/reinforcement-core.ts
|
|
1862
|
-
function clusterByKey(items, keyFn) {
|
|
1863
|
-
const clusters = /* @__PURE__ */ new Map();
|
|
1864
|
-
for (const item of items) {
|
|
1865
|
-
const key = keyFn(item);
|
|
1866
|
-
if (typeof key !== "string") {
|
|
1867
|
-
throw new TypeError(
|
|
1868
|
-
`clusterByKey: keyFn must return a string, got ${key === null ? "null" : typeof key}`
|
|
1869
|
-
);
|
|
1870
|
-
}
|
|
1871
|
-
const existing = clusters.get(key);
|
|
1872
|
-
if (existing) {
|
|
1873
|
-
existing.push(item);
|
|
1874
|
-
} else {
|
|
1875
|
-
clusters.set(key, [item]);
|
|
1876
|
-
}
|
|
1877
|
-
}
|
|
1878
|
-
return clusters;
|
|
1879
|
-
}
|
|
1880
|
-
|
|
1881
|
-
export {
|
|
1882
|
-
CorrectionContractError,
|
|
1883
|
-
createCorrectionService,
|
|
1884
|
-
isCorrectionFeatureEnabled,
|
|
1885
|
-
detectPassiveCorrections,
|
|
1886
|
-
capturePassiveCorrections,
|
|
1887
|
-
clusterByKey
|
|
1888
|
-
};
|
|
1889
|
-
//# sourceMappingURL=chunk-A2KKLCOS.js.map
|