counterparts 0.1.0

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 (195) hide show
  1. package/CONSTITUTION.md +68 -0
  2. package/LICENSE +21 -0
  3. package/README.md +348 -0
  4. package/docs/ELI5.md +84 -0
  5. package/docs/QUICKSTART.md +1258 -0
  6. package/docs/module-map.md +81 -0
  7. package/package.json +63 -0
  8. package/src/adapters/claude-code/CONTRACT.md +606 -0
  9. package/src/adapters/claude-code/INTERFACE-GAPS.md +655 -0
  10. package/src/adapters/claude-code/NOTES.md +1055 -0
  11. package/src/adapters/claude-code/bin/hook.ts +820 -0
  12. package/src/adapters/claude-code/bin/runner.ts +522 -0
  13. package/src/adapters/claude-code/config.ts +778 -0
  14. package/src/adapters/claude-code/credentials.ts +199 -0
  15. package/src/adapters/claude-code/doctor.ts +2557 -0
  16. package/src/adapters/claude-code/embed-client.ts +617 -0
  17. package/src/adapters/claude-code/hooks.ts +2240 -0
  18. package/src/adapters/claude-code/index.ts +224 -0
  19. package/src/adapters/claude-code/interpret-client.ts +395 -0
  20. package/src/adapters/claude-code/page-writer.ts +462 -0
  21. package/src/adapters/claude-code/primacy.ts +162 -0
  22. package/src/adapters/claude-code/spawn.ts +241 -0
  23. package/src/adapters/claude-code/standdown.ts +536 -0
  24. package/src/adapters/claude-code/transcript.ts +661 -0
  25. package/src/adapters/claude-code/vectors.ts +415 -0
  26. package/src/adapters/cli/CONTRACT.md +255 -0
  27. package/src/adapters/cli/INTERFACE-GAPS.md +350 -0
  28. package/src/adapters/cli/NOTES.md +936 -0
  29. package/src/adapters/cli/bin/counterparts.ts +74 -0
  30. package/src/adapters/cli/commands.ts +6095 -0
  31. package/src/adapters/cli/export.ts +766 -0
  32. package/src/adapters/cli/index.ts +103 -0
  33. package/src/adapters/cli/install.ts +670 -0
  34. package/src/adapters/cli/removal.ts +1186 -0
  35. package/src/adapters/cli/repair-dates.ts +659 -0
  36. package/src/adapters/cli/self-page.ts +229 -0
  37. package/src/adapters/cli/snapshot.ts +279 -0
  38. package/src/adapters/cli/start-fresh.ts +1228 -0
  39. package/src/adapters/config-path.ts +342 -0
  40. package/src/adapters/dashboard/CONTRACT.md +67 -0
  41. package/src/adapters/dashboard/INTERFACE-GAPS.md +139 -0
  42. package/src/adapters/dashboard/NOTES.md +474 -0
  43. package/src/adapters/dashboard/activity.ts +121 -0
  44. package/src/adapters/dashboard/ansi.ts +82 -0
  45. package/src/adapters/dashboard/bin/dashboard.ts +479 -0
  46. package/src/adapters/dashboard/browse.ts +298 -0
  47. package/src/adapters/dashboard/identity.ts +182 -0
  48. package/src/adapters/dashboard/index.ts +183 -0
  49. package/src/adapters/dashboard/layout.ts +149 -0
  50. package/src/adapters/dashboard/registries.ts +291 -0
  51. package/src/adapters/dashboard/resolve.ts +206 -0
  52. package/src/adapters/dashboard/source.ts +48 -0
  53. package/src/adapters/dashboard/status.ts +327 -0
  54. package/src/adapters/dashboard/stories.ts +194 -0
  55. package/src/adapters/dashboard/web/app.html +1731 -0
  56. package/src/adapters/dashboard/web/brain.html +463 -0
  57. package/src/adapters/dashboard/web/fired.ts +31 -0
  58. package/src/adapters/dashboard/web/flow.ts +457 -0
  59. package/src/adapters/dashboard/web/narrate.ts +1042 -0
  60. package/src/adapters/dashboard/web/reveal.ts +135 -0
  61. package/src/adapters/dashboard/web/server.ts +287 -0
  62. package/src/adapters/dashboard/web/views.ts +1744 -0
  63. package/src/adapters/expansions.ts +569 -0
  64. package/src/adapters/fired.ts +1580 -0
  65. package/src/adapters/mcp/CONTRACT.md +240 -0
  66. package/src/adapters/mcp/INTERFACE-GAPS.md +271 -0
  67. package/src/adapters/mcp/NOTES.md +205 -0
  68. package/src/adapters/mcp/bin/serve.ts +349 -0
  69. package/src/adapters/mcp/deliberate.ts +619 -0
  70. package/src/adapters/mcp/index.ts +101 -0
  71. package/src/adapters/mcp/protocol.ts +170 -0
  72. package/src/adapters/mcp/server.ts +1740 -0
  73. package/src/adapters/mcp/stdio.ts +56 -0
  74. package/src/adapters/mcp/tools.ts +779 -0
  75. package/src/adapters/scopes.ts +657 -0
  76. package/src/adapters/sessions.ts +402 -0
  77. package/src/adapters/snapshots.ts +1069 -0
  78. package/src/adapters/stance-env.ts +137 -0
  79. package/src/core/associate/CONTRACT.md +118 -0
  80. package/src/core/associate/INTERFACE-GAPS.md +173 -0
  81. package/src/core/associate/NOTES.md +194 -0
  82. package/src/core/associate/buffer.ts +66 -0
  83. package/src/core/associate/edges.ts +188 -0
  84. package/src/core/associate/index.ts +570 -0
  85. package/src/core/associate/pending.ts +383 -0
  86. package/src/core/associate/spread.ts +149 -0
  87. package/src/core/associate/tunables.ts +123 -0
  88. package/src/core/bridge.ts +272 -0
  89. package/src/core/briefing.ts +67 -0
  90. package/src/core/counterpart.ts +3855 -0
  91. package/src/core/encode/CONTRACT.md +151 -0
  92. package/src/core/encode/INTERFACE-GAPS.md +135 -0
  93. package/src/core/encode/NOTES.md +146 -0
  94. package/src/core/encode/aliases.ts +71 -0
  95. package/src/core/encode/battery.ts +284 -0
  96. package/src/core/encode/chunk.ts +265 -0
  97. package/src/core/encode/emotion.ts +119 -0
  98. package/src/core/encode/floor.ts +76 -0
  99. package/src/core/encode/index.ts +100 -0
  100. package/src/core/encode/precision.ts +162 -0
  101. package/src/core/encode/preselect.ts +269 -0
  102. package/src/core/encode/salience.ts +108 -0
  103. package/src/core/encode/secrets.ts +265 -0
  104. package/src/core/encode/tunables.ts +99 -0
  105. package/src/core/encode/types.ts +286 -0
  106. package/src/core/encode/words.ts +75 -0
  107. package/src/core/handoff/CONTRACT.md +199 -0
  108. package/src/core/handoff/INTERFACE-GAPS.md +166 -0
  109. package/src/core/handoff/NOTES.md +206 -0
  110. package/src/core/handoff/index.ts +957 -0
  111. package/src/core/mint.ts +279 -0
  112. package/src/core/observer.ts +28 -0
  113. package/src/core/physics/CONTRACT.md +341 -0
  114. package/src/core/physics/NOTES.md +155 -0
  115. package/src/core/physics/clock.ts +51 -0
  116. package/src/core/physics/index.ts +1054 -0
  117. package/src/core/prospective/CONTRACT.md +137 -0
  118. package/src/core/prospective/INTERFACE-GAPS.md +112 -0
  119. package/src/core/prospective/NOTES.md +160 -0
  120. package/src/core/prospective/derive.ts +188 -0
  121. package/src/core/prospective/index.ts +1030 -0
  122. package/src/core/prospective/tunables.ts +72 -0
  123. package/src/core/prospective/windows.ts +187 -0
  124. package/src/core/recall/CONTRACT.md +326 -0
  125. package/src/core/recall/INTERFACE-GAPS.md +163 -0
  126. package/src/core/recall/NOTES.md +472 -0
  127. package/src/core/recall/activate.ts +521 -0
  128. package/src/core/recall/cues.ts +275 -0
  129. package/src/core/recall/gate.ts +441 -0
  130. package/src/core/recall/index.ts +692 -0
  131. package/src/core/recall/probe.ts +239 -0
  132. package/src/core/recall/reference.ts +201 -0
  133. package/src/core/recall/render.ts +285 -0
  134. package/src/core/recall/session.ts +403 -0
  135. package/src/core/recall/tunables.ts +329 -0
  136. package/src/core/remember/CONTRACT.md +293 -0
  137. package/src/core/remember/INTERFACE-GAPS.md +189 -0
  138. package/src/core/remember/NOTES.md +373 -0
  139. package/src/core/remember/fallback.ts +452 -0
  140. package/src/core/remember/index.ts +103 -0
  141. package/src/core/remember/owner-strike-seam.ts +479 -0
  142. package/src/core/remember/proposals.ts +609 -0
  143. package/src/core/remember/spans.ts +1310 -0
  144. package/src/core/remember/tunables.ts +111 -0
  145. package/src/core/remember/updates.ts +198 -0
  146. package/src/core/retrieval.ts +96 -0
  147. package/src/core/revision.ts +441 -0
  148. package/src/core/schemas/CONTRACT.md +190 -0
  149. package/src/core/schemas/INTERFACE-GAPS.md +172 -0
  150. package/src/core/schemas/NOTES.md +260 -0
  151. package/src/core/schemas/aliases.ts +160 -0
  152. package/src/core/schemas/index.ts +1459 -0
  153. package/src/core/schemas/tunables.ts +44 -0
  154. package/src/core/schemas/types.ts +387 -0
  155. package/src/core/self/CONTRACT.md +459 -0
  156. package/src/core/self/INTERFACE-GAPS.md +284 -0
  157. package/src/core/self/NOTES.md +1057 -0
  158. package/src/core/self/briefing.ts +980 -0
  159. package/src/core/self/episodes.ts +483 -0
  160. package/src/core/self/freeze.ts +103 -0
  161. package/src/core/self/identity.ts +604 -0
  162. package/src/core/self/index.ts +2130 -0
  163. package/src/core/self/journal-file.ts +760 -0
  164. package/src/core/self/page.ts +404 -0
  165. package/src/core/self/tunables.ts +244 -0
  166. package/src/core/self/writer.ts +714 -0
  167. package/src/core/sleep/CONTRACT.md +298 -0
  168. package/src/core/sleep/INTERFACE-GAPS.md +262 -0
  169. package/src/core/sleep/NOTES.md +770 -0
  170. package/src/core/sleep/briefing.ts +86 -0
  171. package/src/core/sleep/consolidate.ts +241 -0
  172. package/src/core/sleep/cycle.ts +598 -0
  173. package/src/core/sleep/decay.ts +237 -0
  174. package/src/core/sleep/dedup.ts +373 -0
  175. package/src/core/sleep/index.ts +112 -0
  176. package/src/core/sleep/log.ts +116 -0
  177. package/src/core/sleep/markers.ts +164 -0
  178. package/src/core/sleep/prune.ts +170 -0
  179. package/src/core/sleep/strength-cache.ts +176 -0
  180. package/src/core/sleep/tunables.ts +135 -0
  181. package/src/core/sleep/types.ts +542 -0
  182. package/src/core/store/CONTRACT.md +446 -0
  183. package/src/core/store/NOTES.md +1068 -0
  184. package/src/core/store/cache.ts +709 -0
  185. package/src/core/store/db.ts +275 -0
  186. package/src/core/store/errors.ts +134 -0
  187. package/src/core/store/index.ts +2450 -0
  188. package/src/core/store/operational.ts +610 -0
  189. package/src/core/store/owner-op-seam.ts +428 -0
  190. package/src/core/store/paths.ts +494 -0
  191. package/src/core/store/prose.ts +165 -0
  192. package/src/core/store/render.ts +87 -0
  193. package/src/core/store/walk-seam.ts +78 -0
  194. package/src/core/types.ts +68 -0
  195. package/tools/install-loop/run.sh +1063 -0
@@ -0,0 +1,135 @@
1
+ /**
2
+ * One rule, in one place: **the web views withhold a confidential memory exactly
3
+ * the way every other surface withholds it.**
4
+ *
5
+ * `recall/activate.ts#isConfidential` is the predicate the surfacing gate uses;
6
+ * a dashboard that resolved the same id straight to its first line would be the
7
+ * one screen in the system where the rule does not hold — and it would be the
8
+ * screen that gets screenshotted. So every id that becomes text on a web page
9
+ * goes through `reveal()` rather than through `resolveRef` directly, and a
10
+ * confidential row comes back as a NAMED withholding: its id, its physics, its
11
+ * band, its place in the constellation, all still visible — only the words gone.
12
+ *
13
+ * That distinction is the point. Withholding the text is not hiding the memory:
14
+ * a memory the owner cannot see the EXISTENCE of would be worse than one whose
15
+ * sentence is on screen (constitution line 16). The label says which it is.
16
+ *
17
+ * Render-time, like everything else here (CONTRACT §3, scar §2.20): nothing
18
+ * below caches, and a memory made confidential after a page loaded stops
19
+ * resolving on the next request.
20
+ */
21
+ import { isConfidential } from "../../../core/recall/index.js";
22
+ import type { ProseDoc, Store } from "../../../core/store/index.js";
23
+ import { gistOf, looksLikeId, resolvePayload, resolveRef } from "../resolve.js";
24
+ import type { ResolvedRef } from "../resolve.js";
25
+
26
+ /** What a confidential row says instead of its first line. */
27
+ export const WITHHELD = "[confidential — withheld here as it is withheld everywhere]";
28
+
29
+ export interface Revealed {
30
+ readonly id: string;
31
+ readonly headId: string | null;
32
+ readonly state: ResolvedRef["state"];
33
+ readonly present: boolean;
34
+ /** The current text, or null when absent OR withheld. */
35
+ readonly text: string | null;
36
+ /** True when the row is real and its words are deliberately not shown. */
37
+ readonly confidential: boolean;
38
+ /** Ready to print: the text, a named absence, or the withholding. */
39
+ readonly label: string;
40
+ }
41
+
42
+ function confidentialAt(store: Store, id: string): boolean {
43
+ try {
44
+ return isConfidential(store.readProse(id));
45
+ } catch {
46
+ // Unreadable is an absence, not a secret; `resolveRef` already named it.
47
+ return false;
48
+ }
49
+ }
50
+
51
+ /** Resolve one id for display. The only id-to-text path the web views use. */
52
+ export function reveal(store: Store, id: string | null | undefined, width = 64): Revealed {
53
+ const ref = resolveRef(store, id, width);
54
+ if (!ref.present || ref.headId === null) {
55
+ return {
56
+ id: ref.id,
57
+ headId: ref.headId,
58
+ state: ref.state,
59
+ present: false,
60
+ text: null,
61
+ confidential: false,
62
+ label: ref.label,
63
+ };
64
+ }
65
+ if (confidentialAt(store, ref.headId)) {
66
+ return {
67
+ id: ref.id,
68
+ headId: ref.headId,
69
+ state: ref.state,
70
+ present: true,
71
+ text: null,
72
+ confidential: true,
73
+ label: WITHHELD,
74
+ };
75
+ }
76
+ return {
77
+ id: ref.id,
78
+ headId: ref.headId,
79
+ state: ref.state,
80
+ present: true,
81
+ text: ref.text,
82
+ confidential: false,
83
+ label: ref.label,
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Resolve an id at ITS OWN address, without following the forwarding chain.
89
+ *
90
+ * "It began as X" and "it now says Y" are unsayable without reading both ends,
91
+ * and a superseded belief's prose is retained by design for exactly this. Still
92
+ * render-time: an id whose own row is gone comes back as a named absence.
93
+ */
94
+ export function revealHere(store: Store, id: string | null | undefined, width = 64): Revealed {
95
+ const ref = resolveRef(store, id, { width, follow: false });
96
+ if (!ref.present || ref.headId === null) {
97
+ return { id: ref.id, headId: ref.headId, state: ref.state, present: false, text: null, confidential: false, label: ref.label };
98
+ }
99
+ if (confidentialAt(store, ref.headId)) {
100
+ return { id: ref.id, headId: ref.headId, state: ref.state, present: true, text: null, confidential: true, label: WITHHELD };
101
+ }
102
+ return { id: ref.id, headId: ref.headId, state: ref.state, present: true, text: ref.text, confidential: false, label: ref.label };
103
+ }
104
+
105
+ /** The short form a feed line or a tooltip wants: text, or the reason there is none. */
106
+ export function shortOf(store: Store, id: string | null | undefined, width = 56): string {
107
+ const r = reveal(store, id, width);
108
+ return r.text ?? r.label;
109
+ }
110
+
111
+ /**
112
+ * A payload, rendered — the same job as `resolvePayload`, but every id-shaped
113
+ * value goes through `reveal` so a confidential memory named inside an event
114
+ * detail is withheld there too. The modal is the last place a withheld sentence
115
+ * could leak back in, which is exactly why it is worth a second pass.
116
+ */
117
+ export function revealPayload(
118
+ store: Store,
119
+ payload: Record<string, unknown>,
120
+ width = 40,
121
+ ): { key: string; value: string }[] {
122
+ return resolvePayload(store, payload, width).map(({ key, value }) => {
123
+ const raw = payload[key];
124
+ if (!looksLikeId(raw)) return { key, value };
125
+ const r = reveal(store, raw, width);
126
+ return { key, value: r.confidential ? `${WITHHELD} [${raw}]` : value };
127
+ });
128
+ }
129
+
130
+ /** A doc already in hand — the list paths read the row once and reuse it. */
131
+ export function gistOfDoc(doc: ProseDoc, width = 64): { text: string; confidential: boolean } {
132
+ return isConfidential(doc)
133
+ ? { text: WITHHELD, confidential: true }
134
+ : { text: gistOf(doc, width), confidential: false };
135
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * The local web dashboard's server — `node:http`, one page, JSON under `/api`.
3
+ *
4
+ * CONTRACT OQ1 asked terminal or local web and the build answered "terminal, for
5
+ * now" with a named revision condition: *the moment the owner wants to click.*
6
+ * That moment arrived (owner ruling 2026-09-04, `NOTES.md`), and nothing in the
7
+ * answer's reasoning is discarded here — the guarantees the terminal shape made
8
+ * cheap to prove are the ones this file is built to keep provable:
9
+ *
10
+ * - **`router()` is a pure function of an opened observer source.** It takes
11
+ * the source, returns a plain `{status, headers, body}`, and binds no
12
+ * socket. Every endpoint is therefore testable exactly the way a view
13
+ * function was — including "the data dir is byte-identical after every
14
+ * endpoint", which is the observer guarantee restated for a web adapter.
15
+ * - **One source, opened once, in observer mode by construction.**
16
+ * `Dashboard.open` sets `observer: true` itself and `sourceOf` refuses a
17
+ * Counterpart that is not one, so a request cannot reach a writable brain
18
+ * even by mistake. SQLite readers see committed writes, so a long-lived
19
+ * handle is fresh without reopening the store on every request.
20
+ * - **`node:http`, not `Bun.serve`.** The core targets Node and Bun both; a
21
+ * dashboard that only starts under one runtime would foreclose the other for
22
+ * no gain (owner ruling, same date).
23
+ *
24
+ * ## The two refusals
25
+ *
26
+ * **127.0.0.1 only.** The model of you stays on your machine.
27
+ *
28
+ * **A Host-header allowlist**, checked before any view is computed. Binding to
29
+ * loopback stops remote connections; it does NOT stop a page in the owner's own
30
+ * browser rebinding its origin to 127.0.0.1 and issuing same-origin fetches with
31
+ * an attacker Host header (v1's audit finding #30, inherited as a scar rather
32
+ * than as code). Only `localhost`, `127.0.0.1` and `[::1]`, with an optional
33
+ * port, are accepted.
34
+ *
35
+ * ## The filesystem exception, named
36
+ *
37
+ * This is the ONE file in `adapters/dashboard/` that imports `node:fs`, and it
38
+ * imports exactly `readFileSync`, to serve two static HTML files that ship
39
+ * beside it. The directory-wide ban exists to mechanize "no memory body text is
40
+ * persisted into dashboard state" — there is no state file because nothing here
41
+ * can open one — and a read-only import preserves that exactly.
42
+ * `test/dashboard.test.ts` encodes the exception per-file and asserts the
43
+ * binding, so it cannot quietly widen into a write.
44
+ */
45
+ import { readFileSync } from "node:fs";
46
+ import { createServer } from "node:http";
47
+ import type { Server } from "node:http";
48
+ import { dirname, join } from "node:path";
49
+ import { fileURLToPath } from "node:url";
50
+
51
+ import { isStoreError, today as todayUtc } from "../../../core/store/index.js";
52
+ import { Dashboard } from "../index.js";
53
+ import type { DashboardSource } from "../source.js";
54
+ import { firedPanel } from "./fired.js";
55
+ import {
56
+ activityView,
57
+ eventDetail,
58
+ flowView,
59
+ healthView,
60
+ memoriesView,
61
+ memoryDetail,
62
+ metaView,
63
+ mindView,
64
+ nodeDetail,
65
+ overviewView,
66
+ pulse,
67
+ searchView,
68
+ } from "./views.js";
69
+
70
+ /** bansai's 3737 is in use for the length of the parallel run. */
71
+ export const DEFAULT_PORT = 4747;
72
+ export const PORT_ENV = "COUNTERPARTS_DASHBOARD_PORT";
73
+
74
+ const HERE = dirname(fileURLToPath(import.meta.url));
75
+ const APP_PATH = join(HERE, "app.html");
76
+ const BRAIN_PATH = join(HERE, "brain.html");
77
+
78
+ const NO_STORE = { "cache-control": "no-store" } as const;
79
+
80
+ /**
81
+ * A small mark: three dots on a rising diagonal, the middle one lit. Served from
82
+ * memory, so there is no fourth file to lose — and served at all because a
83
+ * missing favicon is a console error, and this dashboard's bar is zero of them.
84
+ * Static branding rather than a data view, so it is the one response that may
85
+ * cache.
86
+ */
87
+ const FAVICON_SVG =
88
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">` +
89
+ `<rect width="64" height="64" rx="13" fill="#0a0e14"/>` +
90
+ `<path d="M14 46 L32 32 L50 18" stroke="#00e5ff" stroke-opacity=".35" stroke-width="2.5" fill="none" stroke-linecap="round"/>` +
91
+ `<circle cx="14" cy="46" r="4.5" fill="#00bfa5"/>` +
92
+ `<circle cx="32" cy="32" r="7" fill="#00e5ff"/>` +
93
+ `<circle cx="50" cy="18" r="4.5" fill="#b388ff"/></svg>`;
94
+
95
+ const ALLOWED_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
96
+
97
+ export function isAllowedHost(host: string | null | undefined): boolean {
98
+ if (typeof host !== "string" || host.length === 0) return false;
99
+ const match = /^(\[[^\]]+\]|[^:]+)(:\d+)?$/.exec(host.trim());
100
+ if (match === null) return false;
101
+ const hostname = (match[1] ?? "").toLowerCase();
102
+ return ALLOWED_HOSTNAMES.has(hostname);
103
+ }
104
+
105
+ export interface Reply {
106
+ readonly status: number;
107
+ readonly headers: Record<string, string>;
108
+ readonly body: string;
109
+ }
110
+
111
+ function json(body: unknown, status = 200): Reply {
112
+ return {
113
+ status,
114
+ headers: { "content-type": "application/json; charset=utf-8", ...NO_STORE },
115
+ body: JSON.stringify(body),
116
+ };
117
+ }
118
+
119
+ function html(body: string): Reply {
120
+ return { status: 200, headers: { "content-type": "text/html; charset=utf-8", ...NO_STORE }, body };
121
+ }
122
+
123
+ /** One of the two static pages. A missing file is a sentence, never a stack. */
124
+ function page(file: string): Reply {
125
+ try {
126
+ return html(readFileSync(file, "utf8"));
127
+ } catch {
128
+ return json(
129
+ { error: `the dashboard page is missing from the install (${file}). Reinstall, or run from a checkout.` },
130
+ 500,
131
+ );
132
+ }
133
+ }
134
+
135
+ function intParam(url: URL, name: string, fallback: number): number {
136
+ const raw = url.searchParams.get(name);
137
+ if (raw === null) return fallback;
138
+ const parsed = Number.parseInt(raw, 10);
139
+ return Number.isFinite(parsed) ? parsed : fallback;
140
+ }
141
+
142
+ /**
143
+ * Resolve one request against an already-open observer source.
144
+ *
145
+ * Read-only by construction and by scan. Every throw becomes a 500 JSON body:
146
+ * an instrument that crashes its own loop on a broken store is the one moment
147
+ * the owner most needs it to render (scar E7).
148
+ */
149
+ export function router(url: URL, host: string | null, src: DashboardSource): Reply {
150
+ if (!isAllowedHost(host)) {
151
+ return json(
152
+ { error: "forbidden: this dashboard answers only to localhost, 127.0.0.1 or [::1]" },
153
+ 403,
154
+ );
155
+ }
156
+ const path = url.pathname;
157
+ try {
158
+ if (path === "/" || path === "/index.html") return page(APP_PATH);
159
+ if (path === "/brain") return page(BRAIN_PATH);
160
+ if (path === "/favicon.svg" || path === "/favicon.ico") {
161
+ return {
162
+ status: 200,
163
+ headers: { "content-type": "image/svg+xml", "cache-control": "public, max-age=86400" },
164
+ body: FAVICON_SVG,
165
+ };
166
+ }
167
+
168
+ if (path === "/api/meta") return json(metaView(src));
169
+ if (path === "/api/pulse") return json(pulse(src));
170
+ if (path === "/api/overview") return json(overviewView(src, intParam(url, "limit", 40)));
171
+ if (path === "/api/memories") return json(memoriesView(src, { limit: intParam(url, "limit", 4000) }));
172
+ if (path === "/api/memory") {
173
+ const id = url.searchParams.get("id") ?? "";
174
+ if (id.length === 0) return json({ error: "id is required" }, 400);
175
+ return json(memoryDetail(src, id));
176
+ }
177
+ if (path === "/api/search") {
178
+ return json(searchView(src, url.searchParams.get("q") ?? "", intParam(url, "limit", 25)));
179
+ }
180
+ if (path === "/api/mind") return json(mindView(src));
181
+ if (path === "/api/flow") return json(flowView(src, intParam(url, "limit", 24)));
182
+ if (path === "/api/node") {
183
+ const key = url.searchParams.get("key") ?? "";
184
+ const detail = nodeDetail(src, key, intParam(url, "limit", 8));
185
+ return detail.found ? json(detail) : json({ error: `no such node: ${key}` }, 404);
186
+ }
187
+ if (path === "/api/health") return json(healthView(src));
188
+ if (path === "/api/fired") return json(firedPanel(src, todayUtc()));
189
+ if (path === "/api/activity") {
190
+ const sinceRaw = url.searchParams.get("sinceSeq");
191
+ const opts: { limit: number; name?: string; sinceSeq?: number } = {
192
+ limit: intParam(url, "limit", 40),
193
+ };
194
+ const name = url.searchParams.get("name");
195
+ if (name !== null && name.length > 0) opts.name = name;
196
+ if (sinceRaw !== null) opts.sinceSeq = intParam(url, "sinceSeq", 0);
197
+ return json(activityView(src, opts));
198
+ }
199
+ if (path === "/api/event") {
200
+ const seq = intParam(url, "seq", -1);
201
+ if (seq < 0) return json({ error: "seq is required" }, 400);
202
+ const detail = eventDetail(src, seq);
203
+ return detail.found ? json(detail) : json({ error: "no event with that seq in the kept window" }, 404);
204
+ }
205
+ return json({ error: `not found: ${path}` }, 404);
206
+ } catch (err) {
207
+ // A store refusal reaches the page as its code and its detail — ids and
208
+ // counts, never prose, so both are safe to print (`bin/dashboard.ts` makes
209
+ // the same argument for the terminal).
210
+ if (isStoreError(err)) return json({ error: `${err.code}: ${JSON.stringify(err.detail)}` }, 500);
211
+ return json({ error: err instanceof Error ? err.message : String(err) }, 500);
212
+ }
213
+ }
214
+
215
+ export interface ServeOptions {
216
+ /** The data dir. Always passed explicitly by every caller in this repo. */
217
+ readonly dir?: string;
218
+ /** 0 asks the OS for a free port — what the visual loop uses. */
219
+ readonly port?: number;
220
+ }
221
+
222
+ export interface RunningDashboard {
223
+ readonly port: number;
224
+ readonly url: string;
225
+ readonly dir: string;
226
+ readonly server: Server;
227
+ stop(): Promise<void>;
228
+ }
229
+
230
+ function resolvePort(opts: ServeOptions): number {
231
+ if (opts.port !== undefined) return opts.port;
232
+ const fromEnv = Number.parseInt(process.env[PORT_ENV] ?? "", 10);
233
+ return Number.isInteger(fromEnv) && fromEnv >= 0 && fromEnv < 65536 ? fromEnv : DEFAULT_PORT;
234
+ }
235
+
236
+ /**
237
+ * Open the store in observer mode, bind loopback, serve. The returned handle
238
+ * carries the BOUND port — which is not the requested one when the caller asked
239
+ * for 0 — and closing it closes the store.
240
+ */
241
+ export function startDashboard(opts: ServeOptions = {}): Promise<RunningDashboard> {
242
+ const dashboard = Dashboard.open({ ...(opts.dir === undefined ? {} : { dir: opts.dir }) });
243
+ const src = dashboard.source;
244
+ const dir = dashboard.store.dir;
245
+
246
+ const server = createServer((req, res) => {
247
+ let reply: Reply;
248
+ try {
249
+ const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
250
+ reply = router(url, req.headers.host ?? null, src);
251
+ } catch (err) {
252
+ reply = {
253
+ status: 500,
254
+ headers: { "content-type": "application/json; charset=utf-8", ...NO_STORE },
255
+ body: JSON.stringify({ error: err instanceof Error ? err.message : String(err) }),
256
+ };
257
+ }
258
+ res.writeHead(reply.status, reply.headers);
259
+ res.end(reply.body);
260
+ });
261
+
262
+ return new Promise<RunningDashboard>((ok, fail) => {
263
+ server.once("error", fail);
264
+ server.listen(resolvePort(opts), "127.0.0.1", () => {
265
+ server.removeListener("error", fail);
266
+ const address = server.address();
267
+ const port = typeof address === "object" && address !== null ? address.port : resolvePort(opts);
268
+ ok({
269
+ port,
270
+ url: `http://127.0.0.1:${port}`,
271
+ dir,
272
+ server,
273
+ stop: () =>
274
+ new Promise<void>((done) => {
275
+ server.close(() => {
276
+ dashboard.close();
277
+ done();
278
+ });
279
+ // Node keeps a server open while a keep-alive socket lives; the
280
+ // dashboard is a local tool and a hung `stop()` in a test harness is
281
+ // worse than a dropped connection.
282
+ server.closeAllConnections?.();
283
+ }),
284
+ });
285
+ });
286
+ });
287
+ }