pi-mega-compact 0.19.3 → 0.20.1

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 (114) hide show
  1. package/dist/config/vector-cortex.js +24 -0
  2. package/dist/config.js +1 -1
  3. package/dist/extensions/dashboard-server/routes-cache.test/_helpers.js +2 -0
  4. package/dist/extensions/dashboard-server/routes-rag-settings-helpers.js +2 -0
  5. package/dist/extensions/dashboard-server/routes-vector-cortex-helpers.js +100 -0
  6. package/dist/extensions/dashboard-server/routes-vector-cortex-residual.js +51 -0
  7. package/dist/extensions/dashboard-server/routes-vector-cortex-shards.js +48 -0
  8. package/dist/extensions/dashboard-server/routes-vector-cortex.js +2 -0
  9. package/dist/extensions/dashboard-server/routes.js +1 -1
  10. package/dist/extensions/dashboard-server/server.js +41 -16
  11. package/dist/extensions/dashboard-server/tailscale.js +32 -0
  12. package/dist/src/config/vector-cortex.js +24 -0
  13. package/dist/src/config.js +1 -1
  14. package/dist/src/vector-cortex/residual/codec.js +224 -0
  15. package/dist/src/vector-cortex/residual/dct.js +158 -0
  16. package/dist/src/vector-cortex/residual/fixture-payload.js +77 -0
  17. package/dist/src/vector-cortex/residual/gf256.js +182 -0
  18. package/dist/src/vector-cortex/residual/parity.js +245 -0
  19. package/dist/src/vector-cortex/residual/quantize.js +200 -0
  20. package/dist/src/vector-cortex/residual/stream.js +124 -0
  21. package/dist/src/vector-cortex/residual/types.js +55 -0
  22. package/dist/src/vector-cortex/shards/exact.js +134 -0
  23. package/dist/src/vector-cortex/shards/manifest.js +237 -0
  24. package/dist/src/vector-cortex/shards/semantic.js +137 -0
  25. package/dist/src/vector-cortex/shards/types.js +51 -0
  26. package/dist/vector-cortex/residual/codec.js +224 -0
  27. package/dist/vector-cortex/residual/dct.js +158 -0
  28. package/dist/vector-cortex/residual/fixture-payload.js +77 -0
  29. package/dist/vector-cortex/residual/gf256.js +182 -0
  30. package/dist/vector-cortex/residual/parity.js +245 -0
  31. package/dist/vector-cortex/residual/quantize.js +200 -0
  32. package/dist/vector-cortex/residual/stream.js +124 -0
  33. package/dist/vector-cortex/residual/types.js +55 -0
  34. package/dist/vector-cortex/shards/exact.js +134 -0
  35. package/dist/vector-cortex/shards/manifest.js +237 -0
  36. package/dist/vector-cortex/shards/semantic.js +137 -0
  37. package/dist/vector-cortex/shards/types.js +51 -0
  38. package/extensions/dashboard-client/dist/assets/{AreaChart-DqiFSnDx.js → AreaChart-n4z5w9Ox.js} +2 -2
  39. package/extensions/dashboard-client/dist/assets/{AreaChart-DqiFSnDx.js.map → AreaChart-n4z5w9Ox.js.map} +1 -1
  40. package/extensions/dashboard-client/dist/assets/{BarChart-Cqg-PQMK.js → BarChart-BLGjWWBr.js} +2 -2
  41. package/extensions/dashboard-client/dist/assets/{BarChart-Cqg-PQMK.js.map → BarChart-BLGjWWBr.js.map} +1 -1
  42. package/extensions/dashboard-client/dist/assets/{CacheTab-BPNs0xIF.js → CacheTab-CAnrKKVK.js} +2 -2
  43. package/extensions/dashboard-client/dist/assets/{CacheTab-BPNs0xIF.js.map → CacheTab-CAnrKKVK.js.map} +1 -1
  44. package/extensions/dashboard-client/dist/assets/{EventsTab-BQf7OGkf.js → EventsTab-D-GL7Ngq.js} +2 -2
  45. package/extensions/dashboard-client/dist/assets/{EventsTab-BQf7OGkf.js.map → EventsTab-D-GL7Ngq.js.map} +1 -1
  46. package/extensions/dashboard-client/dist/assets/{HealthTab-B14TaSPN.js → HealthTab-C4x5qQ8s.js} +2 -2
  47. package/extensions/dashboard-client/dist/assets/{HealthTab-B14TaSPN.js.map → HealthTab-C4x5qQ8s.js.map} +1 -1
  48. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-D8lkRoa1.js → MaintenanceTab-BSPs0eq5.js} +2 -2
  49. package/extensions/dashboard-client/dist/assets/{MaintenanceTab-D8lkRoa1.js.map → MaintenanceTab-BSPs0eq5.js.map} +1 -1
  50. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BOWtGfpx.js → MemoryMapTab-BWEUtTSu.js} +2 -2
  51. package/extensions/dashboard-client/dist/assets/{MemoryMapTab-BOWtGfpx.js.map → MemoryMapTab-BWEUtTSu.js.map} +1 -1
  52. package/extensions/dashboard-client/dist/assets/{MetricsTab-7XI9cWaX.js → MetricsTab-Dhm1c3Cx.js} +2 -2
  53. package/extensions/dashboard-client/dist/assets/{MetricsTab-7XI9cWaX.js.map → MetricsTab-Dhm1c3Cx.js.map} +1 -1
  54. package/extensions/dashboard-client/dist/assets/{OverviewTab-C9KaGYvh.js → OverviewTab-Cm6cySiQ.js} +2 -2
  55. package/extensions/dashboard-client/dist/assets/{OverviewTab-C9KaGYvh.js.map → OverviewTab-Cm6cySiQ.js.map} +1 -1
  56. package/extensions/dashboard-client/dist/assets/{ReposTab-BwESNhox.js → ReposTab-DxLN1N4K.js} +2 -2
  57. package/extensions/dashboard-client/dist/assets/{ReposTab-BwESNhox.js.map → ReposTab-DxLN1N4K.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{SessionsTab-DKH55Rda.js → SessionsTab-CZuI4ISW.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{SessionsTab-DKH55Rda.js.map → SessionsTab-CZuI4ISW.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/assets/{SetupTab-zDxf-nJd.js → SetupTab-C_0VOomm.js} +2 -2
  61. package/extensions/dashboard-client/dist/assets/{SetupTab-zDxf-nJd.js.map → SetupTab-C_0VOomm.js.map} +1 -1
  62. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-C9isog4L.js → TimeSavedCard-BhbaRLmi.js} +2 -2
  63. package/extensions/dashboard-client/dist/assets/{TimeSavedCard-C9isog4L.js.map → TimeSavedCard-BhbaRLmi.js.map} +1 -1
  64. package/extensions/dashboard-client/dist/assets/{TurnsTab-ciI6ydvj.js → TurnsTab-CXJmbjje.js} +2 -2
  65. package/extensions/dashboard-client/dist/assets/{TurnsTab-ciI6ydvj.js.map → TurnsTab-CXJmbjje.js.map} +1 -1
  66. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js +2 -0
  67. package/extensions/dashboard-client/dist/assets/VectorCortexTab-BGe9hu3r.js.map +1 -0
  68. package/extensions/dashboard-client/dist/assets/{WikiTab-DcYHc734.js → WikiTab-C5uvMCzp.js} +2 -2
  69. package/extensions/dashboard-client/dist/assets/{WikiTab-DcYHc734.js.map → WikiTab-C5uvMCzp.js.map} +1 -1
  70. package/extensions/dashboard-client/dist/assets/{button-DF8lx4bt.js → button-Cl_fxJcg.js} +2 -2
  71. package/extensions/dashboard-client/dist/assets/{button-DF8lx4bt.js.map → button-Cl_fxJcg.js.map} +1 -1
  72. package/extensions/dashboard-client/dist/assets/{card-DIoDheSZ.js → card-BH8Le5YM.js} +2 -2
  73. package/extensions/dashboard-client/dist/assets/{card-DIoDheSZ.js.map → card-BH8Le5YM.js.map} +1 -1
  74. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-BFRzeYX3.js → generateCategoricalChart-sZ6ZNtBi.js} +2 -2
  75. package/extensions/dashboard-client/dist/assets/{generateCategoricalChart-BFRzeYX3.js.map → generateCategoricalChart-sZ6ZNtBi.js.map} +1 -1
  76. package/extensions/dashboard-client/dist/assets/{index-DSZON0Yi.js → index-CX9zv8cJ.js} +3 -3
  77. package/extensions/dashboard-client/dist/assets/{index-DSZON0Yi.js.map → index-CX9zv8cJ.js.map} +1 -1
  78. package/extensions/dashboard-client/dist/assets/{switch-l4qo22mU.js → switch-CXJhcjhM.js} +2 -2
  79. package/extensions/dashboard-client/dist/assets/{switch-l4qo22mU.js.map → switch-CXJhcjhM.js.map} +1 -1
  80. package/extensions/dashboard-client/dist/assets/{toggle-DPn6td1_.js → toggle-CoLtIc6y.js} +2 -2
  81. package/extensions/dashboard-client/dist/assets/{toggle-DPn6td1_.js.map → toggle-CoLtIc6y.js.map} +1 -1
  82. package/extensions/dashboard-client/dist/assets/{useSSE-BLmolqTJ.js → useSSE-fSXho606.js} +2 -2
  83. package/extensions/dashboard-client/dist/assets/{useSSE-BLmolqTJ.js.map → useSSE-fSXho606.js.map} +1 -1
  84. package/extensions/dashboard-client/dist/index.html +1 -1
  85. package/extensions/dashboard-client/src/api/vector-cortex.ts +9 -0
  86. package/extensions/dashboard-client/src/tabs/VectorCortexTab.tsx +35 -0
  87. package/extensions/dashboard-client/src/types/vector-cortex.ts +13 -0
  88. package/extensions/dashboard-server/api-contracts/vector-cortex.ts +53 -0
  89. package/extensions/dashboard-server/routes-cache.test/_helpers.ts +2 -0
  90. package/extensions/dashboard-server/routes-rag-settings-helpers.ts +12 -0
  91. package/extensions/dashboard-server/routes-vector-cortex-helpers.ts +110 -0
  92. package/extensions/dashboard-server/routes-vector-cortex-residual.ts +60 -0
  93. package/extensions/dashboard-server/routes-vector-cortex-shards.ts +57 -0
  94. package/extensions/dashboard-server/routes-vector-cortex.ts +2 -0
  95. package/extensions/dashboard-server/routes.ts +2 -0
  96. package/extensions/dashboard-server/server.ts +46 -17
  97. package/extensions/dashboard-server/tailscale.ts +32 -0
  98. package/package.json +1 -1
  99. package/src/config/vector-cortex.ts +26 -0
  100. package/src/config.ts +2 -0
  101. package/src/vector-cortex/residual/codec.ts +292 -0
  102. package/src/vector-cortex/residual/dct.ts +166 -0
  103. package/src/vector-cortex/residual/fixture-payload.ts +90 -0
  104. package/src/vector-cortex/residual/gf256.ts +196 -0
  105. package/src/vector-cortex/residual/parity.ts +283 -0
  106. package/src/vector-cortex/residual/quantize.ts +230 -0
  107. package/src/vector-cortex/residual/stream.ts +135 -0
  108. package/src/vector-cortex/residual/types.ts +236 -0
  109. package/src/vector-cortex/shards/exact.ts +141 -0
  110. package/src/vector-cortex/shards/manifest.ts +276 -0
  111. package/src/vector-cortex/shards/semantic.ts +156 -0
  112. package/src/vector-cortex/shards/types.ts +212 -0
  113. package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js +0 -2
  114. package/extensions/dashboard-client/dist/assets/VectorCortexTab-qTZ7NWng.js.map +0 -1
@@ -34,6 +34,7 @@ export async function withServer<T>(
34
34
  fn: (port: number) => Promise<T>,
35
35
  ): Promise<T> {
36
36
  process.env.MEGACOMPACT_DASHBOARD_PORT = port;
37
+ process.env.MEGACOMPACT_DASHBOARD_HOST = "127.0.0.1";
37
38
  const child = spawn(process.execPath, [SERVER_ENTRY, dir], { stdio: "ignore" });
38
39
  try {
39
40
  await waitFor(async () => {
@@ -50,6 +51,7 @@ export async function withServer<T>(
50
51
  } finally {
51
52
  child.kill("SIGTERM");
52
53
  delete process.env.MEGACOMPACT_DASHBOARD_PORT;
54
+ delete process.env.MEGACOMPACT_DASHBOARD_HOST;
53
55
  rmSync(dir, { recursive: true, force: true });
54
56
  }
55
57
  }
@@ -349,6 +349,18 @@ export const SETTINGS: ReadonlyArray<{
349
349
  "TopologyQueryV1/RouterKeyV2 structured keys (length-delimited, unsigned-byte order, no prefix ambiguity), exact (session,generation) invalidation, stale-generation rejection (TOP_GENERATION_STALE), and the M6 router-generation-v2 copy/validate/switch migration. OFF = mode C, no structured router key / generation invalidation, byte-identical predecessor.",
350
350
  true,
351
351
  ),
352
+ boolDirect(
353
+ "MEGACOMPACT_VC4A",
354
+ "VC4A Dual-Tier Shards",
355
+ "SemanticShardV1/ExactShardV1/ShardManifestV1: partition a session ONLY at complete EventV2 boundaries; exact shards preserve every tool call/result pair, anchor and invalid UTF-8 event as original bytes (pairs never split across exact shards); manifest enforces disjoint sorted ranges + complete protected-span coverage. OFF = mode C, exact anchors/current transcript only, byte-identical predecessor.",
356
+ true,
357
+ ),
358
+ boolDirect(
359
+ "MEGACOMPACT_VC4B",
360
+ "VC4B Residual Basis Parity",
361
+ "Residual codec: orthonormal DCT-II basis + int16 block quantization + block-scoped exact correction stream + (9,6) Reed-Solomon parity shards with SHA-256 corruption detection; admission gates on encodedSize <= 95% of exact-compressed size. OFF = mode C, no residual artifact produced, byte-identical predecessor.",
362
+ true,
363
+ ),
352
364
  ],
353
365
  },
354
366
  {
@@ -0,0 +1,110 @@
1
+ /**
2
+ * routes-vector-cortex-helpers.ts — shared spawn-and-fetch harness for the
3
+ * /api/vector-cortex/* route test files.
4
+ *
5
+ * The dashboard-server.js main block fires when the entry argv includes
6
+ * "dashboard-server", so tests under dist/extensions/dashboard-server/ MUST
7
+ * spawn the server as a child process rather than import launchDashboardServer.
8
+ * Extracted from routes-vector-cortex.test.ts so per-sprint route test files
9
+ * can share the harness without each re-implementing it.
10
+ *
11
+ * Reader-only: no payload bytes are ever returned by the routes under test.
12
+ */
13
+ import { createHash } from "node:crypto";
14
+ import { rmSync, readFileSync, existsSync } from "node:fs";
15
+ import { dirname, join } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { spawn } from "node:child_process";
18
+
19
+ /** Locate the repo root (the directory holding `conformance/vector-cortex`). */
20
+ const HERE = dirname(fileURLToPath(import.meta.url));
21
+ export function repoRoot(from: string = HERE): string {
22
+ let dir = from;
23
+ for (let i = 0; i < 8; i++) {
24
+ if (existsSync(join(dir, "conformance", "vector-cortex"))) return dir;
25
+ const next = dirname(dir);
26
+ if (next === dir) break;
27
+ dir = next;
28
+ }
29
+ throw new Error("conformance corpus not found above " + from);
30
+ }
31
+
32
+ const REPO_ROOT = repoRoot();
33
+
34
+ /** SHA-256 of the REAL committed ModelManifestV1 — the health card's digest. */
35
+ export function realManifestDigest(): string {
36
+ // guardrails-allow PREVENT-PI-004: local committed asset filesystem read (loopback)
37
+ return createHash("sha256")
38
+ .update(readFileSync(join(REPO_ROOT, "assets", "vector-cortex", "encoder-v1", "manifest.json")))
39
+ .digest("hex");
40
+ }
41
+
42
+ export const SERVER_ENTRY = new URL("./server.js", import.meta.url).pathname;
43
+
44
+ export function waitFor(
45
+ cond: () => boolean | Promise<boolean>,
46
+ timeoutMs = 6000,
47
+ ): Promise<void> {
48
+ const start = Date.now();
49
+ return new Promise((resolve, reject) => {
50
+ const tick = async () => {
51
+ if (await cond()) return resolve();
52
+ if (Date.now() - start > timeoutMs) return reject(new Error("timeout"));
53
+ setTimeout(tick, 50);
54
+ };
55
+ tick();
56
+ });
57
+ }
58
+
59
+ export async function withServer<T>(
60
+ port: string,
61
+ dir: string,
62
+ fn: (port: number) => Promise<T>,
63
+ ): Promise<T> {
64
+ process.env.MEGACOMPACT_DASHBOARD_PORT = port;
65
+ // Pin loopback so the spawn-and-fetch harness stays hermetic even on a
66
+ // machine with tailscale0 (the production auto-bind would otherwise grab the
67
+ // tailnet IP and the localhost probe would connection-refuse). Tests that
68
+ // need a different host can set MEGACOMPACT_DASHBOARD_HOST before calling.
69
+ process.env.MEGACOMPACT_DASHBOARD_HOST = "127.0.0.1";
70
+ const child = spawn(process.execPath, [SERVER_ENTRY, dir], {
71
+ stdio: "ignore",
72
+ env: {
73
+ ...process.env,
74
+ MEGACOMPACT_INDEX_DIR: dir,
75
+ },
76
+ });
77
+ try {
78
+ await waitFor(async () => {
79
+ try {
80
+ const raw = JSON.parse(readFileSync(join(dir, "port.pid"), "utf-8"));
81
+ const res = await fetch(`http://localhost:${raw.port}/api/version`);
82
+ return res.ok;
83
+ } catch {
84
+ return false;
85
+ }
86
+ });
87
+ const raw = JSON.parse(readFileSync(join(dir, "port.pid"), "utf-8"));
88
+ return await fn(raw.port);
89
+ } finally {
90
+ child.kill("SIGTERM");
91
+ delete process.env.MEGACOMPACT_DASHBOARD_PORT;
92
+ delete process.env.MEGACOMPACT_DASHBOARD_HOST;
93
+ rmSync(dir, { recursive: true, force: true });
94
+ }
95
+ }
96
+
97
+ /** Seed redacted metric rows directly on disk so the server's reader sees them. */
98
+ export async function seedEval(dir: string): Promise<void> {
99
+ const { appendEvalRow } = await import(
100
+ "../../src/vector-cortex/eval/persist.js"
101
+ );
102
+ // Buckets (inclusive): 1,5,10,25,50,100,250. 1ms→cell0, 12ms→cell3
103
+ // (<=25), 250ms→cell6, 300ms→overflow.
104
+ appendEvalRow(dir, [
105
+ { session: "s1", seq: 1, event: "encode", value: 1, unit: "ms", mode: "A" },
106
+ { session: "s1", seq: 2, event: "encode", value: 250, unit: "ms", mode: "A" },
107
+ { session: "s1", seq: 3, event: "encode", value: 300, unit: "ms", mode: "A" },
108
+ { session: "s1", seq: 4, event: "encode", value: 12, unit: "ms", mode: "A" },
109
+ ]);
110
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * dashboard-server/routes-vector-cortex-residual.ts — VC4B residual basis parity
3
+ * dashboard route.
4
+ *
5
+ * Reader-only GET /api/vector-cortex/residual returning a COUNT/BYTE aggregate
6
+ * (encode attempts, admitted/rejected counts, recovery failures, encoded/exact
7
+ * byte totals) — never residual payloads, correction streams, shard bytes, or
8
+ * original source bytes. Flag-gated on MEGACOMPACT_VC4B: `enabled:false` when off
9
+ * (byte-identical to the pre-VC4B predecessor).
10
+ *
11
+ * The VC4B residual codec is PURE IN-MEMORY logic in this sprint (it has no
12
+ * durable metrics store yet), so the aggregate reports the current status
13
+ * truthfully: `enabled` reflects the flag, and the count/byte fields are zero
14
+ * until a future sprint persists a metrics store. This route is the seam that
15
+ * sprint will populate. Non-fatal: a missing state dir degrades to
16
+ * `enabled:false`.
17
+ *
18
+ * Guardrails: PREVENT-PI-004 (local filesystem read only / in-process state),
19
+ * PREVENT-011 (no `any`), reader-only aggregate (counts/bytes only).
20
+ */
21
+
22
+ import type { IncomingMessage, ServerResponse } from "node:http";
23
+ import type { RouteContext } from "./routes-core.js";
24
+ import { VC4B_ENABLED } from "../../src/config.js";
25
+ import { sendJson } from "./routes-vector-cortex-shared.js";
26
+ import type { VectorCortexResidualView } from "./api-contracts/vector-cortex.js";
27
+
28
+ /**
29
+ * Reader-only GET /api/vector-cortex/residual (VC4B).
30
+ */
31
+ export function handleVectorCortexResidual(
32
+ req: IncomingMessage,
33
+ res: ServerResponse,
34
+ _ctx: RouteContext,
35
+ ): boolean {
36
+ const url = req.url ?? "";
37
+ const path = url.split("?")[0] ?? url;
38
+ if (path !== "/api/vector-cortex/residual") return false;
39
+ if (req.method !== "GET") {
40
+ // Reader-only path: cannot be "off" without a GET; it is genuinely read-only.
41
+ sendJson(res, 405, { error: "method_not_allowed" });
42
+ return true;
43
+ }
44
+
45
+ const enabled = VC4B_ENABLED();
46
+ const body: VectorCortexResidualView = {
47
+ enabled,
48
+ // No durable residual metrics store is staged yet in this sprint (pure
49
+ // in-memory encode), so the aggregates are truthfully zero.
50
+ encodeAttempts: 0,
51
+ admittedCount: 0,
52
+ rejectedCount: 0,
53
+ recoveryFailures: 0,
54
+ encodedByteTotal: 0,
55
+ exactByteTotal: 0,
56
+ updatedAt: new Date().toISOString(),
57
+ };
58
+ sendJson(res, 200, body);
59
+ return true;
60
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * dashboard-server/routes-vector-cortex-shards.ts — VC4A dual-tier shard
3
+ * dashboard route.
4
+ *
5
+ * Reader-only GET /api/vector-cortex/shards returning a COUNT/BYTE aggregate
6
+ * (semantic shards, exact shards, protected byte total) — never shard payloads,
7
+ * verbatim exact bytes, or prompt text. Flag-gated on MEGACOMPACT_VC4A:
8
+ * `enabled:false` when off (byte-identical to the pre-VC4A predecessor).
9
+ *
10
+ * The VC4A shard partition is PURE IN-MEMORY logic in this sprint (it has no
11
+ * durable manifest store yet), so the aggregate reports the current status
12
+ * truthfully: `enabled` reflects the flag, and the count/byte fields are zero
13
+ * until a future sprint persists a staged manifest. This route is the seam that
14
+ * sprint will populate. Non-fatal: a missing state dir degrades to
15
+ * `enabled:false`.
16
+ *
17
+ * Guardrails: PREVENT-PI-004 (local filesystem read only / in-process state),
18
+ * PREVENT-011 (no `any`), reader-only aggregate (counts/bytes only).
19
+ */
20
+
21
+ import type { IncomingMessage, ServerResponse } from "node:http";
22
+ import type { RouteContext } from "./routes-core.js";
23
+ import { VC4A_ENABLED } from "../../src/config.js";
24
+ import { sendJson } from "./routes-vector-cortex-shared.js";
25
+ import type { VectorCortexShardsView } from "./api-contracts/vector-cortex.js";
26
+
27
+ /**
28
+ * Reader-only GET /api/vector-cortex/shards (VC4A).
29
+ */
30
+ export function handleVectorCortexShards(
31
+ req: IncomingMessage,
32
+ res: ServerResponse,
33
+ _ctx: RouteContext,
34
+ ): boolean {
35
+ const url = req.url ?? "";
36
+ const path = url.split("?")[0] ?? url;
37
+ if (path !== "/api/vector-cortex/shards") return false;
38
+ if (req.method !== "GET") {
39
+ // Reader-only path: cannot be "off" without a GET; it is genuinely read-only.
40
+ sendJson(res, 405, { error: "method_not_allowed" });
41
+ return true;
42
+ }
43
+
44
+ const enabled = VC4A_ENABLED();
45
+ const body: VectorCortexShardsView = {
46
+ enabled,
47
+ // No durable shard manifest is staged yet in this sprint (pure in-memory
48
+ // partition), so the aggregates are truthfully zero.
49
+ semanticCount: 0,
50
+ exactCount: 0,
51
+ byteTotal: 0,
52
+ protectedByteTotal: 0,
53
+ updatedAt: new Date().toISOString(),
54
+ };
55
+ sendJson(res, 200, body);
56
+ return true;
57
+ }
@@ -19,3 +19,5 @@ export { handleVectorCortexHealth, handleVectorCortexBreakersReset } from "./rou
19
19
  export { handleVectorCortexLedger } from "./routes-vector-cortex-ledger.js";
20
20
  export { handleVectorCortexTopology } from "./routes-vector-cortex-topology.js";
21
21
  export { handleVectorCortexQuery } from "./routes-vector-cortex-query.js";
22
+ export { handleVectorCortexShards } from "./routes-vector-cortex-shards.js";
23
+ export { handleVectorCortexResidual } from "./routes-vector-cortex-residual.js";
@@ -47,4 +47,6 @@ export {
47
47
  handleVectorCortexLedger,
48
48
  handleVectorCortexTopology,
49
49
  handleVectorCortexQuery,
50
+ handleVectorCortexShards,
51
+ handleVectorCortexResidual,
50
52
  } from "./routes-vector-cortex.js";
@@ -25,6 +25,7 @@ import { createRequire } from "node:module";
25
25
 
26
26
  import { NEW_UI } from "../../src/config.js";
27
27
  import { log, setLogPath, setDashboardServerVersion } from "./state.js";
28
+ import { detectTailscaleIP } from "./tailscale.js";
28
29
  import {
29
30
  buildRouteContext,
30
31
  handleIndex,
@@ -62,6 +63,8 @@ import {
62
63
  handleVectorCortexLedger,
63
64
  handleVectorCortexTopology,
64
65
  handleVectorCortexQuery,
66
+ handleVectorCortexShards,
67
+ handleVectorCortexResidual,
65
68
  handleStatic,
66
69
  } from "./routes.js";
67
70
 
@@ -231,15 +234,31 @@ export async function launchDashboardServer(
231
234
  detectCrossRepoDrift,
232
235
  });
233
236
 
237
+ // Bind host resolution: explicit MEGACOMPACT_DASHBOARD_HOST override wins;
238
+ // otherwise auto-bind to the Tailscale interface (tailnet access); fall back
239
+ // to loopback when Tailscale is absent. 0.0.0.0 means "all interfaces" and
240
+ // opts into permissive CORS below.
241
+ const host =
242
+ process.env.MEGACOMPACT_DASHBOARD_HOST ??
243
+ detectTailscaleIP() ??
244
+ "127.0.0.1";
245
+ const allInterfaces = host === "0.0.0.0";
246
+
247
+ // guardrails-allow PREVENT-PI-004: optional, user-triggered /dashboard server (tailnet-local via Tailscale mesh or loopback); no remote outbound calls.
234
248
  const server = createServer((req: IncomingMessage, res: ServerResponse) => {
235
- // guardrails-allow PREVENT-PI-004: optional, user-triggered /dashboard localhost server (loopback-only) CORS restricted to same-origin localhost browsers.
236
- // CORS for local access — restricted to loopback origins (the dashboard server only binds to localhost).
249
+ // CORS for local access — restricted to loopback/same-origin tailnet
250
+ // origins (the dashboard server binds to localhost or the tailscale IP).
251
+ // With MEGACOMPACT_DASHBOARD_HOST=0.0.0.0 the user opted into
252
+ // all-interfaces binding, so we allow any origin.
237
253
  const origin = req.headers.origin;
238
- if (
239
- typeof origin === "string" &&
240
- /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin)
241
- ) {
242
- res.setHeader("Access-Control-Allow-Origin", origin);
254
+ const originAllowed =
255
+ allInterfaces ||
256
+ (typeof origin === "string" &&
257
+ new RegExp(
258
+ `^http://(localhost|127\\.0\\.0\\.1|::1|${host.replace(/\./g, "\\.")})(:\\d+)?$`,
259
+ ).test(origin));
260
+ if (originAllowed) {
261
+ res.setHeader("Access-Control-Allow-Origin", origin ?? "*");
243
262
  res.setHeader("Vary", "Origin");
244
263
  }
245
264
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
@@ -287,6 +306,8 @@ export async function launchDashboardServer(
287
306
  if (handleVectorCortexLedger(req, res, ctx)) return;
288
307
  if (handleVectorCortexTopology(req, res, ctx)) return;
289
308
  if (handleVectorCortexQuery(req, res, ctx)) return;
309
+ if (handleVectorCortexShards(req, res, ctx)) return;
310
+ if (handleVectorCortexResidual(req, res, ctx)) return;
290
311
  handleStatic(req, res, ctx);
291
312
  });
292
313
 
@@ -310,20 +331,28 @@ export async function launchDashboardServer(
310
331
  }
311
332
  });
312
333
 
313
- server.listen(port, "127.0.0.1", () => {
314
- const url = `http://localhost:${port}`; // guardrails-allow PREVENT-PI-004: localhost dashboard URL (loopback-only)
315
- log("server running", { url });
334
+ server.listen(port, host, () => {
335
+ // When bound to the loopback, keep the legacy localhost URL so the
336
+ // user's browser (which resolves localhost ::1 or 127.0.0.1) works.
337
+ // When bound to a tailnet/tailscale IP, surface that address instead.
338
+ const url =
339
+ host === "127.0.0.1"
340
+ ? `http://localhost:${port}`
341
+ : `http://${host}:${port}`; // guardrails-allow PREVENT-PI-004: dashboard URL (tailnet-local via Tailscale mesh or loopback)
342
+ log("server running", { url, host });
316
343
  // eslint-disable-next-line no-console
317
344
  console.log(`[mega-compact] dashboard server running: ${url}`);
318
345
 
319
- // v0.8.2: also bind the IPv6 loopback (::1). On many systems `localhost`
320
- // resolves to ::1 first (see /etc/hosts), so an IPv4-only bind makes the
321
- // browser hit ::1:port and get connection refused. PREVENT-PI-004
322
- // (loopback-only) means BOTH 127.0.0.1 and ::1. Non-fatal: IPv4-only
323
- // hosts or a ::1 already in use just skip the mirror.
346
+ // v0.8.2: also bind the IPv6 loopback (::1) when bound to the IPv4
347
+ // loopback. On many systems `localhost` resolves to ::1 first (see
348
+ // /etc/hosts), so an IPv4-only bind makes the browser hit ::1:port and
349
+ // get connection refused. PREVENT-PI-004 (loopback-only) means BOTH
350
+ // 127.0.0.1 and ::1. When bound to a tailscale/0.0.0.0 host, we do NOT
351
+ // bind ::1 — the tailnet address is what the user reaches. Non-fatal:
352
+ // IPv4-only hosts or a ::1 already in use just skip the mirror.
324
353
  let v6: ReturnType<typeof createServer> | undefined;
325
354
  const v4Handler = server.listeners("request")[0];
326
- if (v4Handler) {
355
+ if (host === "127.0.0.1" && v4Handler) {
327
356
  v6 = createServer((r, s) =>
328
357
  (v4Handler as (a: IncomingMessage, b: ServerResponse) => void).call(
329
358
  server,
@@ -338,7 +367,7 @@ export async function launchDashboardServer(
338
367
  message: e.message,
339
368
  }),
340
369
  );
341
- v6.listen(port, "::1", () => log("ipv6 loopback bound", { port })); // guardrails-allow PREVENT-PI-004: IPv6 loopback (::1) mirror of the localhost dashboard server
370
+ v6.listen(port, "::1", () => log("ipv6 loopback bound", { port })); // guardrails-allow PREVENT-PI-004: IPv6 loopback (::1) mirror of the dashboard server
342
371
  }
343
372
 
344
373
  // Write port.pid
@@ -1,3 +1,5 @@
1
+ import { networkInterfaces } from "node:os";
2
+
1
3
  export function setupTailscaleServe(port = 3000, httpsPort = 443): boolean {
2
4
  // Tailscale serve: exposes localhost dashboard securely.
3
5
  // Only activates when TAILSCALE_ENABLED=1 is set.
@@ -5,3 +7,33 @@ export function setupTailscaleServe(port = 3000, httpsPort = 443): boolean {
5
7
  console.log(`[tailscale] Serve enabled on port ${port} (https:${httpsPort})`);
6
8
  return true;
7
9
  }
10
+
11
+ // CGNAT block used by Tailscale for client addresses (100.64.0.0/10).
12
+ const TAILSCALE_CGNAT_PREFIX = "100.";
13
+
14
+ /**
15
+ * Detect the IPv4 address Tailscale has assigned to this host, so the dashboard
16
+ * server can auto-bind to the tailnet interface and be reachable from other
17
+ * devices on the tailnet. Returns null when Tailscale is not present.
18
+ *
19
+ * The default Tailscale interface name is `tailscale0` on Linux and `Tailscale`
20
+ * on macOS/Windows. We prefer an address inside Tailscale's CGNAT range
21
+ * (100.64.0.0/10) when one exists; otherwise we return the first IPv4 address
22
+ * found on the interface.
23
+ */
24
+ export function detectTailscaleIP(): string | null {
25
+ const ifaces = networkInterfaces();
26
+ const candidates: Array<string> = [];
27
+ for (const [name, addrs] of Object.entries(ifaces)) {
28
+ if (name !== "tailscale0" && name !== "Tailscale") continue;
29
+ if (!addrs) continue;
30
+ for (const addr of addrs) {
31
+ if (addr.family === "IPv4") {
32
+ candidates.push(addr.address);
33
+ }
34
+ }
35
+ }
36
+ if (candidates.length === 0) return null;
37
+ const cgnat = candidates.find((ip) => ip.startsWith(TAILSCALE_CGNAT_PREFIX));
38
+ return cgnat ?? candidates[0];
39
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.19.3",
3
+ "version": "0.20.1",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -134,6 +134,32 @@ export const VC3B_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC3B");
134
134
  */
135
135
  export const VC3C_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC3C");
136
136
 
137
+ /**
138
+ * VC4A — dual-tier shard contract (SemanticShardV1 / ExactShardV1 /
139
+ * ShardManifestV1).
140
+ * Default ON. `MEGACOMPACT_VC4A=0` disables and is byte-identical to the
141
+ * predecessor (mode C: exact anchors/current transcript only, no semantic or
142
+ * exact shard manifest is assembled or emitted, zero
143
+ * `vector_cortex_shard_manifest_built` / `vector_cortex_protected_span_rejected`
144
+ * emissions; the predecessor derived pointer and goldens are unchanged). The
145
+ * real consumers are the shard assembly seam (manifest.ts) and the reader-only
146
+ * dashboard shards aggregate view.
147
+ */
148
+ export const VC4A_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC4A");
149
+
150
+ /**
151
+ * VC4B — residual codec and numeric parity (ResidualCodecV1 / ParityShardV1).
152
+ * Default ON. `MEGACOMPACT_VC4B=0` disables and is byte-identical to the
153
+ * predecessor (mode C: no residual artifact is admitted, the exact compressed
154
+ * payload / ledger bytes remain the only representation, zero
155
+ * `vector_cortex_residual_admitted` / `vector_cortex_parity_recovery_failed`
156
+ * emissions; the VC4A shard manifest and its goldens are unchanged). The real
157
+ * consumers are the codec admission seam (codec.ts) and the reader-only
158
+ * dashboard residual aggregate view. The codec math itself is PURE — flag OFF
159
+ * gates the reporter/admission seam, never the arithmetic.
160
+ */
161
+ export const VC4B_ENABLED = (): boolean => sprintFlag("MEGACOMPACT_VC4B");
162
+
137
163
  // ---------------------------------------------------------------------------
138
164
  // Breaker state machine constants (TRIAD_RESILIENCE.md §breaker).
139
165
  // Rolled numbers for one 60s window; VC0C consumes these at its breaker seam.
package/src/config.ts CHANGED
@@ -163,6 +163,8 @@ export {
163
163
  VC3A_ENABLED,
164
164
  VC3B_ENABLED,
165
165
  VC3C_ENABLED,
166
+ VC4A_ENABLED,
167
+ VC4B_ENABLED,
166
168
  BREAKER_WINDOW_MS,
167
169
  BREAKER_MIN_ATTEMPTS,
168
170
  BREAKER_PERF_FAILURES,