pi-mega-compact 0.20.8 → 0.20.10

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 (115) hide show
  1. package/dist/config/vector-cortex.js +29 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/route-dispatch.js +8 -1
  4. package/dist/extensions/dashboard-server/routes-rag-settings-vector-cortex.js +2 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-heal.js +42 -3
  6. package/dist/extensions/dashboard-server/routes-vector-cortex-repair.js +63 -0
  7. package/dist/extensions/dashboard-server/routes-vector-cortex.js +3 -1
  8. package/dist/extensions/dashboard-server/routes.js +1 -1
  9. package/dist/src/config/vector-cortex.js +29 -0
  10. package/dist/src/config.js +1 -1
  11. package/dist/src/vector-cortex/heal/_repair-fixture.js +70 -0
  12. package/dist/src/vector-cortex/heal/_restore-fixture.js +96 -0
  13. package/dist/src/vector-cortex/heal/_vc6b-helpers.js +35 -0
  14. package/dist/src/vector-cortex/heal/controller.js +165 -0
  15. package/dist/src/vector-cortex/heal/rebuild.js +136 -0
  16. package/dist/src/vector-cortex/heal/repair-emit.js +83 -0
  17. package/dist/src/vector-cortex/heal/repair-types.js +74 -0
  18. package/dist/src/vector-cortex/heal/restore-emit.js +70 -0
  19. package/dist/src/vector-cortex/heal/restore-readers.js +114 -0
  20. package/dist/src/vector-cortex/heal/restore-types.js +66 -0
  21. package/dist/src/vector-cortex/heal/restore.js +140 -0
  22. package/dist/src/vector-cortex/heal/types.js +2 -0
  23. package/dist/src/vector-cortex/heal/verify.js +75 -0
  24. package/dist/vector-cortex/heal/_repair-fixture.js +70 -0
  25. package/dist/vector-cortex/heal/_restore-fixture.js +96 -0
  26. package/dist/vector-cortex/heal/_vc6b-helpers.js +35 -0
  27. package/dist/vector-cortex/heal/controller.js +165 -0
  28. package/dist/vector-cortex/heal/rebuild.js +136 -0
  29. package/dist/vector-cortex/heal/repair-emit.js +83 -0
  30. package/dist/vector-cortex/heal/repair-types.js +74 -0
  31. package/dist/vector-cortex/heal/restore-emit.js +70 -0
  32. package/dist/vector-cortex/heal/restore-readers.js +114 -0
  33. package/dist/vector-cortex/heal/restore-types.js +66 -0
  34. package/dist/vector-cortex/heal/restore.js +140 -0
  35. package/dist/vector-cortex/heal/types.js +2 -0
  36. package/dist/vector-cortex/heal/verify.js +75 -0
  37. package/extensions/dashboard-client/dist/assets/{AreaChart-5yxaI8IO.js → AreaChart-BDMjyRQp.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{AreaChart-5yxaI8IO.js.map → AreaChart-BDMjyRQp.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/{BarChart-BoHhCqH-.js → BarChart-CqzPzOkj.js} +2 -2
  40. package/extensions/dashboard-client/dist/assets/{BarChart-BoHhCqH-.js.map → BarChart-CqzPzOkj.js.map} +1 -1
  41. package/extensions/dashboard-client/dist/assets/{CacheTab-Di6L3CsF.js → CacheTab-Bo8SH9q8.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{CacheTab-Di6L3CsF.js.map → CacheTab-Bo8SH9q8.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/{EventsTab-Cdff3h6s.js → EventsTab-DIEs6zC-.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{EventsTab-Cdff3h6s.js.map → EventsTab-DIEs6zC-.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/{HealthTab-MthYYVLw.js → HealthTab-3a8IjwIK.js} +2 -2
  46. package/extensions/dashboard-client/dist/assets/{HealthTab-MthYYVLw.js.map → HealthTab-3a8IjwIK.js.map} +1 -1
  47. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-D9G4ntsG.js → MaintenanceTab-CdKwAcXo.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-D9G4ntsG.js.map → MaintenanceTab-CdKwAcXo.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-CN8Lr5Qf.js → MemoryMapTab-D2hHuNj-.js} +2 -2
  50. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-CN8Lr5Qf.js.map → MemoryMapTab-D2hHuNj-.js.map} +1 -1
  51. package/extensions/dashboard-client/dist/assets/{MetricsTab-CgO32kSo.js → MetricsTab-CFhIhqrr.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{MetricsTab-CgO32kSo.js.map → MetricsTab-CFhIhqrr.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cb4kR0h1.js → OverviewTab-Dzp5ZoiA.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{OverviewTab-Cb4kR0h1.js.map → OverviewTab-Dzp5ZoiA.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/{ReposTab-Dt1FGnMR.js → ReposTab-CFJT9mDR.js} +2 -2
  56. package/extensions/dashboard-client/dist/assets/{ReposTab-Dt1FGnMR.js.map → ReposTab-CFJT9mDR.js.map} +1 -1
  57. package/extensions/dashboard-client/dist/assets/{SessionsTab-D7D2RW6U.js → SessionsTab-BhP1z6_y.js} +2 -2
  58. package/extensions/dashboard-client/dist/assets/{SessionsTab-D7D2RW6U.js.map → SessionsTab-BhP1z6_y.js.map} +1 -1
  59. package/extensions/dashboard-client/dist/assets/{SetupTab-CgV5xCzz.js → SetupTab-2Glh7MKk.js} +2 -2
  60. package/extensions/dashboard-client/dist/assets/{SetupTab-CgV5xCzz.js.map → SetupTab-2Glh7MKk.js.map} +1 -1
  61. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CCNuJjyO.js → TimeSavedCard-DmwBDhkw.js} +2 -2
  62. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-CCNuJjyO.js.map → TimeSavedCard-DmwBDhkw.js.map} +1 -1
  63. package/extensions/dashboard-client/dist/assets/{TurnsTab-Cv1OCttJ.js → TurnsTab-CYIaOUUZ.js} +2 -2
  64. package/extensions/dashboard-client/dist/assets/{TurnsTab-Cv1OCttJ.js.map → TurnsTab-CYIaOUUZ.js.map} +1 -1
  65. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DD7vGaRS.js +2 -0
  66. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DD7vGaRS.js.map +1 -0
  67. package/extensions/dashboard-client/dist/assets/{WikiTab-B48QnQrK.js → WikiTab-CP-JEd17.js} +2 -2
  68. package/extensions/dashboard-client/dist/assets/{WikiTab-B48QnQrK.js.map → WikiTab-CP-JEd17.js.map} +1 -1
  69. package/extensions/dashboard-client/dist/assets/{button-BBQl2MiF.js → button-B1RhLsGs.js} +2 -2
  70. package/extensions/dashboard-client/dist/assets/{button-BBQl2MiF.js.map → button-B1RhLsGs.js.map} +1 -1
  71. package/extensions/dashboard-client/dist/assets/{card-BYbefUur.js → card-BLPT2-8G.js} +2 -2
  72. package/extensions/dashboard-client/dist/assets/{card-BYbefUur.js.map → card-BLPT2-8G.js.map} +1 -1
  73. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-swm0YZe0.js → generateCategoricalChart-DVOMJzL2.js} +2 -2
  74. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-swm0YZe0.js.map → generateCategoricalChart-DVOMJzL2.js.map} +1 -1
  75. package/extensions/dashboard-client/dist/assets/{index-DeIky7xm.js → index-CuLdiHRl.js} +3 -3
  76. package/extensions/dashboard-client/dist/assets/{index-DeIky7xm.js.map → index-CuLdiHRl.js.map} +1 -1
  77. package/extensions/dashboard-client/dist/assets/{switch-CctU78ww.js → switch-C5tqzhcl.js} +2 -2
  78. package/extensions/dashboard-client/dist/assets/{switch-CctU78ww.js.map → switch-C5tqzhcl.js.map} +1 -1
  79. package/extensions/dashboard-client/dist/assets/{toggle-BRCNCoiI.js → toggle-HcM6W2Yl.js} +2 -2
  80. package/extensions/dashboard-client/dist/assets/{toggle-BRCNCoiI.js.map → toggle-HcM6W2Yl.js.map} +1 -1
  81. package/extensions/dashboard-client/dist/assets/{useSSE-WfOiWDH_.js → useSSE-BtWUs2kL.js} +2 -2
  82. package/extensions/dashboard-client/dist/assets/{useSSE-WfOiWDH_.js.map → useSSE-BtWUs2kL.js.map} +1 -1
  83. package/extensions/dashboard-client/dist/index.html +1 -1
  84. package/extensions/dashboard-client/src/api/vector-cortex.ts +18 -0
  85. package/extensions/dashboard-client/src/tabs/VectorCortexRepairCard.tsx +43 -0
  86. package/extensions/dashboard-client/src/tabs/VectorCortexRestoreCard.tsx +42 -0
  87. package/extensions/dashboard-client/src/tabs/VectorCortexShardsCard.tsx +89 -0
  88. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +22 -60
  89. package/extensions/dashboard-client/src/types/vector-cortex.ts +33 -0
  90. package/extensions/dashboard-server/api-contracts/vector-cortex-heal.ts +68 -0
  91. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +5 -1
  92. package/extensions/dashboard-server/route-dispatch.ts +6 -0
  93. package/extensions/dashboard-server/routes-rag-settings-vector-cortex.ts +12 -0
  94. package/extensions/dashboard-server/routes-vector-cortex-heal.ts +51 -4
  95. package/extensions/dashboard-server/routes-vector-cortex-repair.ts +72 -0
  96. package/extensions/dashboard-server/routes-vector-cortex.ts +6 -1
  97. package/extensions/dashboard-server/routes.ts +1 -0
  98. package/package.json +1 -1
  99. package/src/config/vector-cortex.ts +31 -0
  100. package/src/config.ts +2 -0
  101. package/src/vector-cortex/heal/_repair-fixture.ts +138 -0
  102. package/src/vector-cortex/heal/_restore-fixture.ts +163 -0
  103. package/src/vector-cortex/heal/_vc6b-helpers.ts +55 -0
  104. package/src/vector-cortex/heal/controller.ts +189 -0
  105. package/src/vector-cortex/heal/rebuild.ts +200 -0
  106. package/src/vector-cortex/heal/repair-emit.ts +118 -0
  107. package/src/vector-cortex/heal/repair-types.ts +227 -0
  108. package/src/vector-cortex/heal/restore-emit.ts +94 -0
  109. package/src/vector-cortex/heal/restore-readers.ts +145 -0
  110. package/src/vector-cortex/heal/restore-types.ts +185 -0
  111. package/src/vector-cortex/heal/restore.ts +165 -0
  112. package/src/vector-cortex/heal/types.ts +50 -0
  113. package/src/vector-cortex/heal/verify.ts +93 -0
  114. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DTabQo6h.js +0 -2
  115. package/extensions/dashboard-client/dist/assets/VectorCortexTab-DTabQo6h.js.map +0 -1
@@ -0,0 +1,200 @@
1
+ /**
2
+ * vector-cortex/heal/rebuild.ts — VC6C generation rebuild + atomic pointer switch.
3
+ *
4
+ * Executes what `controller.ts` planned: materialize a NEW generation, verify its
5
+ * root digest, and only then flip the live pointer.
6
+ *
7
+ * COPY, VERIFY, SWITCH — in that order, always.
8
+ *
9
+ * 1. COPY. The rebuild writes into `plan.generation` (always `current + 1`),
10
+ * never into the live generation. The thing currently being served is never
11
+ * the thing being modified, so a crash mid-rebuild leaves a complete old
12
+ * generation and a partial new one — never a torn live one.
13
+ * 2. VERIFY. The new generation's root digest must equal the digest the plan
14
+ * pinned. This is the ONLY gate on the pointer.
15
+ * 3. SWITCH. `switchPointer` moves the pointer iff verification passed.
16
+ *
17
+ * A FAILED VERIFICATION DELETES NO EVIDENCE. On mismatch we keep the old pointer
18
+ * AND leave the new generation on disk. That is deliberate: the corrupt
19
+ * generation is the only artifact that can explain WHY the rebuild was wrong, and
20
+ * a self-healing system that tidies up its failures is a system that cannot be
21
+ * debugged. Cleanup is a separate, explicit operator action.
22
+ *
23
+ * CRASH SAFETY IS A CONSEQUENCE OF THE ORDER, NOT AN EXTRA STEP. The pointer is
24
+ * the single atomic commit point. Kill the process after step 1 or 2 and the old
25
+ * pointer is still live, so the next start serves the prior generation and simply
26
+ * re-plans — the orphaned generation is inert. This is what
27
+ * `rebuild-chaos.test.ts` pins.
28
+ *
29
+ * THE TRIAD (independent algorithms, per TRIAD_RESILIENCE).
30
+ * A — TARGETED: rebuild only `plan.range`, reusing the prior generation for
31
+ * everything outside it. Cheap; needs a healthy prior generation.
32
+ * B — FULL DETERMINISTIC: re-derive the whole subsystem from the byte ledger,
33
+ * reusing NOTHING. Independent of A: it shares no index, no prior
34
+ * generation, and no incremental state, so a bug or corruption that breaks
35
+ * A cannot break B the same way.
36
+ * C — DISABLE DERIVED STATE: no rebuild at all. Mode C is a real outcome, not
37
+ * an error path, and it MUST state its loss of old semantic context — the
38
+ * subsystem serves nothing rather than serving something wrong.
39
+ *
40
+ * PURE. `node:crypto` only — no storage, no console, no clock, no network
41
+ * (PREVENT-PI-004 / PREVENT-011). Callers own persistence; this module owns the
42
+ * decision and the digest arithmetic, which is what makes it fixture-testable.
43
+ */
44
+
45
+ import { createHash } from "node:crypto";
46
+
47
+ import type { Mode, RepairFailureCode, ShardRange } from "./repair-types.js";
48
+
49
+ /**
50
+ * Everything a rebuild needs. `sourceBytes` is the materialized content of the
51
+ * new generation; `expectedDigest` is the root digest the plan pinned and the
52
+ * ONLY thing that authorizes a pointer switch.
53
+ */
54
+ export interface RebuildInput {
55
+ readonly subsystem: string;
56
+ readonly range: ShardRange;
57
+ /** The NEW generation being written (never the live one). */
58
+ readonly generation: number;
59
+ /** The rebuilt generation's content. */
60
+ readonly sourceBytes: Uint8Array;
61
+ /** Root digest, BARE lowercase hex (the ExactShardV1.digest convention). */
62
+ readonly expectedDigest: string;
63
+ }
64
+
65
+ /**
66
+ * The rebuild verdict.
67
+ *
68
+ * The failure arm still carries `generation` so the caller can name the orphaned
69
+ * generation in a log or an operator prompt — the evidence is retained, so its
70
+ * identity must be reportable.
71
+ */
72
+ export type RebuildResult =
73
+ | {
74
+ readonly ok: true;
75
+ readonly generation: number;
76
+ /** The VERIFIED root digest (equals `expectedDigest`). */
77
+ readonly digest: string;
78
+ readonly mode: Mode;
79
+ }
80
+ | {
81
+ readonly ok: false;
82
+ readonly code: RepairFailureCode;
83
+ readonly generation: number;
84
+ readonly mode: Mode;
85
+ /** Set on mode C: the caller MUST be told derived context is gone. */
86
+ readonly semanticLossStated?: boolean;
87
+ };
88
+
89
+ /** The outcome of a pointer switch: which generation is live afterwards. */
90
+ export interface PointerSwitch {
91
+ readonly switched: boolean;
92
+ /** The live generation AFTER the attempt (unchanged when `switched` is false). */
93
+ readonly generation: number;
94
+ }
95
+
96
+ /** Root digest of a generation's bytes: SHA-256, bare lowercase hex. */
97
+ export function rootDigest(bytes: Uint8Array): string {
98
+ return createHash("sha256").update(bytes).digest("hex");
99
+ }
100
+
101
+ /**
102
+ * Materialize + verify one generation.
103
+ *
104
+ * Hashes the rebuilt bytes and compares to the pinned root digest. A mismatch
105
+ * returns `HEAL_REPAIR_DIGEST_MISMATCH` and — critically — the caller must NOT
106
+ * switch the pointer; `switchPointer` enforces that structurally by requiring the
107
+ * verified flag.
108
+ *
109
+ * An EMPTY rebuild is a failure, not an empty success: a generation with no bytes
110
+ * would hash to the digest of nothing, and if a plan ever pinned that digest an
111
+ * empty rebuild would "verify" and the pointer would flip to nothing at all. It
112
+ * is reported as `HEAL_REBUILD_FAILED` because the rebuild produced no artifact.
113
+ */
114
+ export function rebuildGeneration(
115
+ input: RebuildInput,
116
+ mode: Mode = "A",
117
+ ): RebuildResult {
118
+ if (input.sourceBytes.length === 0) {
119
+ return {
120
+ ok: false,
121
+ code: "HEAL_REBUILD_FAILED",
122
+ generation: input.generation,
123
+ mode,
124
+ };
125
+ }
126
+ const digest = rootDigest(input.sourceBytes);
127
+ if (digest !== input.expectedDigest) {
128
+ // Evidence retained: the caller keeps the generation on disk for inspection.
129
+ return {
130
+ ok: false,
131
+ code: "HEAL_REPAIR_DIGEST_MISMATCH",
132
+ generation: input.generation,
133
+ mode,
134
+ };
135
+ }
136
+ return { ok: true, generation: input.generation, digest, mode };
137
+ }
138
+
139
+ /**
140
+ * The atomic commit point: flip the live pointer iff the new generation verified.
141
+ *
142
+ * `verified` is a required argument rather than something re-derived here, so a
143
+ * caller cannot switch the pointer without having gone through
144
+ * `rebuildGeneration` — "switch without verifying" is not expressible.
145
+ *
146
+ * A non-monotonic switch is also refused: the new generation must be strictly
147
+ * greater than the current one. Replaying a stale plan after a restart would
148
+ * otherwise roll the pointer BACKWARDS onto an older generation, silently
149
+ * un-healing the subsystem.
150
+ */
151
+ export function switchPointer(
152
+ currentGen: number,
153
+ newGen: number,
154
+ verified: boolean,
155
+ ): PointerSwitch {
156
+ if (!verified) return { switched: false, generation: currentGen };
157
+ if (newGen <= currentGen) return { switched: false, generation: currentGen };
158
+ return { switched: true, generation: newGen };
159
+ }
160
+
161
+ /**
162
+ * Apply the triad arm for a rebuild.
163
+ *
164
+ * A and B run the same verification (a digest is a digest) but are reached by
165
+ * INDEPENDENT production paths: A reuses the prior generation and rebuilds only
166
+ * the planned range, while B re-derives everything from the byte ledger sharing
167
+ * no index or incremental state with A. C performs no rebuild at all and states
168
+ * its loss.
169
+ */
170
+ export function applyTriad(mode: Mode, input: RebuildInput): RebuildResult {
171
+ if (mode === "C") {
172
+ // Derived state disabled: no rebuild, and the loss of old semantic context
173
+ // is DISCLOSED rather than papered over with a stale or partial generation.
174
+ return {
175
+ ok: false,
176
+ code: "HEAL_REBUILD_FAILED",
177
+ generation: input.generation,
178
+ mode: "C",
179
+ semanticLossStated: true,
180
+ };
181
+ }
182
+ return rebuildGeneration(input, mode);
183
+ }
184
+
185
+ /**
186
+ * Convenience: rebuild then switch, returning both halves.
187
+ *
188
+ * The pointer moves only on a verified rebuild, so a failed verification yields
189
+ * `switched:false` with the ORIGINAL generation still live and the new (corrupt)
190
+ * generation left intact on disk for inspection.
191
+ */
192
+ export function rebuildAndSwitch(
193
+ input: RebuildInput,
194
+ currentGen: number,
195
+ mode: Mode = "A",
196
+ ): { readonly result: RebuildResult; readonly pointer: PointerSwitch } {
197
+ const result = applyTriad(mode, input);
198
+ const pointer = switchPointer(currentGen, input.generation, result.ok);
199
+ return { result, pointer };
200
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * vector-cortex/heal/repair-emit.ts — VC6C event reporter seam.
3
+ *
4
+ * Mirrors `./restore-emit.ts`: a thin `safe()` wrapper around an optional
5
+ * injected `emit`, and the three event names the sprint spec requires verbatim:
6
+ * - `vector_cortex_repair_planned` — a gap was detected, rebuild queued.
7
+ * - `vector_cortex_repair_pointer_switched`— a verified generation went live.
8
+ * - `vector_cortex_repair_backoff` — suppressed (rate limit) or failed.
9
+ *
10
+ * FLAG SEMANTICS. `detectGaps` / `planRebuild` / `rebuildGeneration` /
11
+ * `switchPointer` are PURE arithmetic and run REGARDLESS of `MEGACOMPACT_VC6C`.
12
+ * The flag gates ONLY this reporting + dashboard seam: with the flag off we still
13
+ * detect gaps, still verify digests, and still refuse unverified pointer
14
+ * switches — we just do not announce it under the VC6C event namespace. That is
15
+ * what makes flag-off byte-identical to VC6B: the computation is never skipped,
16
+ * only the emission.
17
+ *
18
+ * PAYLOAD DISCIPLINE. These events carry the SUBSYSTEM NAME, generation numbers,
19
+ * timings, and codes — never rebuilt bytes, never a root digest of user content,
20
+ * never a seq range's contents. The subsystem name is an operator-facing
21
+ * identifier ("topology"), not user data. A repair event is exactly the place
22
+ * where an unguarded `payload` field would leak a rebuilt transcript into a log.
23
+ *
24
+ * No console, no storage, no network (PREVENT-PI-004 / PREVENT-011). Every line
25
+ * is a structured JSON event with `ts` + `event`.
26
+ */
27
+
28
+ import { VC6C_ENABLED } from "../../config/vector-cortex.js";
29
+ import type { Mode, RepairEventName, RepairFailureCode } from "./repair-types.js";
30
+
31
+ /** Optional emit fn injected by the runtime; tests pass `undefined`. */
32
+ export type RepairEmit = (name: string, payload: unknown) => void;
33
+
34
+ /** Run `fn` only when an emit exists; a reporting failure is never fatal. */
35
+ function safe(emit: RepairEmit | undefined, fn: (emit: RepairEmit) => void): void {
36
+ if (emit === undefined) return;
37
+ try {
38
+ fn(emit);
39
+ } catch {
40
+ // Non-fatal: a reporting failure must never break the agent loop.
41
+ }
42
+ }
43
+
44
+ /** The event names VC6C emits, exported for the dashboard seam and tests. */
45
+ export const REPAIR_EVENT_NAMES: readonly RepairEventName[] = [
46
+ "vector_cortex_repair_planned",
47
+ "vector_cortex_repair_pointer_switched",
48
+ "vector_cortex_repair_backoff",
49
+ ] as const;
50
+
51
+ /** Report a planned rebuild: which subsystem, which generation, what delay. */
52
+ export function reportRepairPlanned(
53
+ emit: RepairEmit | undefined,
54
+ payload: {
55
+ readonly subsystem: string;
56
+ readonly generation: number;
57
+ readonly backoffMs: number;
58
+ readonly gapSize: number;
59
+ },
60
+ ): void {
61
+ if (!VC6C_ENABLED()) return;
62
+ safe(emit, (e) =>
63
+ e("vector_cortex_repair_planned", {
64
+ ts: undefined,
65
+ event: "vector_cortex_repair_planned",
66
+ subsystem: payload.subsystem,
67
+ generation: payload.generation,
68
+ backoffMs: payload.backoffMs,
69
+ gapSize: payload.gapSize,
70
+ }),
71
+ );
72
+ }
73
+
74
+ /** Report the atomic commit: a verified generation became live. */
75
+ export function reportRepairPointerSwitched(
76
+ emit: RepairEmit | undefined,
77
+ payload: {
78
+ readonly subsystem: string;
79
+ readonly fromGeneration: number;
80
+ readonly toGeneration: number;
81
+ readonly mode: Mode;
82
+ },
83
+ ): void {
84
+ if (!VC6C_ENABLED()) return;
85
+ safe(emit, (e) =>
86
+ e("vector_cortex_repair_pointer_switched", {
87
+ ts: undefined,
88
+ event: "vector_cortex_repair_pointer_switched",
89
+ subsystem: payload.subsystem,
90
+ fromGeneration: payload.fromGeneration,
91
+ toGeneration: payload.toGeneration,
92
+ mode: payload.mode,
93
+ }),
94
+ );
95
+ }
96
+
97
+ /** Report a suppressed or failed rebuild now waiting out its backoff. */
98
+ export function reportRepairBackoff(
99
+ emit: RepairEmit | undefined,
100
+ payload: {
101
+ readonly subsystem: string;
102
+ readonly code: RepairFailureCode;
103
+ readonly backoffMs: number;
104
+ readonly attempt: number;
105
+ },
106
+ ): void {
107
+ if (!VC6C_ENABLED()) return;
108
+ safe(emit, (e) =>
109
+ e("vector_cortex_repair_backoff", {
110
+ ts: undefined,
111
+ event: "vector_cortex_repair_backoff",
112
+ subsystem: payload.subsystem,
113
+ code: payload.code,
114
+ backoffMs: payload.backoffMs,
115
+ attempt: payload.attempt,
116
+ }),
117
+ );
118
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * vector-cortex/heal/repair-types.ts — VC6C self-healing derived controller.
3
+ *
4
+ * VC6B answered "when a node's bytes are gone, WHERE do they come from?". VC6C
5
+ * answers the question one level up: when a DERIVED subsystem (topology, shards,
6
+ * closure) has fallen BEHIND the durable authority, how do we notice, and how do
7
+ * we catch it up without ever risking the authority itself?
8
+ *
9
+ * THE AUTHORITY IS READ-ONLY, ALWAYS. The controller compares each derived
10
+ * source's high-water to the durable authority high-water and plans work. It has
11
+ * no write path to the authority — not a guarded one, not an admin one. Derived
12
+ * state is disposable and can always be rebuilt from the byte ledger; the
13
+ * authority is not, so the repair path is deliberately one-directional. This is
14
+ * why `RepairState` carries `authorityHighWater` as a plain readonly field and
15
+ * why no function in `controller.ts` returns anything that could be applied to it.
16
+ *
17
+ * NEVER READ PAST THE AUTHORITY (TRIAD_RESILIENCE §frontier). A derived builder
18
+ * may not read beyond the durable CONTIGUOUS authority high-water. During an
19
+ * authority outage that high-water FREEZES even though the spool keeps accepting
20
+ * frames — so a derived subsystem that is "behind" a frozen frontier is CORRECT,
21
+ * not broken, and planning a rebuild against the spool tail would materialize
22
+ * frames that are not yet durable. `detectGaps` therefore treats
23
+ * `authorityFrozen` as a hard stop (`HEAL_REPAIR_AUTHORITY_FROZEN`) rather than
24
+ * as a large gap to chase. After the drain, catch-up resumes from the OLD
25
+ * high-water; it never jumps to the tail.
26
+ *
27
+ * REBUILD IS COPY-THEN-SWITCH, NEVER IN-PLACE. `rebuild.ts` materializes a NEW
28
+ * generation, verifies its root digest, and only then flips the pointer. A failed
29
+ * verification keeps the old pointer and DELETES NO EVIDENCE: the corrupt
30
+ * generation stays on disk to be inspected. An in-place repair would, by
31
+ * construction, destroy the only copy of the thing that was about to be proven
32
+ * wrong.
33
+ *
34
+ * RATE LIMIT + BACKOFF ARE THE BLAST RADIUS. A subsystem that fails to rebuild
35
+ * will fail again, usually instantly, so an unbounded retry loop turns one broken
36
+ * shard into a CPU-saturating rebuild storm. One rebuild per subsystem per 5
37
+ * minutes bounds the steady state, and the deterministic exponential backoff
38
+ * (30s * 2^attempt, capped at 15 min, ±10% jitter derived from the SUBSYSTEM
39
+ * DIGEST rather than `Math.random`) bounds the failure state while keeping the
40
+ * schedule reproducible in a fixture.
41
+ *
42
+ * Pure types + registered conformance IDs: no storage, no console, no clock, no
43
+ * network (PREVENT-PI-004 / PREVENT-011).
44
+ */
45
+
46
+ import type { ShardRange } from "../shards/types.js";
47
+ import type { EventV2 } from "../ledger/types.js";
48
+
49
+ /** The triad mode, mirroring TRIAD_RESILIENCE (A targeted / B full / C disable). */
50
+ export type Mode = "A" | "B" | "C";
51
+
52
+ /**
53
+ * A derived subsystem name (e.g. "topology", "shards", "closure").
54
+ *
55
+ * Deliberately a plain string rather than a closed union: the set of derived
56
+ * subsystems grows every sprint, and a union here would force an unrelated
57
+ * contract edit (and a conformance-corpus regeneration) every time a new derived
58
+ * tier is added. The subsystem name is also the jitter seed, so it must be stable.
59
+ */
60
+ export type RepairSubsystem = string;
61
+
62
+ /**
63
+ * A planned rebuild for ONE subsystem.
64
+ *
65
+ * `range` is the gap to rebuild — derived high-water (exclusive) to authority
66
+ * high-water (inclusive) — so a plan is self-describing: an operator can read the
67
+ * exact seq window that will be materialized. `generation` is the NEW generation
68
+ * the rebuild will write into (never the live one). `backoffMs` is the delay
69
+ * BEFORE the plan may execute, and `scheduledAt` is the monotonic timestamp it
70
+ * becomes eligible.
71
+ */
72
+ export interface RepairPlanV1 {
73
+ readonly schema: "repair-plan-v1";
74
+ readonly subsystem: RepairSubsystem;
75
+ /** The seq/byte window to rebuild (derived high-water .. authority high-water). */
76
+ readonly range: ShardRange;
77
+ /** The NEW generation number the rebuild materializes into. */
78
+ readonly generation: number;
79
+ /** Deterministic delay before this plan is eligible to run. */
80
+ readonly backoffMs: number;
81
+ /** Monotonic ms at which the plan becomes eligible (`now + backoffMs`). */
82
+ readonly scheduledAt: bigint;
83
+ }
84
+
85
+ /**
86
+ * A repair lifecycle record. Emitted as a structured event AND retained for the
87
+ * dashboard's repair state, so it carries identity and counters only — never a
88
+ * rebuilt byte, never a node id, never transcript text (SECURITY_PRIVACY).
89
+ */
90
+ export interface RepairEventV1 {
91
+ readonly schema: "repair-event-v1";
92
+ readonly subsystem: RepairSubsystem;
93
+ /**
94
+ * `planned` — a gap was detected and a rebuild scheduled.
95
+ * `pointer-switched` — a verified generation became live (the ONLY success).
96
+ * `backoff` — a rebuild was suppressed (rate limit) or failed and is
97
+ * now waiting out its exponential delay.
98
+ */
99
+ readonly kind: "planned" | "pointer-switched" | "backoff";
100
+ readonly generation: number;
101
+ /** Monotonic ms of the transition. */
102
+ readonly ts: bigint;
103
+ }
104
+
105
+ /** VC6C failure codes (registered HEAL codes). */
106
+ export type RepairFailureCode =
107
+ /**
108
+ * The authority high-water is frozen (outage). Derived state is CORRECTLY
109
+ * behind and must not chase the spool tail — planning is refused, not delayed.
110
+ */
111
+ | "HEAL_REPAIR_AUTHORITY_FROZEN"
112
+ /** A rebuilt generation's root digest does not match — pointer NOT switched. */
113
+ | "HEAL_REPAIR_DIGEST_MISMATCH"
114
+ /** The rebuild itself could not produce a generation (mode C disable). */
115
+ | "HEAL_REBUILD_FAILED"
116
+ /** A second rebuild for this subsystem inside the 5-minute window. */
117
+ | "HEAL_REPAIR_RATE_LIMITED";
118
+
119
+ /**
120
+ * The controller's view of ONE derived subsystem.
121
+ *
122
+ * `authorityHighWater` is READ, never written (see the file header). `mode`
123
+ * records which triad arm this subsystem is currently served by, so a subsystem
124
+ * already in mode C (derived state disabled) is not repeatedly re-planned.
125
+ */
126
+ export interface RepairState {
127
+ readonly subsystem: RepairSubsystem;
128
+ /** How far the derived source has been built (inclusive seq). */
129
+ readonly derivedHighWater: bigint;
130
+ /** Durable CONTIGUOUS authority high-water (inclusive seq). Read-only. */
131
+ readonly authorityHighWater: bigint;
132
+ /** Monotonic ms of the last rebuild, or null if never rebuilt. */
133
+ readonly lastRebuildAt: bigint | null;
134
+ /** The CURRENT live generation. A plan targets `generation + 1`. */
135
+ readonly generation: number;
136
+ /** Which triad arm currently serves this subsystem. */
137
+ readonly mode: Mode;
138
+ /**
139
+ * Consecutive failed rebuild attempts, the exponent in `30s * 2^attempt`.
140
+ * Reset to 0 on a successful pointer switch.
141
+ */
142
+ readonly failedAttempts?: number;
143
+ /**
144
+ * True while the durable authority frontier is frozen (outage). A frozen
145
+ * authority makes a derived lag EXPECTED, so no plan may be produced.
146
+ */
147
+ readonly authorityFrozen?: boolean;
148
+ }
149
+
150
+ /** The gap-detection + planning surface. Pure: no clock of its own, no I/O. */
151
+ export interface RepairController {
152
+ /** Plan a rebuild for every subsystem with a real, actionable gap. */
153
+ readonly detectGaps: (
154
+ states: readonly RepairState[],
155
+ nowMs: bigint,
156
+ ) => readonly RepairPlanV1[];
157
+ /** Build a single plan for one subsystem's gap. */
158
+ readonly planRebuild: (state: RepairState, nowMs: bigint) => RepairPlanV1;
159
+ }
160
+
161
+ /**
162
+ * One rebuild per subsystem per 5 minutes. Bounds a rebuild storm: a subsystem
163
+ * that fails will fail again immediately, and without this an unhealthy tier
164
+ * would saturate the box re-materializing the same broken generation.
165
+ */
166
+ export const REPAIR_RATE_LIMIT_MS = 5 * 60_000;
167
+
168
+ /**
169
+ * Exponential backoff base/cap, matching the breaker's retry rule
170
+ * (TRIAD_RESILIENCE): `30s * 2^attempt`, capped at 15 minutes.
171
+ */
172
+ export const REPAIR_BACKOFF_BASE_MS = 30_000;
173
+ export const REPAIR_BACKOFF_CAP_MS = 15 * 60_000;
174
+
175
+ /**
176
+ * ±10% deterministic jitter. Derived from the SUBSYSTEM DIGEST, not a PRNG, so
177
+ * two subsystems desynchronize (no thundering herd) while any single subsystem's
178
+ * schedule stays reproducible in a fixture.
179
+ */
180
+ export const REPAIR_BACKOFF_JITTER = 0.1;
181
+
182
+ /**
183
+ * Registered VC6C conformance ID range (HEAL-031..045), continuing VC6B's
184
+ * HEAL-016..030. The acceptance test reads these rows from the v2 manifest and
185
+ * asserts each returns its manifest `ok`/`code`.
186
+ */
187
+ export const REPAIR_IDS: readonly string[] = Array.from(
188
+ { length: 15 },
189
+ (_v, i) => `HEAL-${String(i + 31).padStart(3, "0")}`,
190
+ );
191
+
192
+ /** Named VC6C conformance assertions (the sprint's headline rows). */
193
+ export const REPAIR_NAMED_IDS = [
194
+ "HEAL-GAP-001",
195
+ "HEAL-RATE-002",
196
+ "HEAL-SWITCH-003",
197
+ ] as const;
198
+
199
+ /** The three structured events the VC6C reporter emits. */
200
+ export type RepairEventName =
201
+ | "vector_cortex_repair_planned"
202
+ | "vector_cortex_repair_pointer_switched"
203
+ | "vector_cortex_repair_backoff";
204
+
205
+ /**
206
+ * Reader-only dashboard aggregate. Counters and the runtime mode only — no
207
+ * subsystem payload, no rebuilt bytes, no gap ranges, no high-water marks, no
208
+ * root digests (SECURITY_PRIVACY).
209
+ *
210
+ * Field names mirror `VectorCortexRepairView` in
211
+ * `extensions/dashboard-server/api-contracts/vector-cortex-heal.ts` EXACTLY.
212
+ * The dashboard contract is the shipped shape; keeping a differently-named
213
+ * mirror here would guarantee a silent drift the compiler could never catch,
214
+ * since the route builds its body from the extensions-side type.
215
+ */
216
+ export interface RepairView {
217
+ readonly enabled: boolean;
218
+ readonly mode: Mode;
219
+ readonly repairAttempts: number;
220
+ readonly repairsPlanned: number;
221
+ readonly pointersSwitched: number;
222
+ readonly backoffs: number;
223
+ readonly lastBackoffMs: number | null;
224
+ readonly lastFailure: RepairFailureCode | null;
225
+ }
226
+
227
+ export type { EventV2, ShardRange };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * vector-cortex/heal/restore-emit.ts — VC6B event reporter seam.
3
+ *
4
+ * Mirrors `./emit.ts`: a thin `safe()` wrapper around an optional injected
5
+ * `emit` (unit tests pass `undefined` and stay pure), and the two event names the
6
+ * sprint spec requires verbatim:
7
+ * - `vector_cortex_source_restored` — a restore batch completed.
8
+ * - `vector_cortex_restore_digest_rejected` — a source failed its digest check.
9
+ *
10
+ * FLAG SEMANTICS. `restoreSources` / `verifyRestored` are PURE arithmetic and run
11
+ * REGARDLESS of `MEGACOMPACT_VC6B`. The flag gates ONLY this reporting +
12
+ * dashboard seam: with the flag off we still restore and still verify, we just do
13
+ * not announce it under the VC6B event namespace. That is what makes flag-off
14
+ * byte-identical to VC6A — the computation is never skipped, only the emission.
15
+ *
16
+ * PAYLOAD DISCIPLINE. These events carry COUNTS and MODES only — never restored
17
+ * bytes, never node text, never a digest of user content. The exact ledger is not
18
+ * diagnostic data (SECURITY_PRIVACY), and a restoration event is exactly the
19
+ * place where an unguarded `payload` field would leak the entire transcript into
20
+ * a log file.
21
+ *
22
+ * No console, no storage, no network (PREVENT-PI-004 / PREVENT-011). Every line
23
+ * is a structured JSON event with `ts` + `event`.
24
+ */
25
+
26
+ import { VC6B_ENABLED } from "../../config/vector-cortex.js";
27
+ import type { RestoreEventName, RestoreFailureCode } from "./restore-types.js";
28
+
29
+ /** Optional emit fn injected by the runtime; tests pass `undefined`. */
30
+ export type RestoreEmit = (name: string, payload: unknown) => void;
31
+
32
+ /** Run `fn` only when an emit exists; a reporting failure is never fatal. */
33
+ function safe(emit: RestoreEmit | undefined, fn: (emit: RestoreEmit) => void): void {
34
+ if (emit === undefined) return;
35
+ try {
36
+ fn(emit);
37
+ } catch {
38
+ // Non-fatal: a reporting failure must never break the agent loop.
39
+ }
40
+ }
41
+
42
+ /** The event names VC6B emits, exported for the dashboard seam and tests. */
43
+ export const RESTORE_EVENT_NAMES: readonly RestoreEventName[] = [
44
+ "vector_cortex_source_restored",
45
+ "vector_cortex_restore_digest_rejected",
46
+ ] as const;
47
+
48
+ /**
49
+ * Report a completed restoration. Counts and mode only — enough to see whether
50
+ * the shard index is serving reads (mode A) or every span is falling through to
51
+ * a ledger scan (mode B), without disclosing what was restored.
52
+ */
53
+ export function reportSourceRestored(
54
+ emit: RestoreEmit | undefined,
55
+ payload: {
56
+ readonly sessionId: string;
57
+ readonly restoredCount: number;
58
+ readonly missingCount: number;
59
+ readonly mode: "A" | "B" | "C";
60
+ },
61
+ ): void {
62
+ if (!VC6B_ENABLED()) return;
63
+ safe(emit, (e) =>
64
+ e("vector_cortex_source_restored", {
65
+ ts: undefined,
66
+ event: "vector_cortex_source_restored",
67
+ sessionId: payload.sessionId,
68
+ restoredCount: payload.restoredCount,
69
+ missingCount: payload.missingCount,
70
+ mode: payload.mode,
71
+ }),
72
+ );
73
+ }
74
+
75
+ /** Report a rejected source (digest/limit/range). Suppressed under flag-off. */
76
+ export function reportRestoreDigestRejected(
77
+ emit: RestoreEmit | undefined,
78
+ payload: {
79
+ readonly sessionId: string;
80
+ readonly code: RestoreFailureCode;
81
+ readonly mode: "A" | "B" | "C";
82
+ },
83
+ ): void {
84
+ if (!VC6B_ENABLED()) return;
85
+ safe(emit, (e) =>
86
+ e("vector_cortex_restore_digest_rejected", {
87
+ ts: undefined,
88
+ event: "vector_cortex_restore_digest_rejected",
89
+ sessionId: payload.sessionId,
90
+ code: payload.code,
91
+ mode: payload.mode,
92
+ }),
93
+ );
94
+ }