pi-mega-compact 0.20.1 → 0.20.2

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 (85) hide show
  1. package/dist/config/vector-cortex.js +13 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +1 -0
  4. package/dist/extensions/dashboard-server/routes-vector-cortex-reconstruct.js +33 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex.js +1 -0
  6. package/dist/extensions/dashboard-server/routes.js +1 -1
  7. package/dist/extensions/dashboard-server/server.js +3 -1
  8. package/dist/src/config/vector-cortex.js +13 -0
  9. package/dist/src/config.js +1 -1
  10. package/dist/src/vector-cortex/reconstruct/_acceptance-helpers.js +365 -0
  11. package/dist/src/vector-cortex/reconstruct/assemble.js +137 -0
  12. package/dist/src/vector-cortex/reconstruct/closure.js +268 -0
  13. package/dist/src/vector-cortex/reconstruct/types.js +46 -0
  14. package/dist/src/vector-cortex/reconstruct/validate.js +152 -0
  15. package/dist/vector-cortex/reconstruct/_acceptance-helpers.js +365 -0
  16. package/dist/vector-cortex/reconstruct/assemble.js +137 -0
  17. package/dist/vector-cortex/reconstruct/closure.js +268 -0
  18. package/dist/vector-cortex/reconstruct/types.js +46 -0
  19. package/dist/vector-cortex/reconstruct/validate.js +152 -0
  20. package/extensions/dashboard-client/dist/assets/{AreaChart-n4z5w9Ox.js → AreaChart-XF3jPpvn.js} +2 -2
  21. package/extensions/dashboard-client/dist/assets/{AreaChart-n4z5w9Ox.js.map → AreaChart-XF3jPpvn.js.map} +1 -1
  22. package/extensions/dashboard-client/dist/assets/{BarChart-BLGjWWBr.js → BarChart-DnYYn0GF.js} +2 -2
  23. package/extensions/dashboard-client/dist/assets/{BarChart-BLGjWWBr.js.map → BarChart-DnYYn0GF.js.map} +1 -1
  24. package/extensions/dashboard-client/dist/assets/{CacheTab-CAnrKKVK.js → CacheTab-D3bVskCL.js} +2 -2
  25. package/extensions/dashboard-client/dist/assets/{CacheTab-CAnrKKVK.js.map → CacheTab-D3bVskCL.js.map} +1 -1
  26. package/extensions/dashboard-client/dist/assets/{EventsTab-D-GL7Ngq.js → EventsTab-CX_8myfc.js} +2 -2
  27. package/extensions/dashboard-client/dist/assets/{EventsTab-D-GL7Ngq.js.map → EventsTab-CX_8myfc.js.map} +1 -1
  28. package/extensions/dashboard-client/dist/assets/{HealthTab-C4x5qQ8s.js → HealthTab-CnVzBQvN.js} +2 -2
  29. package/extensions/dashboard-client/dist/assets/{HealthTab-C4x5qQ8s.js.map → HealthTab-CnVzBQvN.js.map} +1 -1
  30. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BSPs0eq5.js → MaintenanceTab-Cao--dtV.js} +2 -2
  31. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-BSPs0eq5.js.map → MaintenanceTab-Cao--dtV.js.map} +1 -1
  32. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BWEUtTSu.js → MemoryMapTab-DZdI-9ig.js} +2 -2
  33. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BWEUtTSu.js.map → MemoryMapTab-DZdI-9ig.js.map} +1 -1
  34. package/extensions/dashboard-client/dist/assets/{MetricsTab-Dhm1c3Cx.js → MetricsTab-SlpSmNU4.js} +2 -2
  35. package/extensions/dashboard-client/dist/assets/{MetricsTab-Dhm1c3Cx.js.map → MetricsTab-SlpSmNU4.js.map} +1 -1
  36. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cm6cySiQ.js → OverviewTab-C_-_4au9.js} +2 -2
  37. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cm6cySiQ.js.map → OverviewTab-C_-_4au9.js.map} +1 -1
  38. package/extensions/dashboard-client/dist/assets/{ReposTab-DxLN1N4K.js → ReposTab-CyWedWZC.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{ReposTab-DxLN1N4K.js.map → ReposTab-CyWedWZC.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{SessionsTab-CZuI4ISW.js → SessionsTab-wqPBMIJZ.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{SessionsTab-CZuI4ISW.js.map → SessionsTab-wqPBMIJZ.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{SetupTab-C_0VOomm.js → SetupTab-MojXmuUf.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{SetupTab-C_0VOomm.js.map → SetupTab-MojXmuUf.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BhbaRLmi.js → TimeSavedCard-BxcplEOJ.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-BhbaRLmi.js.map → TimeSavedCard-BxcplEOJ.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJmbjje.js → TurnsTab-D8_qWbjY.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{TurnsTab-CXJmbjje.js.map → TurnsTab-D8_qWbjY.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/VectorCortexTab-B3yisAyB.js +2 -0
  49. package/extensions/dashboard-client/dist/assets/VectorCortexTab-B3yisAyB.js.map +1 -0
  50. package/extensions/dashboard-client/dist/assets/{WikiTab-C5uvMCzp.js → WikiTab-Cfd-QZYz.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{WikiTab-C5uvMCzp.js.map → WikiTab-Cfd-QZYz.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{button-Cl_fxJcg.js → button-tX5ht0bb.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{button-Cl_fxJcg.js.map → button-tX5ht0bb.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/{card-BH8Le5YM.js → card-BT3Z5dDg.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{card-BH8Le5YM.js.map → card-BT3Z5dDg.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-sZ6ZNtBi.js → generateCategoricalChart-B6p2WnkY.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-sZ6ZNtBi.js.map → generateCategoricalChart-B6p2WnkY.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{index-CX9zv8cJ.js → index-CFLekP12.js} +3 -3
  59. package/extensions/dashboard-client/dist/assets/{index-CX9zv8cJ.js.map → index-CFLekP12.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{switch-CXJhcjhM.js → switch-B52oAMSw.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{switch-CXJhcjhM.js.map → switch-B52oAMSw.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{toggle-CoLtIc6y.js → toggle-VxxVc5Tp.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{toggle-CoLtIc6y.js.map → toggle-VxxVc5Tp.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{useSSE-fSXho606.js → useSSE-DAVdZnG7.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{useSSE-fSXho606.js.map → useSSE-DAVdZnG7.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/index.html +1 -1
  67. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  68. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +37 -0
  69. package/extensions/dashboard-client/src/types/vector-cortex.ts +16 -0
  70. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +28 -0
  71. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +6 -0
  72. package/extensions/dashboard-server/routes-vector-cortex-reconstruct.ts +41 -0
  73. package/extensions/dashboard-server/routes-vector-cortex.ts +1 -0
  74. package/extensions/dashboard-server/routes.ts +1 -0
  75. package/extensions/dashboard-server/server.ts +2 -0
  76. package/package.json +1 -1
  77. package/src/config/vector-cortex.ts +14 -0
  78. package/src/config.ts +1 -0
  79. package/src/vector-cortex/reconstruct/_acceptance-helpers.ts +455 -0
  80. package/src/vector-cortex/reconstruct/assemble.ts +170 -0
  81. package/src/vector-cortex/reconstruct/closure.ts +299 -0
  82. package/src/vector-cortex/reconstruct/types.ts +330 -0
  83. package/src/vector-cortex/reconstruct/validate.ts +184 -0
  84. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js +0 -2
  85. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js.map +0 -1
@@ -0,0 +1,170 @@
1
+ /**
2
+ * vector-cortex/reconstruct/assemble.ts — source-order assembly (VC4C).
3
+ *
4
+ * Task 4: given a CLOSED + VALIDATED selection, decode the relevant shards,
5
+ * insert protected exact bytes unchanged, then lay the spans out SOLELY by their
6
+ * source range (`ShardRange`) before concatenation — never by closure order,
7
+ * which carries no positional meaning. The deterministic content-only
8
+ * `mandatoryTokenEstimate` from the closure is carried through UNCHANGED to VC5A
9
+ * (VC5A owns framing + budget admission).
10
+ *
11
+ * OWNERSHIP BOUNDARY (CONTRACTS plan + TRIAD_RESILIENCE): assemble produces the
12
+ * raw, ordered, content-only reconstruction. It does NOT frame it, does NOT
13
+ * admit against a budget, and NEVER truncates a mandatory node. Any byte/order
14
+ * error produces a hard rejection (REC_SPAN_OVERLAP / REC_TOOL_PAIR_SPLIT)
15
+ * because a corrupted layout must never reach a live prompt.
16
+ *
17
+ * Determinism: sorting is bytewise on (sessionId, seqStart, byteStart). The
18
+ * output digest is over the CONCATENATED BYTES so any reorder is itself detected
19
+ * downstream (RESIDUAL_CODEC admission parity).
20
+ *
21
+ * Pure/deterministic: no storage, no console, no network.
22
+ */
23
+
24
+ import type { ShardRange } from "../shards/types.js";
25
+ import type {
26
+ ClosureEdge,
27
+ ClosureNode,
28
+ ReconstructionFailureCode,
29
+ ReconstructionSpan,
30
+ ReconstructionV1,
31
+ } from "./types.js";
32
+
33
+ /** A decode result the caller supplies; assemble stays secret-free about format. */
34
+ export interface DecodedShard {
35
+ readonly nodeId: string;
36
+ readonly range: ShardRange;
37
+ readonly bytes: Uint8Array;
38
+ readonly source: "exact" | "residual" | "semantic";
39
+ readonly digest: string;
40
+ readonly protectedSpan: boolean;
41
+ }
42
+
43
+ /** SHA-256 hex of an arbitrary byte array (Web Crypto; no network, no deps). */
44
+ async function sha256Hex(bytes: Uint8Array): Promise<string> {
45
+ const buf = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
46
+ const digest = await crypto.subtle.digest("SHA-256", buf);
47
+ const out = new Uint8Array(digest);
48
+ return Array.from(out, (b) => b.toString(16).padStart(2, "0")).join("");
49
+ }
50
+
51
+ /** Stable source-order comparator: (sessionId, seqStart, byteStart). */
52
+ function bySourceOrder(a: { range: ShardRange }, b: { range: ShardRange }): number {
53
+ if (a.range.sessionId !== b.range.sessionId) {
54
+ return a.range.sessionId < b.range.sessionId ? -1 : 1;
55
+ }
56
+ if (a.range.seqStart !== b.range.seqStart) {
57
+ return a.range.seqStart < b.range.seqStart ? -1 : 1;
58
+ }
59
+ return a.range.byteStart - b.range.byteStart;
60
+ }
61
+
62
+ /**
63
+ * Detect a hard layout failure BEFORE concatenation:
64
+ * - REC_SPAN_OVERLAP: two spans intersect in the source byte space.
65
+ * - REC_TOOL_PAIR_SPLIT: a node bound by a tool-pair edge must be adjacent to
66
+ * its partner (end of one == start of the other) in source order
67
+ * (PREVENT-PI-002 restated at assembly time — a toolCall/toolResult pair is
68
+ * never split across a gap).
69
+ * Returns the first failure code found, or null when the layout is clean.
70
+ */
71
+ function detectLayoutFailure(
72
+ spans: readonly ReconstructionSpan[],
73
+ nodes: readonly ClosureNode[],
74
+ edges: readonly ClosureEdge[],
75
+ ): ReconstructionFailureCode | null {
76
+ const ordered = [...spans].sort(bySourceOrder);
77
+ for (let i = 1; i < ordered.length; i++) {
78
+ const prev = ordered[i - 1].range;
79
+ const cur = ordered[i].range;
80
+ const prevEnd = prev.byteEnd; // half-open: [byteStart, byteEnd)
81
+ if (cur.byteStart < prevEnd) return "REC_SPAN_OVERLAP";
82
+ }
83
+
84
+ // Tool-pair adjacency: every tool-pair edge names two partners that must be
85
+ // immediately adjacent in source order. We check each edge once.
86
+ const rangeById = new Map(spans.map((s) => [s.nodeId, s.range] as const));
87
+ const inOrder = new Map(ordered.map((s) => [s.nodeId, s.range] as const));
88
+ const seenEdges = new Set<string>();
89
+ for (const e of edges) {
90
+ if (e.kind !== "tool-pair") continue;
91
+ const key = e.from < e.to ? `${e.from}|${e.to}` : `${e.to}|${e.from}`;
92
+ if (seenEdges.has(key)) continue;
93
+ seenEdges.add(key);
94
+ // Both endpoints must be present in the selection to be a split concern.
95
+ const a = rangeById.get(e.from);
96
+ const b = rangeById.get(e.to);
97
+ if (a === undefined || b === undefined) continue;
98
+ const aEnd = a.byteEnd;
99
+ const bEnd = b.byteEnd;
100
+ const adjacent = aEnd === b.byteStart || bEnd === a.byteStart;
101
+ if (!adjacent) return "REC_TOOL_PAIR_SPLIT";
102
+ }
103
+ // `nodes` kept in the signature for call symmetry with the composed validator;
104
+ // it is the authoritative kind source but not needed for these two checks.
105
+ void nodes;
106
+ void inOrder;
107
+ return null;
108
+ }
109
+
110
+ /**
111
+ * Assemble a closed+validated selection into source order (task 4).
112
+ *
113
+ * `shards` must be EXACTLY one `DecodedShard` per node id in `selected` — the
114
+ * caller (validate.ts) guarantees availability. A missing shard is therefore a
115
+ * programming error surfaced as REC_SOURCE_UNAVAILABLE, never a silent gap.
116
+ */
117
+ export async function assembleSourceOrder(args: {
118
+ readonly sessionId: string;
119
+ readonly selected: readonly string[];
120
+ readonly nodes: readonly ClosureNode[];
121
+ readonly edges: readonly ClosureEdge[];
122
+ readonly shards: readonly DecodedShard[];
123
+ readonly mandatoryTokenEstimate: number;
124
+ }): Promise<{ readonly reconstruction: ReconstructionV1 | null; readonly code: ReconstructionFailureCode | null }> {
125
+ const { sessionId, selected, nodes, edges, mandatoryTokenEstimate } = args;
126
+ const shardById = new Map(args.shards.map((s) => [s.nodeId, s] as const));
127
+
128
+ // Every selected node MUST have a decoded shard; a missing one is the unique
129
+ // failure-injection path (erase a dependency shard -> REC_SOURCE_UNAVAILABLE).
130
+ for (const id of selected) {
131
+ if (!shardById.has(id)) return { reconstruction: null, code: "REC_SOURCE_UNAVAILABLE" };
132
+ }
133
+
134
+ const spans: ReconstructionSpan[] = selected.map((id) => {
135
+ const s = shardById.get(id)!;
136
+ return {
137
+ nodeId: s.nodeId,
138
+ range: s.range,
139
+ source: s.source,
140
+ bytes: s.bytes,
141
+ digest: s.digest,
142
+ protectedSpan: s.protectedSpan,
143
+ };
144
+ });
145
+
146
+ const layoutFailure = detectLayoutFailure(spans, nodes, edges);
147
+ if (layoutFailure !== null) return { reconstruction: null, code: layoutFailure };
148
+
149
+ const ordered = [...spans].sort(bySourceOrder);
150
+ const byteTotal = ordered.reduce((sum, s) => sum + s.bytes.length, 0);
151
+ const concatenated = new Uint8Array(byteTotal);
152
+ let offset = 0;
153
+ for (const s of ordered) {
154
+ concatenated.set(s.bytes, offset);
155
+ offset += s.bytes.length;
156
+ }
157
+ const digest = await sha256Hex(concatenated);
158
+
159
+ return {
160
+ reconstruction: {
161
+ schema: "reconstruction-v1",
162
+ sessionId,
163
+ spans: ordered,
164
+ digest,
165
+ byteTotal,
166
+ mandatoryTokenEstimate,
167
+ },
168
+ code: null,
169
+ };
170
+ }
@@ -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
+ }