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,82 @@
1
+ /**
2
+ * The whole of this adapter's colour, written here rather than depended upon.
3
+ *
4
+ * Two rules, both from the CONTRACT: no TUI framework and no dependency, and
5
+ * views are plain-text renderers returning strings. Colour is therefore a pure
6
+ * decoration applied by a `Style` object that is DISABLED BY DEFAULT — every
7
+ * view called without a style produces the exact bytes a test asserts on, and
8
+ * the `bin/` entry is the only place that ever turns escapes on.
9
+ *
10
+ * There is no semantic colour vocabulary here beyond `warn`, deliberately: the
11
+ * absence markers in `layout.ts` are WORDS, and a reader who pipes this through
12
+ * `less` must see the same absences a colour terminal shows. Colour may
13
+ * emphasize what the text already says; it may never be the only place it is
14
+ * said (scar §2.4 — absence is displayed, not merely un-highlighted).
15
+ *
16
+ * The escape byte is built with `String.fromCharCode` rather than written as a
17
+ * literal: a raw control character in a source file survives exactly as long as
18
+ * nothing ever reformats it.
19
+ */
20
+
21
+ const CSI = `${String.fromCharCode(27)}[`;
22
+ const RESET = `${CSI}0m`;
23
+ const ANSI_PATTERN = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
24
+
25
+ function wrap(code: string, s: string): string {
26
+ return s.length === 0 ? s : `${CSI}${code}m${s}${RESET}`;
27
+ }
28
+
29
+ export interface Style {
30
+ readonly enabled: boolean;
31
+ bold(s: string): string;
32
+ dim(s: string): string;
33
+ underline(s: string): string;
34
+ /** For a named absence and a torn marker: the two things worth an eye-catch. */
35
+ warn(s: string): string;
36
+ ok(s: string): string;
37
+ }
38
+
39
+ const IDENTITY = (s: string): string => s;
40
+
41
+ /** Escapes off. The default everywhere except an interactive terminal. */
42
+ export const PLAIN: Style = {
43
+ enabled: false,
44
+ bold: IDENTITY,
45
+ dim: IDENTITY,
46
+ underline: IDENTITY,
47
+ warn: IDENTITY,
48
+ ok: IDENTITY,
49
+ };
50
+
51
+ const COLOUR: Style = {
52
+ enabled: true,
53
+ bold: (s) => wrap("1", s),
54
+ dim: (s) => wrap("2", s),
55
+ underline: (s) => wrap("4", s),
56
+ warn: (s) => wrap("33", s),
57
+ ok: (s) => wrap("32", s),
58
+ };
59
+
60
+ export function style(enabled: boolean): Style {
61
+ return enabled ? COLOUR : PLAIN;
62
+ }
63
+
64
+ /**
65
+ * True when this process is attached to a terminal that has not asked for plain
66
+ * output. `NO_COLOR` is honoured because the owner's terminal is not ours to
67
+ * decide about (https://no-color.org).
68
+ */
69
+ export function terminalWantsColour(env: NodeJS.ProcessEnv = process.env): boolean {
70
+ const noColour = env["NO_COLOR"];
71
+ if (typeof noColour === "string" && noColour.length > 0) return false;
72
+ return process.stdout.isTTY === true;
73
+ }
74
+
75
+ /** Column arithmetic must measure what the eye sees, not what the bytes are. */
76
+ export function visibleWidth(s: string): number {
77
+ return stripAnsi(s).length;
78
+ }
79
+
80
+ export function stripAnsi(s: string): string {
81
+ return s.replace(ANSI_PATTERN, "");
82
+ }
@@ -0,0 +1,479 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * The entry script. Thin on purpose: parse a few flags, render a string, print
4
+ * it. Every decision worth testing lives in the view functions, which return
5
+ * strings and know nothing about a terminal.
6
+ *
7
+ * Run as:
8
+ *
9
+ * ~/.bun/bin/bun run src/adapters/dashboard/bin/dashboard.ts status
10
+ * ... browse --id mem_abc123
11
+ * ... stories --limit 3
12
+ *
13
+ * The data dir comes from `COUNTERPARTS_DATA_DIR` or `~/.counterparts/store` by the
14
+ * store's own resolution, at call time; `--dir` overrides it for one run, and
15
+ * `store/paths.ts` structurally refuses a path inside v1's live store.
16
+ */
17
+ import { join, resolve } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ import { Dashboard, VIEWS, VIEW_BLURB, isViewName } from "../index.js";
21
+ import type { ViewArgs, ViewName } from "../index.js";
22
+ import { terminalWantsColour } from "../ansi.js";
23
+ import { DATA_DIR_ENV, dataDir, describeGuardRefusal, isStoreError } from "../../../core/store/index.js";
24
+ import type { StoreError } from "../../../core/store/index.js";
25
+ import type { Band, Kind } from "../../../core/types.js";
26
+
27
+ interface Parsed {
28
+ readonly view: ViewName | "help";
29
+ readonly dir: string | undefined;
30
+ readonly colour: boolean;
31
+ readonly width: number | undefined;
32
+ readonly args: ViewArgs;
33
+ }
34
+
35
+ export function parseArgv(argv: readonly string[]): Parsed {
36
+ const positional: string[] = [];
37
+ const flags = new Map<string, string>();
38
+ for (let i = 0; i < argv.length; i++) {
39
+ const token = argv[i] ?? "";
40
+ if (!token.startsWith("--")) {
41
+ positional.push(token);
42
+ continue;
43
+ }
44
+ const [name, inline] = token.slice(2).split("=", 2);
45
+ if (name === undefined) continue;
46
+ if (inline !== undefined) {
47
+ flags.set(name, inline);
48
+ continue;
49
+ }
50
+ const next = argv[i + 1];
51
+ if (next === undefined || next.startsWith("--")) {
52
+ flags.set(name, "true");
53
+ } else {
54
+ flags.set(name, next);
55
+ i += 1;
56
+ }
57
+ }
58
+
59
+ const first = positional[0];
60
+ // ASKING FOR HELP MUST NOT OPEN A STORE. `--help` is a flag, so it left no
61
+ // positional behind, and "no positional" meant `status` — which opened the
62
+ // DEFAULT data dir, i.e. the owner's live memory, and rendered it. A claims
63
+ // audit hit exactly that on 2026-09-04 while trying to read the usage. Help is
64
+ // checked before anything else here, and `run()` returns it before it opens
65
+ // anything (§5 G9: reads are pure, and this one reads nothing at all).
66
+ const wantsHelp =
67
+ flags.get("help") === "true" || flags.get("h") === "true" || first === "help" ||
68
+ argv.includes("-h") || argv.includes("--help");
69
+ const view: ViewName | "help" = wantsHelp
70
+ ? "help"
71
+ : first === undefined
72
+ ? "status"
73
+ : isViewName(first)
74
+ ? first
75
+ : "help";
76
+
77
+ const args: ViewArgs = {};
78
+ const id = flags.get("id");
79
+ if (id !== undefined) Object.assign(args, { id });
80
+ const limit = flags.get("limit");
81
+ if (limit !== undefined && Number.isFinite(Number(limit))) {
82
+ Object.assign(args, { limit: Number(limit) });
83
+ }
84
+ const band = flags.get("band");
85
+ if (band !== undefined) Object.assign(args, { band: band as Band });
86
+ const kind = flags.get("kind");
87
+ if (kind !== undefined) Object.assign(args, { kind: kind as Kind });
88
+ const name = flags.get("name");
89
+ if (name !== undefined) Object.assign(args, { name });
90
+ if (flags.get("archived") === "true") Object.assign(args, { archived: true });
91
+
92
+ const widthFlag = flags.get("width");
93
+ const width =
94
+ widthFlag !== undefined && Number.isFinite(Number(widthFlag)) ? Number(widthFlag) : undefined;
95
+
96
+ return {
97
+ view,
98
+ dir: flags.get("dir"),
99
+ colour: flags.get("no-colour") === "true" ? false : flags.get("colour") === "true" || terminalWantsColour(),
100
+ ...(width === undefined ? { width: undefined } : { width }),
101
+ args,
102
+ };
103
+ }
104
+
105
+ export function helpText(): string {
106
+ const lines = [
107
+ "counterparts dashboard — the owner's window",
108
+ "",
109
+ " bun run src/adapters/dashboard/bin/dashboard.ts <view> [flags]",
110
+ "",
111
+ "Views:",
112
+ ...VIEWS.map((v) => ` ${v.padEnd(9)} ${VIEW_BLURB[v]}`),
113
+ "",
114
+ "Flags:",
115
+ " --id <id> open one memory (browse) or one belief (stories)",
116
+ " --limit <n> how many rows",
117
+ " --band <band> filter the browse list",
118
+ " --kind <kind> filter the browse list",
119
+ " --name <event> filter the activity feed",
120
+ " --archived include archived rows",
121
+ " --dir <path> read a different data dir",
122
+ " --colour / --no-colour, --width <n>",
123
+ "",
124
+ "The web view:",
125
+ " serve --dir <path> [--port <n>] the local dashboard, on 127.0.0.1 only",
126
+ ` (default port ${SERVE_DEFAULT_PORT}, or ${SERVE_PORT_ENV})`,
127
+ " serve --default-store open the DEFAULT store instead. Without --dir",
128
+ " or --default-store, 'serve' refuses: on a machine",
129
+ " with an install the default is the owner's live",
130
+ " memory.",
131
+ "",
132
+ "A flag a subcommand does not take is refused before anything is opened.",
133
+ "",
134
+ "It reads in observer mode and writes nothing, ever.",
135
+ ];
136
+ return lines.join("\n");
137
+ }
138
+
139
+ /** Kept in sync with `web/server.ts` by the test, not by an import: the help
140
+ * text must render without loading a page server the terminal never needs. */
141
+ const SERVE_DEFAULT_PORT = 4747;
142
+ const SERVE_PORT_ENV = "COUNTERPARTS_DASHBOARD_PORT";
143
+
144
+ export interface ServeArgs {
145
+ readonly serve: boolean;
146
+ readonly dir: string | undefined;
147
+ readonly port: number | undefined;
148
+ /** `--default-store`: I meant the default store. The only way past the refusal
149
+ * below. It is not `--yes` — that flag means "skip an interactive confirmation"
150
+ * everywhere in this package and nothing else (owner ruling 2026-09-05), and
151
+ * `serve` has no confirmation to skip. The flag that puts a whole store on a
152
+ * socket says which store. */
153
+ readonly defaultStore: boolean;
154
+ }
155
+
156
+ /**
157
+ * THE FLAGS EACH SUBCOMMAND TAKES, and the one sentence anything else gets.
158
+ *
159
+ * `parseArgv` collects every `--flag` into a map and reads the ones it knows,
160
+ * so a flag nobody declared was silently dropped — the silence the console
161
+ * closed on 2026-09-04 (`cli/commands.ts#unknownFlag`, where `--dirr` sent a
162
+ * note to the default store without a word). The case that closed it here was
163
+ * `serve --yes`: on this binary it meant "open the DEFAULT store", one package
164
+ * over it meant "skip the typed confirmation", and the owner ruled on
165
+ * 2026-09-05 that `--yes` means only the second, everywhere. The dashboard's
166
+ * flag is `--default-store` now, and `--yes` is not kept as a no-op: a
167
+ * silently-dropped flag IS a no-op, and one that used to mean "aim here" is the
168
+ * worst kind. Checked after help and before anything opens. One line, like
169
+ * every refusal this binary prints; the list is what the reader needs to find
170
+ * the flag they meant.
171
+ */
172
+ const VIEW_FLAGS: readonly string[] = [
173
+ "dir", "id", "limit", "band", "kind", "name", "archived", "width", "colour", "no-colour", "help", "h",
174
+ ];
175
+ const SERVE_FLAGS: readonly string[] = ["dir", "port", "default-store", "help", "h"];
176
+
177
+ export function unknownFlag(argv: readonly string[]): string | null {
178
+ const serve = (argv[0] ?? "") === "serve";
179
+ const allowed = serve ? SERVE_FLAGS : VIEW_FLAGS;
180
+ for (const token of argv) {
181
+ if (!token.startsWith("--") || token === "--") continue;
182
+ const name = token.slice(2).split("=", 2)[0] ?? "";
183
+ if (name.length === 0 || allowed.includes(name)) continue;
184
+ const takes = allowed.filter((f) => f !== "h").map((f) => `--${f}`).join(" ");
185
+ return `Refused: unknown flag --${name}. ${serve ? "'serve' takes" : "The views take"} ${takes}. Nothing was opened.`;
186
+ }
187
+ return null;
188
+ }
189
+
190
+ /** `serve` is parsed separately from the five views because it is not one: it
191
+ * returns nothing to print, and `run()` is a pure string function the suite
192
+ * leans on heavily. Keeping them apart keeps that true. */
193
+ export function parseServe(argv: readonly string[]): ServeArgs {
194
+ const parsed = parseArgv(argv);
195
+ const serve = (argv[0] ?? "") === "serve";
196
+ const portFlag = flagValue(argv, "port");
197
+ const port = portFlag !== undefined && Number.isInteger(Number(portFlag)) ? Number(portFlag) : undefined;
198
+ return {
199
+ serve,
200
+ dir: parsed.dir,
201
+ ...(port === undefined ? { port: undefined } : { port }),
202
+ defaultStore: argv.includes("--default-store") || argv.includes("--default-store=true"),
203
+ };
204
+ }
205
+
206
+ /**
207
+ * THE REFUSAL A STRAY `serve` GETS, or null when the command named its store.
208
+ *
209
+ * `counterparts-dashboard serve`, typed alone, used to print a warning and then
210
+ * open the DEFAULT data dir — which on the author's machine is his live memory,
211
+ * every element of it, on a socket, in a browser. A warning after the fact is
212
+ * the wrong instrument: the page is already up and the reader has already
213
+ * skipped the line. So the default store is now opt-in by name.
214
+ *
215
+ * Pure, and it opens nothing: the sentence has to be reachable without a store
216
+ * and without a socket, or the test for it would need both. `targetDirOf` is
217
+ * the defensive read of the default — `dataDir()` itself throws when the
218
+ * environment points inside v1's live store, and a refusal that throws while
219
+ * naming what it refused is the same bug one frame down.
220
+ *
221
+ * TWO SENTENCES, BECAUSE THERE ARE TWO CASES AND ONLY ONE OF THEM IS KNOWN.
222
+ * `~/.counterparts/store` on a machine with an install IS the owner's live
223
+ * memory — that is what the layout means. `COUNTERPARTS_DATA_DIR` is whatever
224
+ * somebody exported, and an adversarial review pointed this at a scratch demo
225
+ * store and got a refusal asserting it was live memory. The refusal still
226
+ * refuses — QUICKSTART §7 tells the reader to export that variable with the
227
+ * live store in it, so honouring it would put the hole straight back — but it
228
+ * says why without claiming what it cannot check.
229
+ */
230
+ export function serveRefusal(
231
+ args: ServeArgs,
232
+ env: Record<string, string | undefined> = process.env,
233
+ ): string | null {
234
+ if (args.dir !== undefined || args.defaultStore) return null;
235
+ const fromEnv = env[DATA_DIR_ENV];
236
+ if (typeof fromEnv === "string" && fromEnv.length > 0) {
237
+ return (
238
+ `Refused: 'serve' does not take the store from ${DATA_DIR_ENV} (${fromEnv}). ` +
239
+ "Pass --dir <path> to name one, or --default-store to accept that variable. " +
240
+ "It is the variable QUICKSTART tells you to export with your live memory in it, and 'serve' " +
241
+ "puts a whole store on a socket — so that choice is made in the command. Nothing was opened."
242
+ );
243
+ }
244
+ return (
245
+ `Refused: 'serve' with no --dir would open ${targetDirOf(args)}, which is the default store — ` +
246
+ "on a machine with an install, that is the owner's live memory. " +
247
+ "Pass --dir <path> to name a store, or --default-store to mean the default. Nothing was opened."
248
+ );
249
+ }
250
+
251
+ function flagValue(argv: readonly string[], name: string): string | undefined {
252
+ for (let i = 0; i < argv.length; i++) {
253
+ const token = argv[i] ?? "";
254
+ if (token === `--${name}`) return argv[i + 1];
255
+ if (token.startsWith(`--${name}=`)) return token.slice(name.length + 3);
256
+ }
257
+ return undefined;
258
+ }
259
+
260
+ /**
261
+ * Start the web view. The refusal path is the important half: an owner who
262
+ * points this at a directory with no store gets ONE SENTENCE — the same one the
263
+ * terminal views give — and the resolved data dir is PRINTED on every start, so
264
+ * "which store am I looking at" is never a guess.
265
+ */
266
+ export async function serve(argv: readonly string[]): Promise<number> {
267
+ // FIRST, before the store is even resolved: a flag `serve` does not take is a
268
+ // command line that does not mean what it says — and `--yes` is the one a
269
+ // reader of the old docs will type.
270
+ const badFlag = unknownFlag(argv);
271
+ if (badFlag !== null) {
272
+ process.stderr.write(`${badFlag}\n`);
273
+ return 1;
274
+ }
275
+ const args = parseServe(argv);
276
+ // BEFORE the server module is even loaded, let alone a store opened.
277
+ const refusal = serveRefusal(args);
278
+ if (refusal !== null) {
279
+ process.stderr.write(`${refusal}\n`);
280
+ return 1;
281
+ }
282
+ const dir = args.dir === undefined ? undefined : resolve(args.dir);
283
+ const { startDashboard } = await import("../web/server.js");
284
+ try {
285
+ const running = await startDashboard({
286
+ ...(dir === undefined ? {} : { dir }),
287
+ ...(args.port === undefined ? {} : { port: args.port }),
288
+ });
289
+ process.stdout.write(
290
+ [
291
+ `counterparts dashboard — ${running.url}`,
292
+ `reading ${running.dir}`,
293
+ // Named when it was not asked for. `--dir` is optional and the default
294
+ // is somebody's real memory, so a `serve` typed without one should not
295
+ // look the same as a `serve` aimed on purpose (constitution 16: the
296
+ // system shows its workings). It is a read-only view either way; this
297
+ // line is so a stray start is visible rather than merely harmless.
298
+ // Only reachable with `--default-store`, which is the owner saying he
299
+ // meant it — and it still says which store that was.
300
+ ...(dir === undefined
301
+ ? [`(--default-store, so this is the DEFAULT store — ${DATA_DIR_ENV} or ~/.counterparts/store)`]
302
+ : []),
303
+ "observer mode: it strengthens nothing, deposits nothing, and writes no file of its own.",
304
+ "ctrl-c to stop.",
305
+ "",
306
+ ].join("\n"),
307
+ );
308
+ return 0;
309
+ } catch (err) {
310
+ const where = dir ?? targetDirOf(args);
311
+ if (isStoreError(err)) {
312
+ process.stderr.write(`${describeStoreError(err, where, args.dir !== undefined)}\n`);
313
+ return 1;
314
+ }
315
+ const code = (err as { code?: string }).code;
316
+ if (code === "EADDRINUSE") {
317
+ process.stderr.write(
318
+ `Port ${args.port ?? SERVE_DEFAULT_PORT} is already in use. Pass --port <n> or set ${SERVE_PORT_ENV}.\n`,
319
+ );
320
+ return 1;
321
+ }
322
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
323
+ return 1;
324
+ }
325
+ }
326
+
327
+ function targetDirOf(args: ServeArgs): string {
328
+ if (args.dir !== undefined) return resolve(args.dir);
329
+ try {
330
+ return dataDir();
331
+ } catch {
332
+ return `the default data dir (${DATA_DIR_ENV} or ~/.counterparts)`;
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Every store refusal, as one sentence. An owner reading an instrument is owed a
338
+ * SENTENCE, not nine frames: the code is the wire shape (`store/errors.ts`), the
339
+ * detail is ids and counts only, and neither ever carries prose — so both can be
340
+ * printed. Constitution 16: a refusal the owner cannot read is a refusal that
341
+ * teaches nothing.
342
+ */
343
+ export function describeStoreError(err: StoreError, dir: string, namedDir = false): string {
344
+ switch (err.code) {
345
+ // The instrument refuses to mint an absent store (cli INTERFACE-GAPS §7) —
346
+ // and an owner pointing a dashboard at nothing deserves a sentence, not a
347
+ // stack trace.
348
+ //
349
+ // The remedy names the dir that was passed, exactly as the console's copy
350
+ // of this sentence does: `counterparts init` on its own, offered under a
351
+ // line that just named `--dir /somewhere`, creates the store in the DEFAULT
352
+ // place instead — advice that works, somewhere else.
353
+ case "STORE_UNINITIALIZED":
354
+ return `No store at ${dir}. Run 'counterparts init${namedDir ? ` --dir ${dir}` : ""}' to create one.`;
355
+ // The exact error a stranger who put the adapter's config in the wrong place
356
+ // will hit. The CLI's `init` already teaches the rule; this says the same
357
+ // thing at the moment the rule bites.
358
+ case "LAYOUT_UNCLASSIFIED":
359
+ return (
360
+ `LAYOUT_UNCLASSIFIED: ${dir} holds ${String(err.detail["name"] ?? "an unclassified entry")}, ` +
361
+ "which the store's layout does not classify. Write the adapter's configuration BESIDE " +
362
+ "the store, never inside it — the layout check refuses an unclassified file in the data " +
363
+ `dir (§5 G11): ${join(dir, "..", "claude-code.json")}`
364
+ );
365
+ // The explicit-dir guard (`store/paths.ts#REQUIRE_EXPLICIT_DIR_ENV`): armed
366
+ // on purpose by an operator, so the sentence says what it refused and how to
367
+ // proceed. The sentence is the store's; the remedy is this surface's, which
368
+ // has `--dir`. The dir it names comes from the error's own detail, because
369
+ // `dataDir()` is what threw and cannot be called to name it.
370
+ case "IMPLICIT_DEFAULT_DIR_REFUSED":
371
+ case "EXPLICIT_DIR_GUARD_MALFORMED":
372
+ return (
373
+ describeGuardRefusal(err, `Name the store: --dir <path>, or ${DATA_DIR_ENV}.`) ??
374
+ `${err.code}: the store at ${dir} refused this read (${JSON.stringify(err.detail)}).`
375
+ );
376
+ default:
377
+ return `${err.code}: the store at ${dir} refused this read (${JSON.stringify(err.detail)}).`;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * The dir to NAME in a refusal — resolved defensively, because `dataDir()` can
383
+ * itself throw (`DATA_DIR_FORBIDDEN`, when the env points inside v1's live
384
+ * store). A handler that throws while describing an error would be the very bug
385
+ * it was written to fix, one frame further down.
386
+ */
387
+ function targetDir(parsed: Parsed): string {
388
+ if (parsed.dir !== undefined) return resolve(parsed.dir);
389
+ try {
390
+ return dataDir();
391
+ } catch {
392
+ return `the default data dir (${DATA_DIR_ENV} or ~/.counterparts/store)`;
393
+ }
394
+ }
395
+
396
+ /**
397
+ * The rendered view, and whether it is a REFUSAL rather than a render.
398
+ *
399
+ * `run()` returns only the string, because the suite leans on it being a pure
400
+ * string function and every existing test holds. The entry point needs the
401
+ * other half: a view of a store that is not there exits non-zero, the same way
402
+ * `counterparts status` does — a script that asks an instrument what is in a
403
+ * store and gets a sentence about there being no store has not succeeded, and a
404
+ * mistyped `--dir` should not read as a clean run.
405
+ */
406
+ export function runReport(argv: readonly string[]): { text: string; refused: boolean } {
407
+ const parsed = parseArgv(argv);
408
+ if (parsed.view === "help") return { text: helpText(), refused: false };
409
+ // Help first, then this, then the store — the console's order. A view asked
410
+ // for with a flag it does not take is a refusal, not a render of whatever
411
+ // store the parser fell back to.
412
+ const badFlag = unknownFlag(argv);
413
+ if (badFlag !== null) return { text: badFlag, refused: true };
414
+ const refusal = (err: unknown): { text: string; refused: boolean } => ({
415
+ text: describeStoreError(err as StoreError, targetDir(parsed), parsed.dir !== undefined),
416
+ refused: true,
417
+ });
418
+ let dashboard: Dashboard;
419
+ try {
420
+ dashboard = Dashboard.open({
421
+ ...(parsed.dir === undefined ? {} : { dir: parsed.dir }),
422
+ colour: parsed.colour,
423
+ ...(parsed.width === undefined ? {} : { width: parsed.width }),
424
+ });
425
+ } catch (err) {
426
+ // EVERY store refusal, not just the one that was anticipated. A code this
427
+ // file has never heard of still reaches the owner as a line it can read;
428
+ // anything that is not a StoreError is a bug here and still throws.
429
+ if (isStoreError(err)) return refusal(err);
430
+ throw err;
431
+ }
432
+ try {
433
+ return { text: dashboard.render(parsed.view, parsed.args), refused: false };
434
+ } catch (err) {
435
+ if (isStoreError(err)) return refusal(err);
436
+ throw err;
437
+ } finally {
438
+ dashboard.close();
439
+ }
440
+ }
441
+
442
+ export function run(argv: readonly string[]): string {
443
+ return runReport(argv).text;
444
+ }
445
+
446
+ /** True only when this file is the process entry point — so a test may import
447
+ * `run` and `parseArgv` without the script printing itself (the same guard
448
+ * `adapters/claude-code/bin/` uses). */
449
+ export function isEntryPoint(argv1: string | undefined, url: string): boolean {
450
+ if (argv1 === undefined) return false;
451
+ return resolve(argv1) === fileURLToPath(new URL(url));
452
+ }
453
+
454
+ if (isEntryPoint(process.argv[1], import.meta.url)) {
455
+ const argv = process.argv.slice(2);
456
+ // Help first, and before `serve` too: `serve --help` would otherwise bind a
457
+ // socket against the default store.
458
+ if (argv.includes("--help") || argv.includes("-h")) {
459
+ process.stdout.write(`${helpText()}\n`);
460
+ process.exit(0);
461
+ }
462
+ if ((argv[0] ?? "") === "serve") {
463
+ // The one subcommand that does not return a string: it binds a socket and
464
+ // stays. `run()` is left exactly as it was, so every existing test holds.
465
+ const code = await serve(argv);
466
+ if (code !== 0) process.exit(code);
467
+ } else {
468
+ // A refusal goes to stderr and exits 1: a non-zero exit whose only output
469
+ // is on stdout is half a refusal, and the console's `status` makes exactly
470
+ // the same two calls for exactly the same reason.
471
+ const report = runReport(argv);
472
+ if (report.refused) {
473
+ process.stderr.write(`${report.text}\n`);
474
+ process.exit(1);
475
+ }
476
+ process.stdout.write(`${report.text}\n`);
477
+ process.exit(0);
478
+ }
479
+ }