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,138 @@
1
+ /**
2
+ * heal/_repair-fixture.ts — conformance fixture I/O for VC6C healing-controller rows.
3
+ *
4
+ * Sibling of `_restore-fixture.ts` (VC6B) and `_acceptance-fixture.ts` (VC6A);
5
+ * split out so no loader approaches the 300-line soft limit and so the
6
+ * BigInt/base64 decoding lives next to the contract it reconstitutes.
7
+ *
8
+ * DECODING IS THE POINT. Fixtures are canonical JSON, which cannot express
9
+ * bigints or bytes, so the corpus stores numeric `nowMs` / high-waters and
10
+ * base64 source bytes. These loaders turn those back into the REAL `RepairState`
11
+ * / `RebuildInput` objects the production controller consumes — no mocks, no
12
+ * stubs, no parallel "test shape". A lossy decode would make the digests or the
13
+ * planned ranges disagree and the acceptance test would fail loudly.
14
+ */
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import assert from "node:assert/strict";
19
+
20
+ import type { Mode, RepairState } from "./repair-types.js";
21
+ import type { RebuildInput } from "./rebuild.js";
22
+ import { V2, readManifest } from "./_acceptance-fixture.js";
23
+
24
+ /** A subsystem state as it appears in JSON: high-waters are numbers, not bigints. */
25
+ export interface RepairFxState {
26
+ subsystem: string;
27
+ derivedHighWater: number;
28
+ authorityHighWater: number;
29
+ lastRebuildAt: number | null;
30
+ generation: number;
31
+ mode: Mode;
32
+ failedAttempts?: number;
33
+ authorityFrozen?: boolean;
34
+ }
35
+
36
+ export interface RepairFxRebuild {
37
+ subsystem: string;
38
+ generation: number;
39
+ currentGeneration: number;
40
+ sourceBytesBase64: string;
41
+ expectedDigest: string;
42
+ triadMode: Mode;
43
+ }
44
+
45
+ export interface RepairFxBackoff {
46
+ subsystem: string;
47
+ attempts: number[];
48
+ }
49
+
50
+ export interface RepairFxInput {
51
+ scenario: string;
52
+ /** Which real entry point the acceptance test drives. */
53
+ mode: "detect" | "backoff" | "rebuild";
54
+ /** The INJECTED monotonic clock — VC6C never reads a real clock. */
55
+ nowMs: number;
56
+ states: RepairFxState[];
57
+ rebuild?: RepairFxRebuild;
58
+ backoff?: RepairFxBackoff;
59
+ }
60
+
61
+ export interface RepairFxExpected {
62
+ ok: boolean;
63
+ code?: string;
64
+ plannedCount: number;
65
+ /** Exact [seqStart, seqEnd] of each plan, in plan order. */
66
+ ranges: number[][];
67
+ switched?: boolean;
68
+ generation?: number;
69
+ semanticLossStated?: boolean;
70
+ monotonic?: boolean;
71
+ capped?: boolean;
72
+ idempotent?: boolean;
73
+ }
74
+
75
+ export interface RepairFx {
76
+ id: string;
77
+ schema: string;
78
+ producer: string;
79
+ assertion: string;
80
+ kind: string;
81
+ input: RepairFxInput;
82
+ expected: RepairFxExpected;
83
+ }
84
+
85
+ /** Read one registered healing-controller fixture (asserting it IS registered). */
86
+ export function repairFixture(id: string): RepairFx {
87
+ const m = readManifest();
88
+ const row = m.fixtures.find(
89
+ (f) => f.id === id && f.path.startsWith("healing-controller/"),
90
+ );
91
+ assert.ok(row, `fixture ${id} registered under healing-controller/ in manifest`);
92
+ return JSON.parse(readFileSync(join(V2, row!.path), "utf8")) as RepairFx;
93
+ }
94
+
95
+ /** JSON numbers -> the bigint fields `RepairState` declares. */
96
+ export function decodeState(s: RepairFxState): RepairState {
97
+ return {
98
+ subsystem: s.subsystem,
99
+ derivedHighWater: BigInt(s.derivedHighWater),
100
+ authorityHighWater: BigInt(s.authorityHighWater),
101
+ lastRebuildAt: s.lastRebuildAt === null ? null : BigInt(s.lastRebuildAt),
102
+ generation: s.generation,
103
+ mode: s.mode,
104
+ ...(s.failedAttempts !== undefined ? { failedAttempts: s.failedAttempts } : {}),
105
+ ...(s.authorityFrozen !== undefined ? { authorityFrozen: s.authorityFrozen } : {}),
106
+ };
107
+ }
108
+
109
+ /** Reconstitute a real `RebuildInput` from its fixture row. */
110
+ export function decodeRebuild(r: RepairFxRebuild): RebuildInput {
111
+ return {
112
+ subsystem: r.subsystem,
113
+ range: {
114
+ sessionId: r.subsystem,
115
+ seqStart: 0n,
116
+ seqEnd: 0n,
117
+ byteStart: 0,
118
+ byteEnd: 0,
119
+ },
120
+ generation: r.generation,
121
+ sourceBytes: new Uint8Array(Buffer.from(r.sourceBytesBase64, "base64")),
122
+ expectedDigest: r.expectedDigest,
123
+ };
124
+ }
125
+
126
+ /** Flag-pinned wrapper: VC6C gated by MEGACOMPACT_VC6C (defaults ON). */
127
+ export function withVc6cFlagsOn(fn: () => void): () => void {
128
+ return (): void => {
129
+ const saved = process.env.MEGACOMPACT_VC6C;
130
+ process.env.MEGACOMPACT_VC6C = "1";
131
+ try {
132
+ fn();
133
+ } finally {
134
+ if (saved === undefined) delete process.env.MEGACOMPACT_VC6C;
135
+ else process.env.MEGACOMPACT_VC6C = saved;
136
+ }
137
+ };
138
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * heal/_restore-fixture.ts — conformance fixture I/O for VC6B restoration rows.
3
+ *
4
+ * Sibling of `_acceptance-fixture.ts` (which owns the VC6A closure-optimization
5
+ * rows); split out so neither file approaches the 300-line soft limit and so the
6
+ * base64/BigInt decoding lives next to the contract it reconstitutes.
7
+ *
8
+ * DECODING IS THE POINT. Fixtures are canonical JSON, which cannot express bytes
9
+ * or bigints, so the corpus stores `originalBytesBase64` + numeric `seq`. These
10
+ * loaders turn those back into the REAL `ExactShardV1` / `EventV2` objects the
11
+ * production readers consume — no mocks, no stubs, no parallel "test shape". If
12
+ * the decode were lossy the digests would not match and the acceptance test would
13
+ * fail loudly, which is exactly the guarantee we want from a byte-identity sprint.
14
+ */
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import assert from "node:assert/strict";
19
+
20
+ import type { EventV2, ExactShardV1, ShardRange } from "./restore-types.js";
21
+ import { V2, readManifest } from "./_acceptance-fixture.js";
22
+
23
+ /** A `ShardRange` as it appears in JSON: `seq` bounds are numbers, not bigints. */
24
+ export interface RestoreFxRange {
25
+ sessionId: string;
26
+ seqStart: number;
27
+ seqEnd: number;
28
+ byteStart: number;
29
+ byteEnd: number;
30
+ }
31
+
32
+ export interface RestoreFxSpan {
33
+ nodeId: string;
34
+ range: RestoreFxRange;
35
+ digest: string;
36
+ }
37
+
38
+ export interface RestoreFxShard {
39
+ sessionId: string;
40
+ range: RestoreFxRange;
41
+ originalBytesBase64: string;
42
+ digest: string;
43
+ byteCount: number;
44
+ case: "tool-pair" | "anchor" | "invalid-utf8" | "anchor+invalid";
45
+ }
46
+
47
+ export interface RestoreFxEvent {
48
+ sessionId: string;
49
+ seq: number;
50
+ eventId: string;
51
+ role: "policy" | "user" | "assistant" | "tool";
52
+ kind: string;
53
+ originalBytesBase64: string;
54
+ bytesDigest: string;
55
+ occurredAtMs: number;
56
+ toolCallId?: string;
57
+ }
58
+
59
+ export interface RestoreFxInput {
60
+ scenario: string;
61
+ sessionId: string;
62
+ request: { spans: RestoreFxSpan[] };
63
+ exactShards: RestoreFxShard[];
64
+ ledgerEvents: RestoreFxEvent[];
65
+ }
66
+
67
+ export interface RestoreFxExpected {
68
+ ok: boolean;
69
+ code?: string;
70
+ restoredCount: number;
71
+ missingCount: number;
72
+ mode: "A" | "B" | "C";
73
+ }
74
+
75
+ export interface RestoreFx {
76
+ id: string;
77
+ schema: string;
78
+ producer: string;
79
+ assertion: string;
80
+ kind: string;
81
+ input: RestoreFxInput;
82
+ expected: RestoreFxExpected;
83
+ }
84
+
85
+ /** Read one registered restoration fixture (asserting it IS registered). */
86
+ export function restorationFixture(id: string): RestoreFx {
87
+ const m = readManifest();
88
+ const row = m.fixtures.find((f) => f.id === id && f.path.startsWith("restoration/"));
89
+ assert.ok(row, `fixture ${id} registered under restoration/ in manifest`);
90
+ return JSON.parse(readFileSync(join(V2, row!.path), "utf8")) as RestoreFx;
91
+ }
92
+
93
+ /** base64 -> exact bytes, byte-for-byte (invalid UTF-8 included). */
94
+ export function decodeBytes(base64: string): Uint8Array {
95
+ return new Uint8Array(Buffer.from(base64, "base64"));
96
+ }
97
+
98
+ /** JSON number seq bounds -> the bigint bounds `ShardRange` declares. */
99
+ export function decodeRange(r: RestoreFxRange): ShardRange {
100
+ return {
101
+ sessionId: r.sessionId,
102
+ seqStart: BigInt(r.seqStart),
103
+ seqEnd: BigInt(r.seqEnd),
104
+ byteStart: r.byteStart,
105
+ byteEnd: r.byteEnd,
106
+ };
107
+ }
108
+
109
+ /** Reconstitute a real `ExactShardV1` from its fixture row. */
110
+ export function decodeShard(s: RestoreFxShard): ExactShardV1 {
111
+ return {
112
+ schema: "exact-shard-v1",
113
+ sessionId: s.sessionId,
114
+ range: decodeRange(s.range),
115
+ kind: "exact",
116
+ originalBytes: decodeBytes(s.originalBytesBase64),
117
+ digest: s.digest,
118
+ byteCount: s.byteCount,
119
+ case: s.case,
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Reconstitute a real `EventV2`. `utf8` is re-derived by strict classification
125
+ * (never lossy replacement) so an invalid-UTF-8 fixture produces the
126
+ * `{valid:false, base64}` discriminant the VC1A contract requires.
127
+ */
128
+ export function decodeEvent(e: RestoreFxEvent): EventV2 {
129
+ const bytes = decodeBytes(e.originalBytesBase64);
130
+ let utf8: EventV2["utf8"];
131
+ try {
132
+ utf8 = { valid: true, text: new TextDecoder("utf-8", { fatal: true }).decode(bytes) };
133
+ } catch {
134
+ utf8 = { valid: false, base64: e.originalBytesBase64 };
135
+ }
136
+ return {
137
+ schema: "event-v2",
138
+ sessionId: e.sessionId,
139
+ seq: BigInt(e.seq),
140
+ eventId: e.eventId,
141
+ role: e.role,
142
+ kind: e.kind,
143
+ originalBytes: bytes,
144
+ bytesDigest: e.bytesDigest as EventV2["bytesDigest"],
145
+ utf8,
146
+ ...(e.toolCallId !== undefined ? { toolCallId: e.toolCallId } : {}),
147
+ occurredAtMs: BigInt(e.occurredAtMs),
148
+ };
149
+ }
150
+
151
+ /** Flag-pinned wrapper: VC6B gated by MEGACOMPACT_VC6B (defaults ON). */
152
+ export function withVc6bFlagsOn(fn: () => void): () => void {
153
+ return (): void => {
154
+ const saved = process.env.MEGACOMPACT_VC6B;
155
+ process.env.MEGACOMPACT_VC6B = "1";
156
+ try {
157
+ fn();
158
+ } finally {
159
+ if (saved === undefined) delete process.env.MEGACOMPACT_VC6B;
160
+ else process.env.MEGACOMPACT_VC6B = saved;
161
+ }
162
+ };
163
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * heal/_vc6b-helpers.ts — shared decode/run helpers for VC6B acceptance tests.
3
+ *
4
+ * Extracted from vc6b-acceptance.test.ts so no single test file crosses the
5
+ * 300-line soft limit (soft-as-hard gate). Each sibling test file imports from
6
+ * here rather than duplicating the decode/runReal logic.
7
+ */
8
+
9
+ import { createHash } from "node:crypto";
10
+
11
+ import type {
12
+ RestoreReader,
13
+ RestoreRequestV1,
14
+ RestoreResultV1,
15
+ } from "./restore-types.js";
16
+ import { restoreSources } from "./restore.js";
17
+ import { verifyRestored } from "./verify.js";
18
+ import type { RestoreFx } from "./_restore-fixture.js";
19
+ import { decodeRange, decodeShard, decodeEvent } from "./_restore-fixture.js";
20
+
21
+ export const enc = (s: string): Uint8Array => new Uint8Array(Buffer.from(s));
22
+ export const hex = (b: Uint8Array): string =>
23
+ createHash("sha256").update(b).digest("hex");
24
+
25
+ export function decodeFx(fx: RestoreFx): {
26
+ request: RestoreRequestV1;
27
+ reader: RestoreReader;
28
+ } {
29
+ return {
30
+ request: {
31
+ schema: "restore-request-v1",
32
+ sessionId: fx.input.sessionId,
33
+ spans: fx.input.request.spans.map((s) => ({
34
+ nodeId: s.nodeId,
35
+ range: decodeRange(s.range),
36
+ digest: s.digest,
37
+ })),
38
+ },
39
+ reader: {
40
+ exactShards: fx.input.exactShards.map(decodeShard),
41
+ ledgerEvents: fx.input.ledgerEvents.map(decodeEvent),
42
+ },
43
+ };
44
+ }
45
+
46
+ export function runReal(fx: RestoreFx): {
47
+ request: RestoreRequestV1;
48
+ reader: RestoreReader;
49
+ result: RestoreResultV1;
50
+ verification: ReturnType<typeof verifyRestored>;
51
+ } {
52
+ const { request, reader } = decodeFx(fx);
53
+ const result = restoreSources(request, reader);
54
+ return { request, reader, result, verification: verifyRestored(result, request) };
55
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * vector-cortex/heal/controller.ts — VC6C gap detection + rebuild planning.
3
+ *
4
+ * Compares each derived subsystem's high-water to the durable authority
5
+ * high-water and emits a `RepairPlanV1` for every gap that is real, actionable,
6
+ * and not rate-limited. The controller DECIDES; `rebuild.ts` executes.
7
+ *
8
+ * THE AUTHORITY IS NEVER WRITTEN. Every function here takes `RepairState` (whose
9
+ * `authorityHighWater` is readonly) and returns plans. There is no code path,
10
+ * guarded or otherwise, that mutates authority — derived state is rebuildable,
11
+ * authority is not, so repair is strictly one-directional.
12
+ *
13
+ * FOUR REASONS NOT TO PLAN, in priority order. The order is the contract: a
14
+ * frozen authority outranks a rate limit, because "the frontier is not real yet"
15
+ * is a statement about CORRECTNESS while "you rebuilt recently" is only about
16
+ * pacing. Reporting RATE_LIMITED during an outage would tell an operator to wait
17
+ * five minutes for a rebuild that must never happen at all.
18
+ *
19
+ * 1. AUTHORITY FROZEN. During an outage the durable high-water freezes while
20
+ * the spool keeps accepting frames (TRIAD_RESILIENCE §frontier). A derived
21
+ * subsystem behind a frozen frontier is CORRECT, so we refuse to plan rather
22
+ * than chase the spool tail and materialize non-durable frames.
23
+ * 2. NO GAP. `derived >= authority` — nothing to do. Note `>`: a derived source
24
+ * AHEAD of authority is not repaired by rebuilding a backwards range (that
25
+ * would produce an inverted range); it is left alone for the breaker.
26
+ * 3. MODE C. Derived state is disabled for this subsystem. Re-planning a
27
+ * subsystem whose derived tier is intentionally off is a rebuild loop.
28
+ * 4. RATE LIMITED. One rebuild per subsystem per 5 minutes.
29
+ *
30
+ * DETERMINISTIC JITTER. The ±10% spread comes from a SHA-256 of the subsystem
31
+ * name plus the attempt, never `Math.random`. Two subsystems desynchronize (no
32
+ * thundering herd) while a single subsystem's schedule is byte-reproducible — a
33
+ * fixture can pin `backoffMs` exactly, which a PRNG would make untestable.
34
+ *
35
+ * PURE. `node:crypto` is the only dependency beyond types: no storage, no
36
+ * console, no network, and no clock — `nowMs` is always injected, which is what
37
+ * makes the fake-clock restart fixtures possible (PREVENT-PI-004 / PREVENT-011).
38
+ */
39
+
40
+ import { createHash } from "node:crypto";
41
+
42
+ import type {
43
+ RepairPlanV1,
44
+ RepairState,
45
+ RepairSubsystem,
46
+ ShardRange,
47
+ } from "./repair-types.js";
48
+ import {
49
+ REPAIR_BACKOFF_BASE_MS,
50
+ REPAIR_BACKOFF_CAP_MS,
51
+ REPAIR_BACKOFF_JITTER,
52
+ REPAIR_RATE_LIMIT_MS,
53
+ } from "./repair-types.js";
54
+
55
+ /**
56
+ * A stable fraction in [0,1) derived from the subsystem name + attempt.
57
+ *
58
+ * Uses the first 6 hex digits (24 bits) of SHA-256 — plenty of spread for a ±10%
59
+ * window, and small enough to stay exact in a float64 division.
60
+ */
61
+ function digestFraction(subsystem: RepairSubsystem, attempt: number): number {
62
+ const hex = createHash("sha256")
63
+ .update(`${subsystem}:${attempt}`)
64
+ .digest("hex")
65
+ .slice(0, 6);
66
+ return parseInt(hex, 16) / 0x1000000;
67
+ }
68
+
69
+ /**
70
+ * Deterministic exponential backoff: `30s * 2^attempt`, capped at 15 minutes,
71
+ * then spread by ±10% seeded from the subsystem digest.
72
+ *
73
+ * The cap is applied BEFORE the jitter so the jitter is a spread around the cap
74
+ * rather than a way to exceed it; the result is floored to an integer ms so the
75
+ * value is exactly representable in JSON (a fixture pins it verbatim).
76
+ *
77
+ * `attempt` is clamped at 0 and at 30: `2^attempt` for an unclamped large attempt
78
+ * would reach Infinity, and `Infinity * jitter` is NaN — a NaN backoff would
79
+ * schedule a plan that is never eligible and silently wedge the subsystem.
80
+ */
81
+ export function computeBackoff(subsystem: RepairSubsystem, attempt: number): number {
82
+ const safe = Math.min(Math.max(Math.floor(attempt), 0), 30);
83
+ const raw = REPAIR_BACKOFF_BASE_MS * 2 ** safe;
84
+ const capped = Math.min(raw, REPAIR_BACKOFF_CAP_MS);
85
+ // Map [0,1) onto [-1,+1) then scale to the ±10% window.
86
+ const spread = (digestFraction(subsystem, safe) * 2 - 1) * REPAIR_BACKOFF_JITTER;
87
+ return Math.max(0, Math.floor(capped * (1 + spread)));
88
+ }
89
+
90
+ /**
91
+ * True when this subsystem rebuilt less than 5 minutes ago.
92
+ *
93
+ * A subsystem that has NEVER rebuilt (`lastRebuildAt === null`) is never rate
94
+ * limited — the first repair after a restart must not be delayed by the absence
95
+ * of history.
96
+ */
97
+ export function isRateLimited(
98
+ lastRebuildAt: bigint | null,
99
+ nowMs: bigint,
100
+ ): boolean {
101
+ if (lastRebuildAt === null) return false;
102
+ return lastRebuildAt + BigInt(REPAIR_RATE_LIMIT_MS) > nowMs;
103
+ }
104
+
105
+ /**
106
+ * The seq window a rebuild must cover: the first UNBUILT seq through the
107
+ * authority frontier, inclusive.
108
+ *
109
+ * Byte bounds are intentionally 0..0. VC6C plans in SEQ space — the controller
110
+ * knows how far each derived tier has been built, but byte offsets belong to the
111
+ * shard/ledger layer that executes the rebuild. Inventing byte bounds here would
112
+ * be fabricating a fact the controller does not have.
113
+ */
114
+ function gapRange(state: RepairState): ShardRange {
115
+ return {
116
+ sessionId: state.subsystem,
117
+ seqStart: state.derivedHighWater + 1n,
118
+ seqEnd: state.authorityHighWater,
119
+ byteStart: 0,
120
+ byteEnd: 0,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Build the plan for one subsystem's gap.
126
+ *
127
+ * Always targets `generation + 1`: a rebuild NEVER writes into the live
128
+ * generation, so a failed or half-written rebuild cannot corrupt what is
129
+ * currently being served (see `rebuild.ts` copy-then-switch).
130
+ *
131
+ * Exported for direct unit testing and for callers that have already decided a
132
+ * plan is warranted; `detectGaps` is the guarded entry point that applies the
133
+ * four refusal rules first.
134
+ */
135
+ export function planRebuild(state: RepairState, nowMs: bigint): RepairPlanV1 {
136
+ const backoffMs = computeBackoff(state.subsystem, state.failedAttempts ?? 0);
137
+ return {
138
+ schema: "repair-plan-v1",
139
+ subsystem: state.subsystem,
140
+ range: gapRange(state),
141
+ generation: state.generation + 1,
142
+ backoffMs,
143
+ scheduledAt: nowMs + BigInt(backoffMs),
144
+ };
145
+ }
146
+
147
+ /**
148
+ * True when a subsystem is eligible for a rebuild plan (the four refusal rules).
149
+ * Ordering matters — see the file header.
150
+ */
151
+ export function isPlannable(state: RepairState, nowMs: bigint): boolean {
152
+ if (state.authorityFrozen === true) return false;
153
+ if (state.derivedHighWater >= state.authorityHighWater) return false;
154
+ if (state.mode === "C") return false;
155
+ if (isRateLimited(state.lastRebuildAt, nowMs)) return false;
156
+ return true;
157
+ }
158
+
159
+ /**
160
+ * Detect derived gaps and plan a rebuild for each eligible subsystem.
161
+ *
162
+ * Output order follows INPUT order, not subsystem name: the caller controls
163
+ * priority (a topology gap may matter more than a closure gap), and re-sorting
164
+ * here would silently override that. Never throws — an unplannable subsystem is
165
+ * simply absent from the result, so a single wedged tier cannot stop the others
166
+ * from healing (PRACTICES: non-fatal).
167
+ */
168
+ export function detectGaps(
169
+ states: readonly RepairState[],
170
+ nowMs: bigint,
171
+ ): readonly RepairPlanV1[] {
172
+ const plans: RepairPlanV1[] = [];
173
+ for (const state of states) {
174
+ if (!isPlannable(state, nowMs)) continue;
175
+ plans.push(planRebuild(state, nowMs));
176
+ }
177
+ return plans;
178
+ }
179
+
180
+ /**
181
+ * The bound controller surface. A plain object (not a class): there is no
182
+ * instance state to hold — every input, including the clock, is injected.
183
+ */
184
+ export function createRepairController(): {
185
+ readonly detectGaps: typeof detectGaps;
186
+ readonly planRebuild: typeof planRebuild;
187
+ } {
188
+ return { detectGaps, planRebuild };
189
+ }