pi-mega-compact 0.20.1 → 0.20.3

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.
Files changed (120) hide show
  1. package/dist/config/vector-cortex.js +26 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-plans.js +49 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-reconstruct.js +33 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex.js +2 -0
  7. package/dist/extensions/dashboard-server/routes.js +1 -1
  8. package/dist/extensions/dashboard-server/server.js +5 -1
  9. package/dist/src/config/vector-cortex.js +26 -0
  10. package/dist/src/config.js +1 -1
  11. package/dist/src/vector-cortex/planner/manifest.js +66 -0
  12. package/dist/src/vector-cortex/planner/portfolio.js +0 -0
  13. package/dist/src/vector-cortex/planner/types.js +41 -0
  14. package/dist/src/vector-cortex/prompt-dag/_acceptance-dag.js +347 -0
  15. package/dist/src/vector-cortex/prompt-dag/_acceptance-fixture.js +59 -0
  16. package/dist/src/vector-cortex/prompt-dag/_acceptance-helpers.js +17 -0
  17. package/dist/src/vector-cortex/prompt-dag/_acceptance-planner.js +153 -0
  18. package/dist/src/vector-cortex/prompt-dag/_acceptance-shuffle.js +24 -0
  19. package/dist/src/vector-cortex/prompt-dag/builder.js +171 -0
  20. package/dist/src/vector-cortex/prompt-dag/types.js +33 -0
  21. package/dist/src/vector-cortex/prompt-dag/validator.js +0 -0
  22. package/dist/src/vector-cortex/reconstruct/_acceptance-helpers.js +365 -0
  23. package/dist/src/vector-cortex/reconstruct/assemble.js +137 -0
  24. package/dist/src/vector-cortex/reconstruct/closure.js +268 -0
  25. package/dist/src/vector-cortex/reconstruct/types.js +46 -0
  26. package/dist/src/vector-cortex/reconstruct/validate.js +152 -0
  27. package/dist/vector-cortex/planner/manifest.js +66 -0
  28. package/dist/vector-cortex/planner/portfolio.js +0 -0
  29. package/dist/vector-cortex/planner/types.js +41 -0
  30. package/dist/vector-cortex/prompt-dag/_acceptance-dag.js +347 -0
  31. package/dist/vector-cortex/prompt-dag/_acceptance-fixture.js +59 -0
  32. package/dist/vector-cortex/prompt-dag/_acceptance-helpers.js +17 -0
  33. package/dist/vector-cortex/prompt-dag/_acceptance-planner.js +153 -0
  34. package/dist/vector-cortex/prompt-dag/_acceptance-shuffle.js +24 -0
  35. package/dist/vector-cortex/prompt-dag/builder.js +171 -0
  36. package/dist/vector-cortex/prompt-dag/types.js +33 -0
  37. package/dist/vector-cortex/prompt-dag/validator.js +0 -0
  38. package/dist/vector-cortex/reconstruct/_acceptance-helpers.js +365 -0
  39. package/dist/vector-cortex/reconstruct/assemble.js +137 -0
  40. package/dist/vector-cortex/reconstruct/closure.js +268 -0
  41. package/dist/vector-cortex/reconstruct/types.js +46 -0
  42. package/dist/vector-cortex/reconstruct/validate.js +152 -0
  43. package/extensions/dashboard-client/dist/assets/{AreaChart-n4z5w9Ox.js → AreaChart-Cam9-nhT.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{AreaChart-n4z5w9Ox.js.map → AreaChart-Cam9-nhT.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{BarChart-BLGjWWBr.js → BarChart-DzIY8aM1.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{BarChart-BLGjWWBr.js.map → BarChart-DzIY8aM1.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{CacheTab-CAnrKKVK.js → CacheTab-CKIiYsG_.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{CacheTab-CAnrKKVK.js.map → CacheTab-CKIiYsG_.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{EventsTab-D-GL7Ngq.js → EventsTab-xaaBJLiK.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{EventsTab-D-GL7Ngq.js.map → EventsTab-xaaBJLiK.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{HealthTab-C4x5qQ8s.js → HealthTab-BGtUKOqG.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{HealthTab-C4x5qQ8s.js.map → HealthTab-BGtUKOqG.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BSPs0eq5.js → MaintenanceTab-ABgQnTZ9.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BSPs0eq5.js.map → MaintenanceTab-ABgQnTZ9.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BWEUtTSu.js → MemoryMapTab-ChR2GAN-.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BWEUtTSu.js.map → MemoryMapTab-ChR2GAN-.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{MetricsTab-Dhm1c3Cx.js → MetricsTab-DdCLAgcR.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{MetricsTab-Dhm1c3Cx.js.map → MetricsTab-DdCLAgcR.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cm6cySiQ.js → OverviewTab-DtemzJt6.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cm6cySiQ.js.map → OverviewTab-DtemzJt6.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{ReposTab-DxLN1N4K.js → ReposTab-B9mvD9Ep.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{ReposTab-DxLN1N4K.js.map → ReposTab-B9mvD9Ep.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{SessionsTab-CZuI4ISW.js → SessionsTab-BcO38XLS.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{SessionsTab-CZuI4ISW.js.map → SessionsTab-BcO38XLS.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/{SetupTab-C_0VOomm.js → SetupTab-D_TBNP09.js} +2 -2
  66. package/extensions/dashboard-client/dist/assets/{SetupTab-C_0VOomm.js.map → SetupTab-D_TBNP09.js.map} +1 -1
  67. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BhbaRLmi.js → TimeSavedCard-TjHpbUOo.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BhbaRLmi.js.map → TimeSavedCard-TjHpbUOo.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJmbjje.js → TurnsTab-DprxndCF.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJmbjje.js.map → TurnsTab-DprxndCF.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/assets/VectorCortexTab-Bym21yVQ.js +2 -0
  72. package/extensions/dashboard-client/dist/assets/VectorCortexTab-Bym21yVQ.js.map +1 -0
  73. package/extensions/dashboard-client/dist/assets/{WikiTab-C5uvMCzp.js → WikiTab-OKgSo15G.js} +2 -2
  74. package/extensions/dashboard-client/dist/assets/{WikiTab-C5uvMCzp.js.map → WikiTab-OKgSo15G.js.map} +1 -1
  75. package/extensions/dashboard-client/dist/assets/{button-Cl_fxJcg.js → button-D_Qz4q7L.js} +2 -2
  76. package/extensions/dashboard-client/dist/assets/{button-Cl_fxJcg.js.map → button-D_Qz4q7L.js.map} +1 -1
  77. package/extensions/dashboard-client/dist/assets/{card-BH8Le5YM.js → card-CsI6Jm3p.js} +2 -2
  78. package/extensions/dashboard-client/dist/assets/{card-BH8Le5YM.js.map → card-CsI6Jm3p.js.map} +1 -1
  79. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-sZ6ZNtBi.js → generateCategoricalChart-CvHKUdhX.js} +2 -2
  80. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-sZ6ZNtBi.js.map → generateCategoricalChart-CvHKUdhX.js.map} +1 -1
  81. package/extensions/dashboard-client/dist/assets/{index-CX9zv8cJ.js → index-0Ye_un22.js} +3 -3
  82. package/extensions/dashboard-client/dist/assets/{index-CX9zv8cJ.js.map → index-0Ye_un22.js.map} +1 -1
  83. package/extensions/dashboard-client/dist/assets/{switch-CXJhcjhM.js → switch-VQEoJl8Q.js} +2 -2
  84. package/extensions/dashboard-client/dist/assets/{switch-CXJhcjhM.js.map → switch-VQEoJl8Q.js.map} +1 -1
  85. package/extensions/dashboard-client/dist/assets/{toggle-CoLtIc6y.js → toggle-CAPm4HJo.js} +2 -2
  86. package/extensions/dashboard-client/dist/assets/{toggle-CoLtIc6y.js.map → toggle-CAPm4HJo.js.map} +1 -1
  87. package/extensions/dashboard-client/dist/assets/{useSSE-fSXho606.js → useSSE-pxsNTVkh.js} +2 -2
  88. package/extensions/dashboard-client/dist/assets/{useSSE-fSXho606.js.map → useSSE-pxsNTVkh.js.map} +1 -1
  89. package/extensions/dashboard-client/dist/index.html +1 -1
  90. package/extensions/dashboard-client/src/api/vector-cortex.ts +18 -0
  91. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +72 -0
  92. package/extensions/dashboard-client/src/types/vector-cortex.ts +36 -0
  93. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +66 -0
  94. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
  95. package/extensions/dashboard-server/routes-vector-cortex-plans.ts +58 -0
  96. package/extensions/dashboard-server/routes-vector-cortex-reconstruct.ts +41 -0
  97. package/extensions/dashboard-server/routes-vector-cortex.ts +2 -0
  98. package/extensions/dashboard-server/routes.ts +2 -0
  99. package/extensions/dashboard-server/server.ts +4 -0
  100. package/package.json +1 -1
  101. package/src/config/vector-cortex.ts +28 -0
  102. package/src/config.ts +2 -0
  103. package/src/vector-cortex/planner/manifest.ts +83 -0
  104. package/src/vector-cortex/planner/portfolio.ts +0 -0
  105. package/src/vector-cortex/planner/types.ts +190 -0
  106. package/src/vector-cortex/prompt-dag/_acceptance-dag.ts +392 -0
  107. package/src/vector-cortex/prompt-dag/_acceptance-fixture.ts +132 -0
  108. package/src/vector-cortex/prompt-dag/_acceptance-helpers.ts +39 -0
  109. package/src/vector-cortex/prompt-dag/_acceptance-planner.ts +188 -0
  110. package/src/vector-cortex/prompt-dag/_acceptance-shuffle.ts +26 -0
  111. package/src/vector-cortex/prompt-dag/builder.ts +189 -0
  112. package/src/vector-cortex/prompt-dag/types.ts +151 -0
  113. package/src/vector-cortex/prompt-dag/validator.ts +0 -0
  114. package/src/vector-cortex/reconstruct/_acceptance-helpers.ts +455 -0
  115. package/src/vector-cortex/reconstruct/assemble.ts +170 -0
  116. package/src/vector-cortex/reconstruct/closure.ts +299 -0
  117. package/src/vector-cortex/reconstruct/types.ts +330 -0
  118. package/src/vector-cortex/reconstruct/validate.ts +184 -0
  119. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js +0 -2
  120. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js.map +0 -1
@@ -0,0 +1,299 @@
1
+ /**
2
+ * vector-cortex/reconstruct/closure.ts — mandatory conservative closure (VC4C).
3
+ *
4
+ * Task 2/3: a WORKLIST recursion that repeatedly adds every `depends`
5
+ * predecessor and every whole tool pair of an already-selected node until the
6
+ * selection stops growing (a FIXED POINT), tracking visited ids so a cyclic
7
+ * graph terminates instead of recursing forever. Task 3: contradictions are
8
+ * resolved by retaining the LATER exact source resolution; an explicit
9
+ * resolution event may name the loser directly; equal/unordered resolutions are
10
+ * an unresolved tie and return `CLO_CONTRADICTION_UNRESOLVED` so the candidate
11
+ * never goes live (CONTRACTS §plan and closure).
12
+ *
13
+ * Determinism: the worklist is drained in sorted id order and every returned
14
+ * array is sorted, so the closed set is identical regardless of the order seeds
15
+ * or edges were supplied in. Time is never read here — contradiction ordering
16
+ * uses the SOURCE `resolvedAtMs` fact carried on the node.
17
+ *
18
+ * OWNERSHIP: `mandatoryTokenEstimate` is CONTENT ONLY (no prompt framing) and is
19
+ * handed unchanged to VC5A, which owns framing + budget admission and returns
20
+ * `MANDATORY_CLOSURE_OVER_BUDGET` on overflow. Closure NEVER truncates a
21
+ * mandatory node.
22
+ *
23
+ * Pure/deterministic: no storage, no console, no network (PREVENT-PI-004 /
24
+ * PREVENT-011).
25
+ */
26
+
27
+ import type {
28
+ ClosureEdge,
29
+ ClosureFailureCode,
30
+ ClosureGraph,
31
+ ClosureNode,
32
+ ClosureProofStep,
33
+ ClosureResult,
34
+ } from "./types.js";
35
+
36
+ /** Sorted copy (bytewise id order) — every closure output is order-stable. */
37
+ function sortedIds(ids: Iterable<string>): string[] {
38
+ return [...ids].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
39
+ }
40
+
41
+ /** Index the graph's nodes by id (last wins is impossible — ids are unique). */
42
+ function indexNodes(graph: ClosureGraph): Map<string, ClosureNode> {
43
+ const byId = new Map<string, ClosureNode>();
44
+ for (const n of graph.nodes) byId.set(n.id, n);
45
+ return byId;
46
+ }
47
+
48
+ /**
49
+ * Build the "requirement" adjacency: for a selected node `x`, which nodes must
50
+ * ALSO be selected. Edges point prerequisite `from` → dependent `to`, so:
51
+ *
52
+ * - `depends` — selecting `to` requires `from` (walk BACKWARD to the
53
+ * prerequisite; this is the transitive dependency closure);
54
+ * - `tool-pair` — the pair is atomic, so selecting EITHER endpoint requires
55
+ * the other (walk BOTH directions — a pair is never split,
56
+ * PREVENT-PI-002).
57
+ *
58
+ * `contradicts` is deliberately absent: a contradiction never PULLS a node in,
59
+ * it removes one (resolved separately below).
60
+ */
61
+ function buildRequirements(
62
+ edges: readonly ClosureEdge[],
63
+ ): Map<string, Array<{ id: string; rule: "depends" | "tool-pair" }>> {
64
+ const req = new Map<string, Array<{ id: string; rule: "depends" | "tool-pair" }>>();
65
+ const add = (key: string, id: string, rule: "depends" | "tool-pair"): void => {
66
+ const list = req.get(key);
67
+ if (list === undefined) req.set(key, [{ id, rule }]);
68
+ else list.push({ id, rule });
69
+ };
70
+ for (const e of edges) {
71
+ if (e.kind === "depends") {
72
+ add(e.to, e.from, "depends");
73
+ continue;
74
+ }
75
+ if (e.kind === "tool-pair") {
76
+ add(e.to, e.from, "tool-pair");
77
+ add(e.from, e.to, "tool-pair");
78
+ }
79
+ }
80
+ return req;
81
+ }
82
+
83
+ /**
84
+ * Resolve one contradiction pair. Returns the loser id, or `null` when the pair
85
+ * is an unresolved tie.
86
+ *
87
+ * Precedence (CONTRACTS §plan and closure):
88
+ * 1. An explicit resolution event naming the loser wins outright.
89
+ * 2. Otherwise the LATER exact source resolution supersedes the earlier claim.
90
+ * "Exact" is required: a semantic node never supersedes an exact one, since
91
+ * semantic vectors never claim to recover exact text (RESIDUAL_CODEC).
92
+ * 3. Equal timestamps, missing timestamps, or two non-exact claims are
93
+ * UNORDERED — keep both and reject live use.
94
+ */
95
+ function resolveContradiction(
96
+ a: ClosureNode,
97
+ b: ClosureNode,
98
+ explicit: ReadonlyMap<string, string>,
99
+ ): string | null {
100
+ // 1. Explicit resolution event names the loser directly.
101
+ const aLoses = explicit.get(a.id);
102
+ if (aLoses === b.id) return a.id;
103
+ const bLoses = explicit.get(b.id);
104
+ if (bLoses === a.id) return b.id;
105
+
106
+ // 2. Later EXACT source resolution supersedes the earlier claim. Both sides
107
+ // must be exact and both must carry a source resolution time.
108
+ const aExact = a.kind === "exact";
109
+ const bExact = b.kind === "exact";
110
+ const aAt = a.resolvedAtMs;
111
+ const bAt = b.resolvedAtMs;
112
+ if (aExact && bExact && aAt !== undefined && bAt !== undefined && aAt !== bAt) {
113
+ return aAt < bAt ? a.id : b.id;
114
+ }
115
+
116
+ // 3. Equal / unordered / non-exact — unresolved tie.
117
+ return null;
118
+ }
119
+
120
+ /** Seeds for a closure run: the explicitly requested node ids. */
121
+ export interface ClosureInput {
122
+ readonly graph: ClosureGraph;
123
+ /** The initially requested node ids (the selection to close over). */
124
+ readonly seeds: readonly string[];
125
+ }
126
+
127
+ /**
128
+ * Close a selection conservatively to a fixed point (task 2 + 3).
129
+ *
130
+ * Algorithm: seed the worklist with the requested ids (plus the anchor floor,
131
+ * which is always mandatory), then repeatedly pop the smallest id and add every
132
+ * node it requires. A `visited` set makes each node expand exactly once, so a
133
+ * cycle (`a depends b`, `b depends a`) terminates at the fixed point rather than
134
+ * recursing forever. Contradictions among the CLOSED set are then resolved; an
135
+ * unresolved tie fails the closure.
136
+ */
137
+ export function closeSelection(input: ClosureInput): ClosureResult {
138
+ const { graph, seeds } = input;
139
+ const byId = indexNodes(graph);
140
+ const failures: ClosureFailureCode[] = [];
141
+
142
+ // Structural validation: every edge endpoint and every seed must exist.
143
+ for (const e of graph.edges) {
144
+ if (!byId.has(e.from) || !byId.has(e.to)) {
145
+ if (!failures.includes("CLO_MISSING_NODE")) failures.push("CLO_MISSING_NODE");
146
+ }
147
+ }
148
+ for (const s of seeds) {
149
+ if (!byId.has(s)) {
150
+ if (!failures.includes("CLO_UNKNOWN_SEED")) failures.push("CLO_UNKNOWN_SEED");
151
+ }
152
+ }
153
+ if (failures.length > 0) {
154
+ return {
155
+ ok: false,
156
+ selected: [],
157
+ addedDependencies: [],
158
+ removedContradictions: [],
159
+ unresolved: [],
160
+ proof: [],
161
+ failures,
162
+ mandatoryTokenEstimate: 0,
163
+ };
164
+ }
165
+
166
+ const requirements = buildRequirements(graph.edges);
167
+ const selected = new Set<string>();
168
+ const proof: ClosureProofStep[] = [];
169
+ const seedSet = new Set(seeds);
170
+
171
+ // The anchor floor is ALWAYS mandatory: an anchor is never dropped by closure
172
+ // (PREVENT-PI-001's anchor-floor discipline restated for the closed prompt).
173
+ const anchorIds = graph.nodes.filter((n) => n.anchor === true).map((n) => n.id);
174
+
175
+ // Seed the worklist deterministically (sorted), anchors after explicit seeds
176
+ // so the proof reads "what was asked for, then what the floor forced".
177
+ const worklist: string[] = [];
178
+ for (const id of sortedIds(seedSet)) {
179
+ if (selected.has(id)) continue;
180
+ selected.add(id);
181
+ proof.push({ added: id, rule: "seed" });
182
+ worklist.push(id);
183
+ }
184
+ for (const id of sortedIds(anchorIds)) {
185
+ if (selected.has(id)) continue;
186
+ selected.add(id);
187
+ proof.push({ added: id, rule: "anchor-floor" });
188
+ worklist.push(id);
189
+ }
190
+
191
+ // ── Worklist recursion to a FIXED POINT (visited = `selected`) ─────────────
192
+ // Each id is expanded at most once because it can only enter the worklist at
193
+ // the moment it is inserted into `selected`. A cyclic graph therefore
194
+ // terminates: the second traversal of the cycle finds every node already
195
+ // selected and adds nothing.
196
+ while (worklist.length > 0) {
197
+ // Drain in sorted order so the proof is deterministic across input orders.
198
+ worklist.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
199
+ const current = worklist.shift();
200
+ if (current === undefined) break;
201
+ const required = requirements.get(current) ?? [];
202
+ // Sort the requirements of one node so sibling additions are ordered too.
203
+ const ordered = [...required].sort((x, y) =>
204
+ x.id < y.id ? -1 : x.id > y.id ? 1 : x.rule < y.rule ? -1 : x.rule > y.rule ? 1 : 0,
205
+ );
206
+ for (const { id, rule } of ordered) {
207
+ if (selected.has(id)) continue; // already at the fixed point for this node
208
+ selected.add(id);
209
+ proof.push({ added: id, requiredBy: current, rule });
210
+ worklist.push(id);
211
+ }
212
+ }
213
+
214
+ // ── Contradiction resolution over the CLOSED set (task 3) ─────────────────
215
+ const explicit = new Map<string, string>();
216
+ for (const r of graph.resolutions ?? []) explicit.set(r.loserId, r.winnerId);
217
+
218
+ const removed = new Set<string>();
219
+ const unresolved = new Set<string>();
220
+ for (const e of graph.edges) {
221
+ if (e.kind !== "contradicts") continue;
222
+ // Only contradictions BETWEEN TWO SELECTED nodes matter: an unselected claim
223
+ // cannot contradict the prompt that is actually being built.
224
+ if (!selected.has(e.from) || !selected.has(e.to)) continue;
225
+ const a = byId.get(e.from);
226
+ const b = byId.get(e.to);
227
+ if (a === undefined || b === undefined) continue;
228
+ // A pair already decided by an earlier edge (duplicate contradiction) is
229
+ // skipped so one resolution is not re-litigated into a false tie.
230
+ if (removed.has(a.id) || removed.has(b.id)) continue;
231
+ const loser = resolveContradiction(a, b, explicit);
232
+ if (loser === null) {
233
+ unresolved.add(a.id);
234
+ unresolved.add(b.id);
235
+ continue;
236
+ }
237
+ removed.add(loser);
238
+ }
239
+
240
+ // A node that lost a contradiction leaves the selection. An unresolved tie
241
+ // keeps BOTH (CONTRACTS: "ties keep both and reject live use") and fails.
242
+ for (const id of removed) selected.delete(id);
243
+
244
+ const selectedIds = sortedIds(selected);
245
+ const addedDependencies = selectedIds.filter((id) => !seedSet.has(id));
246
+ const mandatoryTokenEstimate = selectedIds.reduce(
247
+ (sum, id) => sum + (byId.get(id)?.tokenEstimate ?? 0),
248
+ 0,
249
+ );
250
+
251
+ const ok = unresolved.size === 0;
252
+ return {
253
+ ok,
254
+ selected: selectedIds,
255
+ addedDependencies,
256
+ removedContradictions: sortedIds(removed),
257
+ unresolved: sortedIds(unresolved),
258
+ proof,
259
+ failures: ok ? [] : ["CLO_CONTRADICTION_UNRESOLVED"],
260
+ mandatoryTokenEstimate,
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Whether a closure result is a genuine fixed point: re-running the closure over
266
+ * its own output adds nothing. Used by the acceptance invariant ("closure reaches
267
+ * a fixed point") — an independent CHECK rather than a restatement of the loop.
268
+ */
269
+ export function isFixedPoint(graph: ClosureGraph, result: ClosureResult): boolean {
270
+ if (!result.ok) return true; // a rejected closure is not required to be closed
271
+ const again = closeSelection({ graph, seeds: result.selected });
272
+ if (!again.ok) return false;
273
+ return (
274
+ again.selected.length === result.selected.length &&
275
+ again.selected.every((id, i) => id === result.selected[i])
276
+ );
277
+ }
278
+
279
+ /**
280
+ * Mode B: a GREEDY EXACT-ONLY closure, forced when semantic validation fails.
281
+ * Independent of mode A by construction — it consults no semantic node and no
282
+ * semantic index, deriving purely from the exact/event source tiers
283
+ * (TRIAD_RESILIENCE: A/B must not share the same algorithm or index).
284
+ */
285
+ export function closeExactOnly(input: ClosureInput): ClosureResult {
286
+ const exactGraph: ClosureGraph = {
287
+ sessionId: input.graph.sessionId,
288
+ nodes: input.graph.nodes.filter((n) => n.kind !== "semantic"),
289
+ edges: input.graph.edges.filter((e) => {
290
+ const kinds = new Map(input.graph.nodes.map((n) => [n.id, n.kind]));
291
+ return kinds.get(e.from) !== "semantic" && kinds.get(e.to) !== "semantic";
292
+ }),
293
+ resolutions: input.graph.resolutions,
294
+ };
295
+ const seeds = input.seeds.filter((id) =>
296
+ exactGraph.nodes.some((n) => n.id === id),
297
+ );
298
+ return closeSelection({ graph: exactGraph, seeds });
299
+ }
@@ -0,0 +1,330 @@
1
+ /**
2
+ * vector-cortex/reconstruct/types.ts — conservative closure + reconstruction
3
+ * fidelity contract (VC4C).
4
+ *
5
+ * Owns `ClosureResult` / `ReconstructionV1` — the contract of the sprint failure
6
+ * triad:
7
+ *
8
+ * A = closed semantic + exact/residual reconstruction (the normal path);
9
+ * B = greedy EXACT-only closure, forced when semantic validation fails;
10
+ * C = legacy prompt, forced by an unresolved contradiction (states its loss of
11
+ * old semantic context — TRIAD_RESILIENCE: C is continuity, NOT semantic
12
+ * completeness).
13
+ *
14
+ * Closure is MANDATORY before VC5 (CONTRACTS §plan and closure): recursively add
15
+ * every `depends`/tool-pair predecessor until a fixed point; for contradictions
16
+ * keep the LATER exact source resolution unless an explicit resolution event
17
+ * names the loser; ties keep both and reject live use
18
+ * (`CLO_CONTRADICTION_UNRESOLVED`). The anchor floor is preserved, and the closed
19
+ * mandatory node set is returned with its deterministic token estimate.
20
+ *
21
+ * OWNERSHIP BOUNDARY (CONTRACTS §plan and closure): `mandatoryTokenEstimate`
22
+ * counts CONTENT ONLY — no prompt framing, no role tags, no separators, no
23
+ * budget admission. VC5A exclusively owns framing/budget: it adds framing cost
24
+ * to this estimate and returns `MANDATORY_CLOSURE_OVER_BUDGET` if the mandatory
25
+ * cost exceeds its `tokenBudget`. VC4C therefore NEVER truncates a mandatory
26
+ * node and never reasons about a budget.
27
+ *
28
+ * Consumes only reviewer-accepted predecessor contracts (VC1A `EventV2` byte
29
+ * authority, VC4A `ShardRange`/`ExactShardV1`, VC4B `ParityShardV1` residual
30
+ * decode) and the common contracts. Pure types + registered conformance IDs: no
31
+ * storage, no console, no network (PREVENT-PI-004 / PREVENT-011).
32
+ */
33
+
34
+ import type { ShardRange } from "../shards/types.js";
35
+
36
+ /**
37
+ * The kind of a closure graph node, mirroring `DagNode.kind`
38
+ * (CONTRACTS §PromptDagV1). `exact` nodes carry authoritative source bytes;
39
+ * `semantic` nodes are derived and never claim to recover exact text;
40
+ * `synthetic` nodes have no source span and order after their prerequisites.
41
+ */
42
+ export type ClosureNodeKind = "event" | "exact" | "semantic" | "synthetic";
43
+
44
+ /**
45
+ * One node in the closure graph. `span` is the half-open source byte range this
46
+ * node occupies (absent for `synthetic` nodes, which have no source position).
47
+ * `anchor` marks a node inside the preserved anchor floor — closure preserves it
48
+ * and the validator rejects a reconstruction that drops it (PREVENT-PI-001's
49
+ * anchor-floor discipline, restated for the closed prompt).
50
+ *
51
+ * `resolvedAtMs` is the source resolution TIME used only for contradiction
52
+ * ordering: the LATER exact resolution wins. It is a source fact (the event's
53
+ * `occurredAtMs`), never a wall clock read at closure time — closure is pure and
54
+ * deterministic (TRIAD_RESILIENCE: wall time for records, never for eligibility).
55
+ */
56
+ export interface ClosureNode {
57
+ readonly id: string;
58
+ readonly kind: ClosureNodeKind;
59
+ /** Source span; absent only for `synthetic` nodes. */
60
+ readonly span?: ShardRange;
61
+ /** True when the node belongs to the preserved anchor floor. */
62
+ readonly anchor?: boolean;
63
+ /**
64
+ * Source resolution time for contradiction ordering (from the source event,
65
+ * never `Date.now()`). Two contradicting nodes with EQUAL or ABSENT
66
+ * resolutions are an unresolved tie.
67
+ */
68
+ readonly resolvedAtMs?: bigint;
69
+ /**
70
+ * Deterministic CONTENT token estimate for this node (no framing). Summed into
71
+ * `ClosureResult.mandatoryTokenEstimate` and handed unchanged to VC5A.
72
+ */
73
+ readonly tokenEstimate: number;
74
+ }
75
+
76
+ /**
77
+ * One directed closure edge. Edges point prerequisite/earlier **from →
78
+ * dependent/later to** (CONTRACTS §PromptDagV1).
79
+ *
80
+ * - `depends` — `to` requires `from`; closure pulls `from` in transitively;
81
+ * - `tool-pair` — a tool call/result pair that must be selected WHOLE (never
82
+ * split at a compaction boundary — PREVENT-PI-002);
83
+ * - `contradicts` — mutually exclusive claims; the later exact resolution wins.
84
+ */
85
+ export type ClosureEdgeKind = "depends" | "tool-pair" | "contradicts";
86
+
87
+ /** A directed closure edge (`from` is the prerequisite/earlier endpoint). */
88
+ export interface ClosureEdge {
89
+ readonly from: string;
90
+ readonly to: string;
91
+ readonly kind: ClosureEdgeKind;
92
+ }
93
+
94
+ /**
95
+ * An explicit resolution event that names the LOSER of a contradiction
96
+ * (CONTRACTS §plan and closure: "keep the later exact source unless an explicit
97
+ * resolution event names the loser"). An explicit resolution therefore
98
+ * OVERRIDES the later-wins time rule and breaks what would otherwise be a tie.
99
+ */
100
+ export interface ContradictionResolution {
101
+ /** The node id explicitly superseded (dropped from the closure). */
102
+ readonly loserId: string;
103
+ /** The node id that survives. */
104
+ readonly winnerId: string;
105
+ }
106
+
107
+ /** The closure graph handed to `closeSelection`. */
108
+ export interface ClosureGraph {
109
+ readonly sessionId: string;
110
+ readonly nodes: readonly ClosureNode[];
111
+ readonly edges: readonly ClosureEdge[];
112
+ /** Explicit resolutions naming contradiction losers (may be empty). */
113
+ readonly resolutions?: readonly ContradictionResolution[];
114
+ }
115
+
116
+ /**
117
+ * A single recorded closure step — the PROOF that the fixed point was reached by
118
+ * a defensible derivation rather than asserted. Each step names the node added
119
+ * and the edge/rule that forced it.
120
+ */
121
+ export interface ClosureProofStep {
122
+ /** The node id added by this step. */
123
+ readonly added: string;
124
+ /** The already-selected node that required it (absent for a seed). */
125
+ readonly requiredBy?: string;
126
+ /** Why it was added. */
127
+ readonly rule: "seed" | "depends" | "tool-pair" | "anchor-floor";
128
+ }
129
+
130
+ /** Closure failure codes (registered CLO codes). */
131
+ export type ClosureFailureCode =
132
+ /** A contradiction whose resolutions are equal/unordered — reject live use. */
133
+ | "CLO_CONTRADICTION_UNRESOLVED"
134
+ /** An edge names a node id that is not in the graph. */
135
+ | "CLO_MISSING_NODE"
136
+ /** A seed id is not in the graph. */
137
+ | "CLO_UNKNOWN_SEED";
138
+
139
+ /**
140
+ * The closed mandatory node set (CONTRACTS §plan and closure). `ok:false` means
141
+ * the closure is NOT live-usable and the adapter demotes (C on an unresolved
142
+ * contradiction).
143
+ *
144
+ * `selected` is the fixed point: every seed plus every transitively required
145
+ * dependency and whole tool pair, sorted deterministically by node id so the
146
+ * result is stable across input permutations. `mandatoryTokenEstimate` is the
147
+ * CONTENT-ONLY sum handed UNCHANGED to VC5A (which adds framing and owns budget
148
+ * admission — VC4C never truncates a mandatory node).
149
+ */
150
+ export interface ClosureResult {
151
+ readonly ok: boolean;
152
+ /** The closed selection (sorted by node id). */
153
+ readonly selected: readonly string[];
154
+ /** Dependencies/tool-pair members pulled in beyond the seeds (sorted). */
155
+ readonly addedDependencies: readonly string[];
156
+ /** Contradiction losers removed by the later-exact / explicit rule (sorted). */
157
+ readonly removedContradictions: readonly string[];
158
+ /** Contradictions that could not be resolved (sorted) — reject live use. */
159
+ readonly unresolved: readonly string[];
160
+ /** Ordered derivation proof of the fixed point. */
161
+ readonly proof: readonly ClosureProofStep[];
162
+ /** Failure codes; empty when `ok`. */
163
+ readonly failures: readonly ClosureFailureCode[];
164
+ /**
165
+ * Deterministic CONTENT-ONLY token estimate of the closed mandatory set.
166
+ * Contains NO prompt framing (VC5A adds that and owns budget admission).
167
+ */
168
+ readonly mandatoryTokenEstimate: number;
169
+ }
170
+
171
+ /**
172
+ * One assembled span of the reconstruction. `bytes` are the authoritative source
173
+ * bytes for `range` — either verbatim exact-shard bytes (`source:"exact"`), a
174
+ * byte-exact residual decode (`source:"residual"`), or a derived semantic
175
+ * rendering that NEVER claims to be the exact text (`source:"semantic"`).
176
+ * `protectedSpan` marks a span the validator requires to be present and exact.
177
+ */
178
+ export interface ReconstructionSpan {
179
+ readonly nodeId: string;
180
+ readonly range: ShardRange;
181
+ readonly source: "exact" | "residual" | "semantic";
182
+ readonly bytes: Uint8Array;
183
+ /** SHA-256 of `bytes`, lowercase hex (no `sha256:` prefix). */
184
+ readonly digest: string;
185
+ /** True when this span must survive verbatim (tool pair / anchor / invalid UTF-8). */
186
+ readonly protectedSpan: boolean;
187
+ }
188
+
189
+ /**
190
+ * The assembled reconstruction (VC4C's outbound contract to VC5A). Spans are
191
+ * ordered SOLELY by source range (`byteStart`, then `seqStart`, then node id for
192
+ * a total order) — never by selection order, map iteration, or scoring, so the
193
+ * assembly is deterministic and replayable. `digest` is one SHA-256 over the
194
+ * ordered span digests plus their ranges.
195
+ */
196
+ export interface ReconstructionV1 {
197
+ readonly schema: "reconstruction-v1";
198
+ readonly sessionId: string;
199
+ /** Spans in source order (the concatenation order). */
200
+ readonly spans: readonly ReconstructionSpan[];
201
+ /** Deterministic digest over the ordered spans. */
202
+ readonly digest: string;
203
+ /** Total assembled byte count. */
204
+ readonly byteTotal: number;
205
+ /**
206
+ * CONTENT-ONLY mandatory token estimate, carried UNCHANGED from the closure so
207
+ * VC5A receives exactly the number VC4C computed (no framing, no budget).
208
+ */
209
+ readonly mandatoryTokenEstimate: number;
210
+ }
211
+
212
+ /** Reconstruction/validation failure codes (registered REC codes). */
213
+ export type ReconstructionFailureCode =
214
+ /** A required source shard is missing AND its residual fallback failed. */
215
+ | "REC_SOURCE_UNAVAILABLE"
216
+ /** A protected anchor span is absent from the reconstruction. */
217
+ | "REC_ANCHOR_MISSING"
218
+ /** A tool call/result pair was split (PREVENT-PI-002). */
219
+ | "REC_TOOL_PAIR_SPLIT"
220
+ /** A span's bytes do not hash to its recorded digest. */
221
+ | "REC_DIGEST_MISMATCH"
222
+ /** The closure carried an unresolved contradiction — never goes live. */
223
+ | "REC_CONTRADICTION_UNRESOLVED"
224
+ /** Two assembled spans overlap in the source byte stream. */
225
+ | "REC_SPAN_OVERLAP";
226
+
227
+ /**
228
+ * Validation verdict. Reader-facing surface is SUMMARY + CODES ONLY — never span
229
+ * bytes, never prompt text (SECURITY_PRIVACY: the exact ledger is not training
230
+ * data and is never rendered through a diagnostic surface).
231
+ */
232
+ export type ReconstructionValidation =
233
+ | { readonly ok: true; readonly summary: ReconstructionSummary }
234
+ | { readonly ok: false; readonly codes: readonly ReconstructionFailureCode[] };
235
+
236
+ /**
237
+ * Aggregate-only reconstruction summary exposed to the dashboard. Counts, byte
238
+ * totals and the digest identity — NEVER payload bytes or prompt text.
239
+ */
240
+ export interface ReconstructionSummary {
241
+ readonly sessionId: string;
242
+ readonly spanCount: number;
243
+ readonly protectedSpanCount: number;
244
+ readonly byteTotal: number;
245
+ readonly mandatoryTokenEstimate: number;
246
+ readonly digest: string;
247
+ /** Per-source span counts (exact / residual / semantic). */
248
+ readonly bySource: {
249
+ readonly exact: number;
250
+ readonly residual: number;
251
+ readonly semantic: number;
252
+ };
253
+ }
254
+
255
+ /** The two structured events the VC4C reporter emits. */
256
+ export type ReconstructEventName =
257
+ | "vector_cortex_reconstruction_validated"
258
+ | "vector_cortex_closure_rejected";
259
+
260
+ /** Injected emit callback — same (event, fields) shape as the other VC seams. */
261
+ export type ReconstructEmitter = (
262
+ event: ReconstructEventName,
263
+ fields: Record<string, unknown>,
264
+ ) => void;
265
+
266
+ /** Typed, best-effort reporter bound to the two reconstruction event names. */
267
+ export interface ReconstructReporter {
268
+ readonly reconstructionValidated: (fields: Record<string, unknown>) => void;
269
+ readonly closureRejected: (fields: Record<string, unknown>) => void;
270
+ }
271
+
272
+ /**
273
+ * Aggregate-only reconstruction metrics for the dashboard (counts/bytes only).
274
+ */
275
+ export interface ReconstructMetricsV1 {
276
+ readonly closureAttempts: number;
277
+ readonly closureRejections: number;
278
+ readonly validatedCount: number;
279
+ readonly invalidatedCount: number;
280
+ readonly spanTotal: number;
281
+ readonly byteTotal: number;
282
+ }
283
+
284
+ /**
285
+ * The triad mode VC4C selects (TRIAD_RESILIENCE). A/B/C use INDEPENDENT
286
+ * algorithms: A closes over semantic+exact/residual; B is a greedy EXACT-only
287
+ * closure that shares no semantic index with A; C abandons the closed prompt
288
+ * entirely and returns the legacy transcript, stating its semantic loss.
289
+ */
290
+ export type ReconstructMode = "A" | "B" | "C";
291
+
292
+ /**
293
+ * The outcome of the triad selection: the mode taken, the validated
294
+ * reconstruction (A/B) and the reason C was forced, if it was.
295
+ */
296
+ export interface ReconstructTriadOutcome {
297
+ readonly mode: ReconstructMode;
298
+ readonly reconstruction: ReconstructionV1 | null;
299
+ readonly codes: readonly ReconstructionFailureCode[];
300
+ /**
301
+ * Set only in mode C: the explicit statement that old semantic context is lost
302
+ * (TRIAD_RESILIENCE — "C states its loss of old semantic context").
303
+ */
304
+ readonly semanticLossStated: boolean;
305
+ }
306
+
307
+ /**
308
+ * Registered CLO conformance ID range (CLO-001..030). The acceptance test reads
309
+ * these rows from the v2 manifest and asserts each returns its manifest
310
+ * `ok`/`code`.
311
+ */
312
+ export const CLO_IDS: readonly string[] = Array.from(
313
+ { length: 30 },
314
+ (_v, i) => `CLO-${String(i + 1).padStart(3, "0")}`,
315
+ );
316
+
317
+ /** Registered REC conformance ID range (REC-001..030). */
318
+ export const REC_IDS: readonly string[] = Array.from(
319
+ { length: 30 },
320
+ (_v, i) => `REC-${String(i + 1).padStart(3, "0")}`,
321
+ );
322
+
323
+ /** Named VC4C conformance assertions (the sprint's headline rows). */
324
+ export const RECONSTRUCT_NAMED_IDS = [
325
+ "CLO-TRANSITIVE-001",
326
+ "CLO-CONTRA-002",
327
+ "REC-ORDER-003",
328
+ ] as const;
329
+
330
+ export type { ShardRange };