@alterset/alterspec-client 0.1.0 → 0.4.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.
package/dist/cli.js CHANGED
@@ -1,13 +1,1715 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
- import { readFileSync } from "fs";
5
4
  import { Command } from "commander";
5
+
6
+ // src/config.ts
7
+ import { execFileSync } from "child_process";
8
+ import { existsSync, readFileSync, writeFileSync } from "fs";
9
+ import { homedir } from "os";
10
+ import { basename, dirname, isAbsolute, join, resolve } from "path";
11
+ import { z as z2 } from "zod";
12
+
13
+ // ../src/schemas/work.ts
14
+ import { z } from "zod";
15
+ var TrackCode = z.string().regex(/^[A-Z]{2,5}$/, { message: "must be BE or a channel code" });
16
+ var ChangeRef = z.string().regex(/^CHG-\d{3,}$/);
17
+ var Day = z.iso.date();
18
+ var WorkTrackSchema = z.object({
19
+ code: TrackCode,
20
+ kind: z.enum(["backend", "ui"]),
21
+ /** The channel codes the track builds: the API channels for `BE`, the channels sharing the experience for a UI track. */
22
+ channels: z.array(z.string())
23
+ }).strict();
24
+ var WorkTaskSchema = z.object({
25
+ track: TrackCode,
26
+ /** The keys of the objects in the change's delta that put it on the track. */
27
+ objects: z.array(z.string()),
28
+ /**
29
+ * The task's checklist, derived from the delta: the acceptance criteria (`<CAP>-AC-NN`), screen actions
30
+ * (`<SCR>.Ann`) and contract states (`<UX-SCR>#<state>`) the change adds or changes, and every other object as
31
+ * its key. Sorted, never empty.
32
+ */
33
+ items: z.array(z.string().min(1)).min(1),
34
+ /** The tasks this one waits for, resolved: the same change's `BE` task, and the track's tasks it builds on. */
35
+ after: z.array(z.object({ change: ChangeRef, track: TrackCode }).strict())
36
+ }).strict();
37
+ var WorkChangeSchema = z.object({
38
+ id: ChangeRef,
39
+ title: z.string(),
40
+ signed_off: Day,
41
+ /** The hash of the change's `delta.json`; a signed-off change never changes. */
42
+ delta: z.string().regex(/^[0-9a-f]{16}$/),
43
+ depends_on: z.array(ChangeRef),
44
+ /** The change map's level. */
45
+ level: z.number().int().min(1),
46
+ /** One per track the change is on; empty = no work. */
47
+ tasks: z.array(WorkTaskSchema)
48
+ }).strict();
49
+ var WORK_FORMAT = 2;
50
+ var WorkSchema = z.object({
51
+ format: z.literal(WORK_FORMAT),
52
+ /** The alterspec version that wrote the export. */
53
+ alterspec: z.string(),
54
+ exported: Day,
55
+ /** Everything signed off before the changes began; `built`: the product as it runs (a reverse-spec), no work. */
56
+ baseline: z.object({ date: Day, built: z.boolean() }).strict().nullable(),
57
+ tracks: z.array(WorkTrackSchema),
58
+ /** Every change signed off after the baseline, in the change map's order. */
59
+ changes: z.array(WorkChangeSchema)
60
+ }).strict();
61
+ var WorkTaskV1Schema = WorkTaskSchema.omit({ items: true });
62
+ var WorkV1Schema = WorkSchema.extend({
63
+ format: z.literal(1),
64
+ changes: z.array(WorkChangeSchema.extend({ tasks: z.array(WorkTaskV1Schema) }).strict())
65
+ }).strict();
66
+ var AnyWorkSchema = z.discriminatedUnion("format", [WorkV1Schema, WorkSchema]);
67
+
68
+ // src/config.ts
69
+ var CONFIG_FILE = ".alterspec-client.json";
70
+ var ClientConfigSchema = z2.object({
71
+ /** The dispatcher's URL. */
72
+ dispatcher: z2.url(),
73
+ /** The developer's clone of the export repository, relative to this file's folder or absolute. */
74
+ export: z2.string().min(1),
75
+ /** The tracks this repository builds: the default of `next_task`. */
76
+ tracks: z2.array(TrackCode).default([]),
77
+ /** Where `worktree` puts a task's worktree; default `../<repo>-tasks`. */
78
+ worktrees: z2.string().min(1).optional(),
79
+ /** The public key to sign with: a `.pub` path or the key line; default ssh-agent, then `~/.ssh/id_ed25519.pub`. */
80
+ key: z2.string().min(1).optional(),
81
+ /** The track's main branch; default the remote's `HEAD`, else `main`. */
82
+ branch: z2.string().min(1).optional()
83
+ }).strict();
84
+ var ConfigError = class extends Error {
85
+ };
86
+ var git = (cwd, ...args) => {
87
+ try {
88
+ return execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
89
+ } catch {
90
+ return void 0;
91
+ }
92
+ };
93
+ function candidates(cwd) {
94
+ const top = git(cwd, "rev-parse", "--show-toplevel");
95
+ const common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir");
96
+ const main = common && basename(common) === ".git" ? dirname(common) : void 0;
97
+ return [...new Set([top, main, resolve(cwd)].filter((d) => !!d))];
98
+ }
99
+ function readConfigAt(root) {
100
+ const path = join(root, CONFIG_FILE);
101
+ if (!existsSync(path)) return void 0;
102
+ let raw;
103
+ try {
104
+ raw = JSON.parse(readFileSync(path, "utf8"));
105
+ } catch {
106
+ throw new ConfigError(`${path} is not valid JSON.`);
107
+ }
108
+ const parsed = ClientConfigSchema.safeParse(raw);
109
+ if (!parsed.success)
110
+ throw new ConfigError(
111
+ `${path} is not valid: ${parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"} ${i.message}`).join("; ")}.`
112
+ );
113
+ return parsed.data;
114
+ }
115
+ function loadConfig(cwd = process.cwd()) {
116
+ for (const root of candidates(cwd)) {
117
+ const config = readConfigAt(root);
118
+ if (config) return { root, config };
119
+ }
120
+ throw new ConfigError(
121
+ `No ${CONFIG_FILE} here: run \`npx @alterset/alterspec-client init --dispatcher <url> --export <path>\` first.`
122
+ );
123
+ }
124
+ function configPath(root, path) {
125
+ if (path === "~" || path.startsWith("~/")) return join(homedir(), path.slice(1));
126
+ return isAbsolute(path) ? path : resolve(root, path);
127
+ }
128
+ var exportDir = ({ root, config }) => configPath(root, config.export);
129
+ var worktreesDir = ({ root, config }) => configPath(root, config.worktrees ?? `../${basename(root)}-tasks`);
130
+ function writeConfig(root, config) {
131
+ writeFileSync(join(root, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
132
+ }
133
+
134
+ // src/ssh.ts
135
+ import { execFileSync as execFileSync2 } from "child_process";
136
+ import { createHash } from "crypto";
137
+ import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync as writeFileSync2 } from "fs";
138
+ import { homedir as homedir2, tmpdir } from "os";
139
+ import { join as join2 } from "path";
140
+ var NAMESPACE = "alterspec-dispatcher";
141
+ var KEY_TYPES = ["ssh-ed25519", "sk-ssh-ed25519@openssh.com"];
142
+ var KeyError = class extends Error {
143
+ };
144
+ function parseKeyLine(line, source, file) {
145
+ const [type, blob] = line.trim().split(/\s+/);
146
+ if (!type || !blob || !KEY_TYPES.includes(type))
147
+ throw new KeyError(
148
+ `${source} is not an ssh-ed25519 public key: the dispatcher accepts ${KEY_TYPES.join(" and ")}.`
149
+ );
150
+ const bytes = Buffer.from(blob, "base64");
151
+ const fingerprint = `SHA256:${createHash("sha256").update(bytes).digest("base64").replace(/=+$/, "")}`;
152
+ return { type, line: line.trim(), fingerprint, source, ...file ? { file } : {} };
153
+ }
154
+ function agentKeys() {
155
+ try {
156
+ return execFileSync2("ssh-add", ["-L"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n").filter((l) => l.trim());
157
+ } catch {
158
+ return [];
159
+ }
160
+ }
161
+ var isKeyLine = (s) => KEY_TYPES.some((t) => s.trim().startsWith(`${t} `));
162
+ function resolveKey(opts = {}) {
163
+ const { configured, agent = agentKeys, home = homedir2() } = opts;
164
+ if (configured) {
165
+ if (isKeyLine(configured)) return parseKeyLine(configured, "the configuration");
166
+ if (!existsSync2(configured)) throw new KeyError(`The configured key ${configured} doesn't exist.`);
167
+ return parseKeyLine(readFileSync2(configured, "utf8"), configured, configured);
168
+ }
169
+ const fromAgent = agent().find((l) => l.startsWith("ssh-ed25519 "));
170
+ if (fromAgent) return parseKeyLine(fromAgent, "ssh-agent");
171
+ const file = join2(home, ".ssh", "id_ed25519.pub");
172
+ if (existsSync2(file)) return parseKeyLine(readFileSync2(file, "utf8"), file, file);
173
+ throw new KeyError(
174
+ "No SSH key to sign with: add an ssh-ed25519 key to ssh-agent, create ~/.ssh/id_ed25519, or name one as `key` in .alterspec-client.json."
175
+ );
176
+ }
177
+ var blobOf = (line) => line.trim().split(/\s+/)[1];
178
+ function sign(key, data, agent = agentKeys) {
179
+ const inAgent = agent().some((l) => blobOf(l) === blobOf(key.line));
180
+ const temp = !key.file || inAgent ? mkdtempSync(join2(tmpdir(), "alterspec-client-")) : void 0;
181
+ try {
182
+ let keyFile;
183
+ if (inAgent || !key.file) {
184
+ if (!inAgent)
185
+ throw new KeyError(`ssh-agent doesn't hold the key ${key.fingerprint}: add it with ssh-add.`);
186
+ keyFile = join2(temp, "key.pub");
187
+ writeFileSync2(keyFile, key.line + "\n");
188
+ } else {
189
+ keyFile = key.file.replace(/\.pub$/, "");
190
+ if (keyFile === key.file || !existsSync2(keyFile))
191
+ throw new KeyError(
192
+ `No private key beside ${key.file} and ssh-agent doesn't hold it: add it with ssh-add.`
193
+ );
194
+ }
195
+ return execFileSync2("ssh-keygen", ["-q", "-Y", "sign", "-n", NAMESPACE, "-f", keyFile], {
196
+ input: data,
197
+ encoding: "utf8",
198
+ stdio: ["pipe", "pipe", "pipe"]
199
+ });
200
+ } catch (e) {
201
+ if (e instanceof KeyError) throw e;
202
+ const stderr = String(e.stderr ?? "").trim();
203
+ throw new KeyError(
204
+ `ssh-keygen could not sign with ${key.fingerprint}${stderr ? `: ${stderr}` : ""}. A key with a passphrase must be in ssh-agent (ssh-add).`
205
+ );
206
+ } finally {
207
+ if (temp) rmSync(temp, { recursive: true, force: true });
208
+ }
209
+ }
210
+
211
+ // src/auth.ts
212
+ var DispatcherError = class extends Error {
213
+ constructor(code, message, status) {
214
+ super(message);
215
+ this.code = code;
216
+ this.status = status;
217
+ }
218
+ };
219
+ var KeyRefused = class extends DispatcherError {
220
+ constructor(code, message, key) {
221
+ super(code, message);
222
+ this.key = key;
223
+ }
224
+ /** One sentence, and the key to send to the admin. */
225
+ get advice() {
226
+ return `The dispatcher refused your SSH key (${this.code}): send this public key to an admin, then reconnect the dispatcher server in Claude Code (/mcp).
227
+ ${this.key.line}
228
+ ${this.key.fingerprint}`;
229
+ }
230
+ };
231
+ var REFUSED = /* @__PURE__ */ new Set(["KEY_UNKNOWN", "DEVELOPER_UNKNOWN", "DEVELOPER_INACTIVE"]);
232
+ var MARGIN_MS = 6e4;
233
+ async function errorOf(res, key) {
234
+ let code = "HTTP_" + res.status;
235
+ let message = `The dispatcher answered ${res.status} ${res.statusText}.`;
236
+ try {
237
+ const body = await res.json();
238
+ if (body.error?.code) code = body.error.code;
239
+ if (body.error?.message) message = body.error.message;
240
+ } catch {
241
+ }
242
+ return REFUSED.has(code) ? new KeyRefused(code, message, key) : new DispatcherError(code, message, res.status);
243
+ }
244
+ var Session = class {
245
+ constructor(base, key, opts = {}) {
246
+ this.base = base;
247
+ this.key = key;
248
+ this.base = base.replace(/\/+$/, "");
249
+ this.fetchFn = opts.fetch ?? fetch;
250
+ this.now = opts.now ?? Date.now;
251
+ this.signer = opts.signer ?? sign;
252
+ }
253
+ token;
254
+ fetchFn;
255
+ now;
256
+ signer;
257
+ /** How many times this session signed in, for tests and logs. */
258
+ signIns = 0;
259
+ async call(path, init) {
260
+ try {
261
+ return await this.fetchFn(this.base + path, init);
262
+ } catch (e) {
263
+ throw new DispatcherError(
264
+ "UNREACHABLE",
265
+ `The dispatcher at ${this.base} can't be reached (${e.message}).`
266
+ );
267
+ }
268
+ }
269
+ async post(path, body) {
270
+ const res = await this.call(path, {
271
+ method: "POST",
272
+ headers: { "content-type": "application/json" },
273
+ body: JSON.stringify(body)
274
+ });
275
+ if (!res.ok) throw await errorOf(res, this.key);
276
+ return res.json();
277
+ }
278
+ async signIn() {
279
+ const { fingerprint } = this.key;
280
+ const { nonce } = await this.post("/auth/challenge", { fingerprint });
281
+ const signature = this.signer(this.key, nonce);
282
+ const t = await this.post("/auth/token", { fingerprint, nonce, signature });
283
+ this.token = { value: t.token, expires: Date.parse(t.expires_at) };
284
+ this.signIns++;
285
+ }
286
+ /** A valid token, signing in when there is none or it is about to run out. */
287
+ async bearer() {
288
+ if (!this.token || this.token.expires - MARGIN_MS <= this.now()) await this.signIn();
289
+ return this.token.value;
290
+ }
291
+ /**
292
+ * A request with the token. A 401 `UNAUTHENTICATED` (token expired or revoked) signs in again once and repeats
293
+ * the request; a refused key surfaces then as `KeyRefused`.
294
+ */
295
+ async fetch(path, init = {}) {
296
+ for (let attempt = 0; ; attempt++) {
297
+ const headers = new Headers(init.headers);
298
+ headers.set("authorization", `Bearer ${await this.bearer()}`);
299
+ const res = await this.call(path, { ...init, headers });
300
+ if (res.status !== 401 || attempt > 0) {
301
+ if (res.status === 401 || res.status === 403) throw await errorOf(res, this.key);
302
+ return res;
303
+ }
304
+ const err = await errorOf(res, this.key);
305
+ if (err.code !== "UNAUTHENTICATED") throw err;
306
+ this.token = void 0;
307
+ }
308
+ }
309
+ };
310
+ function keyOf(loaded) {
311
+ const key = loaded?.config.key;
312
+ const configured = key && !/^(ssh-ed25519|sk-ssh-ed25519@openssh\.com) /.test(key) ? configPath(loaded.root, key) : key;
313
+ return resolveKey({ configured });
314
+ }
315
+ var sessionOf = (loaded) => new Session(loaded.config.dispatcher, keyOf(loaded));
316
+
317
+ // ../src/export/read.ts
318
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "fs";
319
+ import { join as join3 } from "path";
320
+
321
+ // ../src/schemas/delta.ts
322
+ import { z as z6 } from "zod";
323
+
324
+ // ../src/schemas/change.ts
325
+ import { z as z5 } from "zod";
326
+
327
+ // ../src/schemas/common.ts
328
+ import { z as z4 } from "zod";
329
+
330
+ // ../src/schemas/ids.ts
331
+ import { z as z3 } from "zod";
332
+ var CODE = "[A-Z]{2,6}";
333
+ var NAME = "[A-Z0-9]+(?:-[A-Z0-9]+)*";
334
+ var CHANNEL_CODE = "[A-Z]{2,5}";
335
+ var ID_PATTERNS = {
336
+ app: "^APP$",
337
+ module: `^MOD-${CODE}$`,
338
+ capability: `^CAP-${CODE}-\\d{3}$`,
339
+ screen: `^SCR-${CODE}-\\d{2}$`,
340
+ role: `^ROLE-${NAME}$`,
341
+ persona: `^PER-${NAME}$`,
342
+ entity: `^ENT-${NAME}$`,
343
+ rule: `^RULE-(?:${CODE}-)?\\d{3}$`,
344
+ flow: "^FLOW-\\d{3}$",
345
+ event: `^EVT-${NAME}$`,
346
+ decision: "^DEC-\\d{3}$",
347
+ change: "^CHG-\\d{3}$",
348
+ integration: `^INT-${NAME}$`,
349
+ nfr: "^NFR-\\d{3}$",
350
+ acceptance: `^CAP-${CODE}-\\d{3}-AC-\\d{2}$`,
351
+ screenAction: "^A\\d{2}$",
352
+ experience: `^UX-SCR-${CODE}-\\d{2}-${CHANNEL_CODE}$`
353
+ };
354
+ var ID_REGEX = Object.fromEntries(
355
+ Object.entries(ID_PATTERNS).map(([k, p]) => [k, new RegExp(p)])
356
+ );
357
+ var idOf = (kind, label) => z3.string().regex(ID_REGEX[kind], { message: `must be a ${label} ID matching ${ID_PATTERNS[kind]}` });
358
+ var AppId = idOf("app", "application");
359
+ var ModuleId = idOf("module", "module");
360
+ var CapabilityId = idOf("capability", "capability");
361
+ var ScreenId = idOf("screen", "screen");
362
+ var ExperienceId = idOf("experience", "experience screen");
363
+ var RoleId = idOf("role", "role");
364
+ var IntegrationId = idOf("integration", "integration");
365
+ var NfrId = idOf("nfr", "non-functional requirement");
366
+ var PersonaId = idOf("persona", "persona");
367
+ var EntityId = idOf("entity", "entity");
368
+ var RuleId = idOf("rule", "rule");
369
+ var FlowId = idOf("flow", "flow");
370
+ var EventId = idOf("event", "event");
371
+ var DecisionId = idOf("decision", "decision");
372
+ var ChangeId = idOf("change", "change");
373
+ var AcceptanceId = idOf("acceptance", "acceptance criterion");
374
+ var ScreenActionId = idOf("screenAction", "screen action");
375
+ var ChannelCode = z3.string().regex(new RegExp(`^${CHANNEL_CODE}$`), { message: "must be 2\u20135 uppercase letters, e.g. WEB or MOB" });
376
+ var AnyId = z3.string().refine(
377
+ (v) => Object.keys(ID_REGEX).some((k) => k !== "screenAction" && ID_REGEX[k].test(v)),
378
+ { message: "must be a valid alterspec ID" }
379
+ );
380
+ var codeInId = (id) => /^(?:CAP|SCR|RULE)-([A-Z]{2,6})-/.exec(id)?.[1];
381
+ function idKind(id) {
382
+ return Object.keys(ID_REGEX).find((k) => ID_REGEX[k].test(id));
383
+ }
384
+
385
+ // ../src/schemas/common.ts
386
+ var Status = z4.enum(["draft", "ready", "signed_off"], {
387
+ error: (iss) => {
388
+ const was = {
389
+ refined: "refined is no longer a status; a complete object is ready",
390
+ approved: "approved is no longer a status; use signed_off",
391
+ implemented: "implemented is no longer a status (implementation is tracked by the teams, not in the spec)"
392
+ };
393
+ const said = typeof iss.input === "string" ? was[iss.input] : void 0;
394
+ return said ? `${said}; \`alterspec status migrate\` moves a spec to the current statuses` : void 0;
395
+ }
396
+ });
397
+ var Scope = z4.enum(["own", "team", "org", "all"]);
398
+ var Op = z4.enum(["C", "R", "U", "D", "A"]);
399
+ var Title = z4.string().trim().min(1, { message: "must not be empty" });
400
+ var Version = z4.number().int().min(1);
401
+ var StateName = z4.string().regex(/^[a-z][a-z0-9_]*$/, {
402
+ message: "must be a lowercase state name (letters, digits, underscore)"
403
+ });
404
+ var TransitionRef = z4.string().regex(/^[a-z][a-z0-9_]*->[a-z][a-z0-9_]*$/, {
405
+ message: "must be written as from->to, e.g. draft->active"
406
+ });
407
+ var list = (item) => z4.array(item).default([]);
408
+ var AcceptSchema = z4.object({
409
+ /** The lint rule's name. */
410
+ rule: z4.string().trim().min(1),
411
+ /** Part of the finding's message; absent, every finding of the rule on this object is accepted. */
412
+ match: z4.string().trim().min(1).optional(),
413
+ /** The decided `DEC-NNN` (kind decision) that records why, naming this object in `affects`. */
414
+ decision: DecisionId,
415
+ reason: z4.string().trim().min(1)
416
+ }).strict();
417
+
418
+ // ../src/schemas/change.ts
419
+ var ChangeStatus = z5.enum(["draft", "in_review", "signed_off", "rejected"], {
420
+ error: (iss) => iss.input === "applied" || iss.input === "approved" ? `${iss.input} is no longer a status: a change is merged into the spec when it is signed off; \`alterspec status migrate\` moves a spec to the current statuses` : void 0
421
+ });
422
+ var ObjectKey = z5.string().refine(
423
+ (v) => /^term:\S.*$/.test(v) || /^file:[\w./-]+\.md$/.test(v) || /^file:experience\/(?:[a-z]{2,5}\/)?mockups\/[\w./-]+$/.test(v) || v === "file:experience/data.js" || Object.keys(ID_REGEX).some(
424
+ (k) => k !== "screenAction" && k !== "acceptance" && ID_REGEX[k].test(v)
425
+ ),
426
+ { message: "must be a spec ID, term:<Term> or file:<path>" }
427
+ );
428
+ var ChangeSchema = z5.object({
429
+ id: ChangeId,
430
+ title: Title,
431
+ status: ChangeStatus,
432
+ created: z5.iso.date(),
433
+ /** The day the change was signed off and merged. Written by the CLI. */
434
+ signed_off: z5.iso.date().optional(),
435
+ /** Objects this change removes. */
436
+ removes: list(ObjectKey),
437
+ /**
438
+ * Fingerprint of each touched object when the change started touching it (null = new object).
439
+ * Written by the CLI; used to detect conflicts.
440
+ */
441
+ base: z5.record(z5.string(), z5.string().nullable()).default({}),
442
+ /**
443
+ * The earlier signed-off changes this one builds on: developers take it after them. Written by the CLI at sign-off
444
+ * once a baseline exists, never rewritten; `[]` builds on the baseline alone. Absent: signed off before the
445
+ * baseline, part of it.
446
+ */
447
+ depends_on: z5.array(ChangeId).optional(),
448
+ /**
449
+ * The tracks the change puts work on (`BE`, or the code of a channel with an experience of its own), each with the
450
+ * keys of its delta that put it there; `{}` = no work. Written by the CLI at sign-off next to `depends_on`, never
451
+ * rewritten, so a channel added later gives an old change no task.
452
+ */
453
+ tracks: z5.record(TrackCode, z5.array(z5.string())).optional(),
454
+ /** The first 16 hex of the sha256 of the change's `delta.json`, written with it at sign-off, never rewritten. */
455
+ delta: z5.string().regex(/^[0-9a-f]{16}$/).optional()
456
+ }).strict().superRefine((c, ctx) => {
457
+ for (const key of Object.keys(c.base)) {
458
+ if (!ObjectKey.safeParse(key).success) {
459
+ ctx.addIssue({ code: "custom", path: ["base", key], message: `${key} is not a valid object key` });
460
+ }
461
+ }
462
+ });
463
+
464
+ // ../src/schemas/delta.ts
465
+ var Fingerprint = z6.string().regex(/^[0-9a-f]{16}$/);
466
+ var Side = (t) => z6.object({ before: t.optional(), after: t.optional() }).strict();
467
+ var Binary = z6.object({ sha256: z6.string().regex(/^[0-9a-f]{64}$/), size: z6.number().int() }).strict();
468
+ var DeltaChange = z6.enum(["added", "modified", "removed", "moved"]);
469
+ var DeltaEntrySchema = z6.object({
470
+ key: ObjectKey,
471
+ kind: z6.enum(["doc", "item", "prose"]),
472
+ change: DeltaChange,
473
+ file: Side(z6.string()),
474
+ /** The object's status before and after, when it has one. */
475
+ status: Side(z6.string()).optional(),
476
+ /** Whether the export held the object before and after the sign-off (`buildBundle`). */
477
+ exported: z6.object({ before: z6.boolean(), after: z6.boolean() }).strict(),
478
+ fingerprint: Side(Fingerprint),
479
+ /** The text without generated blocks; absent for a binary file and for a side the object has no content on. */
480
+ before: z6.string().optional(),
481
+ after: z6.string().optional(),
482
+ /** A binary file (an image): its hash and size instead of its text. */
483
+ binary: Side(Binary).optional()
484
+ }).strict();
485
+ var DeltaSchema = z6.object({
486
+ change: ChangeId,
487
+ title: z6.string(),
488
+ signed_off: z6.iso.date().optional(),
489
+ /** `git`: rebuilt afterwards from the repository's history by `alterspec migrate changes`. */
490
+ recovered: z6.literal("git").optional(),
491
+ /** In the export: which objects it shows in export terms only (see the export README). */
492
+ view: z6.literal("export").optional(),
493
+ objects: z6.array(DeltaEntrySchema),
494
+ /** Objects a rebuilt delta could not recover, with why. */
495
+ unrecoverable: z6.array(z6.object({ key: z6.string(), why: z6.string() }).strict()).optional()
496
+ }).strict();
497
+
498
+ // ../src/changes/delta-record.ts
499
+ var DELTA_JSON = "delta.json";
500
+ function parseDelta(json) {
501
+ try {
502
+ const parsed = DeltaSchema.safeParse(JSON.parse(json));
503
+ return parsed.success ? parsed.data : void 0;
504
+ } catch {
505
+ return void 0;
506
+ }
507
+ }
508
+ function exportChange(e) {
509
+ const { before, after } = e.exported;
510
+ if (before && after) return e.change;
511
+ if (after) return "enters the export";
512
+ if (before) return "leaves the export";
513
+ return "not in the export";
514
+ }
515
+
516
+ // ../src/lib/frontmatter-split.ts
517
+ var FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
518
+ function splitFrontMatter(source) {
519
+ const m = FRONT_MATTER.exec(source);
520
+ if (!m) return { raw: void 0, body: source, bodyLine: 1 };
521
+ return {
522
+ raw: m[1] ?? "",
523
+ body: source.slice(m[0].length),
524
+ bodyLine: m[0].split("\n").length - (m[0].endsWith("\n") ? 0 : 1)
525
+ };
526
+ }
527
+
528
+ // ../src/spec/layout.ts
529
+ var ROOT_DOCS = {
530
+ application: "application.md",
531
+ "personas-roles": "personas-roles.md",
532
+ glossary: "glossary.md",
533
+ rules: "rules.md",
534
+ events: "events.md",
535
+ decisions: "decisions.md",
536
+ integrations: "integrations.md",
537
+ nfr: "nfr.md"
538
+ };
539
+ var APPLICATION = ROOT_DOCS.application;
540
+ var MODULES_DIR = "modules";
541
+ var CHANGES_DIR = "changes";
542
+ var moduleDir = (code) => `${MODULES_DIR}/${code.replace(/^MOD-/, "").toLowerCase()}`;
543
+ var moduleDirOf = (id) => {
544
+ const code = codeInId(id);
545
+ return code ? moduleDir(code) : void 0;
546
+ };
547
+ var screenDir = (screenId) => `${moduleDirOf(screenId)}/screens/${screenId}`;
548
+ var contractPath = (screenId, code) => `${screenDir(screenId)}/experience/${code.toLowerCase()}.md`;
549
+ var EXPERIENCE_DIR = "experience";
550
+ var surfaceDir = (code) => `${EXPERIENCE_DIR}/${code.toLowerCase()}`;
551
+ var mockupPath = (code, screenId) => `${surfaceDir(code)}/mockups/${screenId}.html`;
552
+ var patternsPath = (code) => `${surfaceDir(code)}/patterns.md`;
553
+ var designSystemPath = (code) => `${surfaceDir(code)}/design-system.md`;
554
+ var OPERATIONS_FILE = "_generated/operations.md";
555
+ var changesDir = (mod) => mod ? `${moduleDir(mod)}/${CHANGES_DIR}` : CHANGES_DIR;
556
+ var archiveDir = (mod) => `${changesDir(mod)}/archive`;
557
+ var CHANGE_PREFIX = String.raw`^(?:${MODULES_DIR}\/[^/]+\/)?${CHANGES_DIR}\/`;
558
+ var CHANGE_FILE = new RegExp(CHANGE_PREFIX);
559
+ var ARCHIVED_FILE = new RegExp(`${CHANGE_PREFIX}archive\\/`);
560
+ var OVERLAY_FILE = new RegExp(`${CHANGE_PREFIX}[^/]+\\/spec\\/`);
561
+ var WORK_FILE = new RegExp(`${CHANGE_PREFIX}[^/]+\\/(?:impact|groom(?:-[^/]+)?)\\.md$`);
562
+ var PROPOSAL_FILE = new RegExp(
563
+ String.raw`^(?:${MODULES_DIR}\/(?<mod>[^/]+)\/)?${CHANGES_DIR}\/(?<change>[^/]+)\/proposal\.md$`
564
+ );
565
+ var ARCHIVED_PROPOSAL = new RegExp(
566
+ String.raw`^(?:${MODULES_DIR}\/(?<mod>[^/]+)\/)?${CHANGES_DIR}\/archive\/(?<change>[^/]+)\/proposal\.md$`
567
+ );
568
+
569
+ // ../src/export/paths.ts
570
+ var EXPORT_JSON = "export.json";
571
+ var WORK_JSON = "work.json";
572
+ var SHARDS_DIR = "_shards";
573
+ var slug = (text) => text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[đłøæœßþ]/g, (c) => ({ \u0111: "d", \u0142: "l", \u00F8: "o", \u00E6: "ae", \u0153: "oe", \u00DF: "ss", \u00FE: "th" })[c] ?? c).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "section";
574
+ var shardDir = (path) => `${SHARDS_DIR}/${path.replace(/\.md$/, "")}`;
575
+ var itemShardName = (key) => `${key.startsWith("term:") ? slug(key.slice(5)) : key}.md`;
576
+ var itemShardPath = (path, key) => `${shardDir(path)}/${itemShardName(key)}`;
577
+ var isSectionShard = (name, heading) => new RegExp(`^\\d{2}-${slug(heading)}\\.md$`).test(name);
578
+
579
+ // ../src/export/read.ts
580
+ var ExportReadError = class extends Error {
581
+ };
582
+ function readJson(dir, name) {
583
+ const path = join3(dir, name);
584
+ if (!existsSync3(path)) throw new ExportReadError(`${dir} is not an alterspec export: it has no ${name}.`);
585
+ try {
586
+ return JSON.parse(readFileSync3(path, "utf8"));
587
+ } catch {
588
+ throw new ExportReadError(`${join3(dir, name)} is not valid JSON.`);
589
+ }
590
+ }
591
+ function readExport(dir) {
592
+ const exp = readJson(dir, EXPORT_JSON);
593
+ const parsed = AnyWorkSchema.safeParse(readJson(dir, WORK_JSON));
594
+ if (!parsed.success)
595
+ throw new ExportReadError(`${join3(dir, WORK_JSON)} is not a work.json this client reads.`);
596
+ const sources = new Map((exp.sources ?? []).map((s) => [s.id, s]));
597
+ const has = (path) => existsSync3(join3(dir, path));
598
+ const read = (path) => has(path) ? readFileSync3(join3(dir, path), "utf8") : void 0;
599
+ const modules = () => existsSync3(join3(dir, "modules")) ? readdirSync(join3(dir, "modules")).map((m) => moduleDir(m)) : [];
600
+ const shards = (file) => {
601
+ const folder = shardDir(file);
602
+ return has(folder) ? readdirSync(join3(dir, folder)).sort().map((n) => `${folder}/${n}`) : [];
603
+ };
604
+ const proposalPath = (change) => [archiveDir(), ...modules().map((m) => `${m}/changes/archive`)].map((a) => `${a}/${change}/proposal.md`).find(has);
605
+ return {
606
+ dir,
607
+ work: parsed.data,
608
+ sources,
609
+ has,
610
+ read,
611
+ fileOf(key) {
612
+ if (key.startsWith("file:")) return key.slice(5);
613
+ if (key.startsWith("term:")) return ROOT_DOCS.glossary;
614
+ return sources.get(key)?.file;
615
+ },
616
+ proposalPath,
617
+ delta(change) {
618
+ const proposal = proposalPath(change);
619
+ const json = proposal && read(proposal.replace(/proposal\.md$/, DELTA_JSON));
620
+ return json ? parseDelta(json) : void 0;
621
+ },
622
+ shards,
623
+ sectionShard(file, heading) {
624
+ const prefix = `${shardDir(file)}/`;
625
+ return shards(file).find((p) => isSectionShard(p.slice(prefix.length), heading));
626
+ },
627
+ itemShard(file, key) {
628
+ const path = itemShardPath(file, key);
629
+ return has(path) ? path : void 0;
630
+ }
631
+ };
632
+ }
633
+ function idsIn(text, kinds) {
634
+ const pattern = new RegExp(
635
+ kinds.map((k) => `(?:${ID_PATTERNS[k].replace(/^\^|\$$/g, "")})`).join("|"),
636
+ "g"
637
+ );
638
+ const out = [];
639
+ for (const m of text.matchAll(new RegExp(`(?<![A-Z0-9-])(?:${pattern.source})(?![A-Z0-9-])`, "g")))
640
+ if (!out.includes(m[0])) out.push(m[0]);
641
+ return out;
642
+ }
643
+ var frontMatterOf = (text) => splitFrontMatter(text).raw ?? "";
644
+
645
+ // ../src/lib/diff.ts
646
+ var linesOf = (text) => text === "" ? [] : text.replace(/\n$/, "").split("\n");
647
+ function diffLines(a, b) {
648
+ const x = linesOf(a);
649
+ const y = linesOf(b);
650
+ const n = x.length;
651
+ const m = y.length;
652
+ const max = n + m;
653
+ const v = /* @__PURE__ */ new Map([[1, 0]]);
654
+ const trace = [];
655
+ outer: for (let d = 0; d <= max; d++) {
656
+ trace.push(new Map(v));
657
+ for (let k = -d; k <= d; k += 2) {
658
+ let i2 = k === -d || k !== d && (v.get(k - 1) ?? -1) < (v.get(k + 1) ?? -1) ? v.get(k + 1) ?? 0 : (v.get(k - 1) ?? 0) + 1;
659
+ let j2 = i2 - k;
660
+ while (i2 < n && j2 < m && x[i2] === y[j2]) {
661
+ i2++;
662
+ j2++;
663
+ }
664
+ v.set(k, i2);
665
+ if (i2 >= n && j2 >= m) break outer;
666
+ }
667
+ }
668
+ const out = [];
669
+ let i = n;
670
+ let j = m;
671
+ for (let d = trace.length - 1; d >= 0; d--) {
672
+ const vd = trace[d];
673
+ const k = i - j;
674
+ const down = k === -d || k !== d && (vd.get(k - 1) ?? -1) < (vd.get(k + 1) ?? -1);
675
+ const pk = down ? k + 1 : k - 1;
676
+ const pi = vd.get(pk) ?? 0;
677
+ const pj = pi - pk;
678
+ while (i > pi && j > pj) {
679
+ out.push({ op: " ", text: x[--i] });
680
+ j--;
681
+ }
682
+ if (d > 0) {
683
+ if (down) out.push({ op: "+", text: y[--j] });
684
+ else out.push({ op: "-", text: x[--i] });
685
+ }
686
+ }
687
+ return out.reverse();
688
+ }
689
+ function unifiedDiff(a, b, context = 3) {
690
+ const lines = diffLines(a, b);
691
+ const changed = lines.map((l, i) => l.op === " " ? -1 : i).filter((i) => i >= 0);
692
+ if (!changed.length) return "";
693
+ const hunks = [];
694
+ for (const i of changed) {
695
+ const from = Math.max(0, i - context);
696
+ const to = Math.min(lines.length, i + context + 1);
697
+ const last = hunks[hunks.length - 1];
698
+ if (last && from <= last[1]) last[1] = to;
699
+ else hunks.push([from, to]);
700
+ }
701
+ const out = [];
702
+ for (const [from, to] of hunks) {
703
+ let ai = 1;
704
+ let bi = 1;
705
+ for (const l of lines.slice(0, from)) {
706
+ if (l.op !== "+") ai++;
707
+ if (l.op !== "-") bi++;
708
+ }
709
+ const body = lines.slice(from, to);
710
+ const aLen = body.filter((l) => l.op !== "+").length;
711
+ const bLen = body.filter((l) => l.op !== "-").length;
712
+ out.push(`@@ -${aLen ? ai : ai - 1},${aLen} +${bLen ? bi : bi - 1},${bLen} @@`);
713
+ for (const l of body) out.push(`${l.op}${l.text}`);
714
+ }
715
+ return out.join("\n");
716
+ }
717
+
718
+ // src/context.ts
719
+ var ContextError = class extends Error {
720
+ };
721
+ var shardText = (x, path) => path ? x.read(path)?.replace(/^<!-- source: [^\n]*-->\n\n/, "").trim() : void 0;
722
+ var sectionText = (x, path) => shardText(x, path)?.replace(/^## [^\n]*\n*/, "");
723
+ var screenOf = (key) => /^UX-(SCR-[A-Z]{2,6}-\d{2})-[A-Z]{2,5}$/.exec(key)?.[1] ?? /^file:experience\/[a-z]{2,5}\/mockups\/(SCR-[A-Z]{2,6}-\d{2})\.html$/.exec(key)?.[1] ?? (/^SCR-[A-Z]{2,6}-\d{2}$/.test(key) ? key : void 0);
724
+ function objectBrief(x, key, entry, why) {
725
+ const file = x.fileOf(key);
726
+ const held = file !== void 0 && x.has(file);
727
+ const brief = { key, ...held ? { file } : {} };
728
+ if (held && x.shards(file).length) brief.shards = x.shards(file)[0].replace(/\/[^/]+$/, "");
729
+ if (why) brief.unrecoverable = why;
730
+ if (!entry) return brief;
731
+ brief.change = exportChange(entry);
732
+ if (entry.status) brief.status = entry.status;
733
+ if (entry.before !== void 0 || entry.after !== void 0) {
734
+ const d = unifiedDiff(entry.before ?? "", entry.after ?? "");
735
+ if (d) brief.diff = d;
736
+ } else if (entry.binary) {
737
+ brief.diff = `binary: ${[entry.binary.before, entry.binary.after].map((b) => b ? `${b.size} bytes` : "\u2014").join(" \u2192 ")}`;
738
+ }
739
+ return brief;
740
+ }
741
+ var KIND_WORDS = {
742
+ app: "the application",
743
+ module: "module",
744
+ capability: "capability",
745
+ screen: "screen",
746
+ experience: "experience screen",
747
+ role: "role",
748
+ integration: "integration",
749
+ nfr: "non-functional requirement",
750
+ persona: "persona",
751
+ entity: "entity",
752
+ rule: "rule",
753
+ flow: "flow",
754
+ event: "event",
755
+ decision: "decision"
756
+ };
757
+ function titleOf(x, id) {
758
+ const file = x.fileOf(id);
759
+ if (!file || !x.has(file)) return void 0;
760
+ const shard = x.itemShard(file, id);
761
+ if (shard) return /^## \S+ (.+)$/m.exec(shardText(x, shard) ?? "")?.[1]?.trim();
762
+ return /^# (.+)$/m.exec(splitFrontMatter(x.read(file)).body)?.[1]?.trim();
763
+ }
764
+ var named = (x, id) => {
765
+ const title = titleOf(x, id);
766
+ return title ? `${id} ${title}` : `${id} (not in the export now)`;
767
+ };
768
+ function criterionOf(x, cap, id) {
769
+ const file = x.fileOf(cap);
770
+ const text = file && x.has(file) ? sectionText(x, x.sectionShard(file, "Acceptance criteria")) : void 0;
771
+ const chunk = text?.split(/^### /m).find((c) => c.split(/\s/)[0] === id);
772
+ if (!chunk) return void 0;
773
+ const lines = chunk.split("\n").slice(1).map(
774
+ (l) => l.replace(/^\s*[-*]\s*/, "").replace(/\*\*/g, "").trim()
775
+ ).filter(Boolean);
776
+ const then = lines.findIndex((l) => /^Then\b/.test(l));
777
+ const kept = (then >= 0 ? lines.slice(then) : lines).filter((l) => !/^Covers:/.test(l));
778
+ return kept.join(" ") || void 0;
779
+ }
780
+ function itemWhat(x, item) {
781
+ const ac = /^((CAP-[A-Z]{2,6}-\d{3})-AC-\d{2})$/.exec(item);
782
+ if (ac) {
783
+ const then = criterionOf(x, ac[2], ac[1]);
784
+ return `acceptance criterion of ${named(x, ac[2])}${then ? `: ${then}` : ""}`;
785
+ }
786
+ const action = /^(SCR-[A-Z]{2,6}-\d{2})\.(A\d{2})$/.exec(item);
787
+ if (action) {
788
+ const [, scr, a] = action;
789
+ const file = x.fileOf(scr);
790
+ const actions = file && x.has(file) ? sectionText(x, x.sectionShard(file, "Actions")) : void 0;
791
+ const line = actions?.split("\n").map((l) => l.replace(/^\s*[-*]\s*/, "").trim()).find((l) => l.startsWith(`${a} `));
792
+ const label = line?.slice(a.length).trim();
793
+ return `action ${a}${label ? ` "${label.replace(/\s*→\s*/, '" \u2192 ')}` : ""}${label && !label.includes("\u2192") ? '"' : ""} on ${named(x, scr)}`;
794
+ }
795
+ const state = /^(UX-(SCR-[A-Z]{2,6}-\d{2})-[A-Z]{2,5})#(.+)$/.exec(item);
796
+ if (state) {
797
+ const [, ux, scr, id] = state;
798
+ const rule = /^rule-(.+)$/.exec(id)?.[1];
799
+ return `state "${id}" of ${ux} (${named(x, scr)})${rule ? `: the message of RULE-${rule.toUpperCase()}` : ""}`;
800
+ }
801
+ if (item.startsWith("file:")) {
802
+ const path = item.slice(5);
803
+ const page = /\/mockups\/(SCR-[A-Z]{2,6}-\d{2})\.html$/.exec(path)?.[1];
804
+ const what = page ? `the mockup page of ${page}` : /\/design-system\.md$/.test(path) ? "the channel\u2019s design system" : /\/patterns\.md$/.test(path) ? "the channel\u2019s patterns" : "a file of the channel\u2019s experience";
805
+ return `${what}: \`${path}\`${x.has(path) ? "" : " (not in the export now)"}`;
806
+ }
807
+ if (item.startsWith("term:")) return `glossary term "${item.slice(5)}"`;
808
+ const kind = idKind(item);
809
+ return `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ""}${named(x, item)}`;
810
+ }
811
+ function taskContext(x, task, exportDir2, state = {}) {
812
+ const change = x.work.changes.find((c) => c.id === task.change);
813
+ if (!change) throw new ContextError(`${task.change} is not in this export's work.json: pull the export.`);
814
+ const work = change.tasks.find((t) => t.track === task.track);
815
+ if (!work)
816
+ throw new ContextError(
817
+ `${task.change} has no task on ${task.track}: its tracks are ${change.tasks.map((t) => t.track).join(", ") || "none"}.`
818
+ );
819
+ const track = x.work.tracks.find((t) => t.code === task.track);
820
+ const proposal = x.proposalPath(task.change);
821
+ if (!proposal) throw new ContextError(`The export holds no archived proposal of ${task.change}.`);
822
+ const delta = x.delta(task.change);
823
+ const entries = new Map(delta?.objects.map((e) => [e.key, e]));
824
+ const lost = new Map(delta?.unrecoverable?.map((u) => [u.key, u.why]));
825
+ const items = work.items;
826
+ const ctx = {
827
+ task: task.id,
828
+ ...items ? {
829
+ checklist: {
830
+ items: items.map((item) => {
831
+ const covered = state.covered?.get(item);
832
+ return { item, what: itemWhat(x, item), ...covered ? { covered } : {} };
833
+ }),
834
+ known: state.covered !== void 0,
835
+ ...state.unknown ? { note: state.unknown } : {}
836
+ }
837
+ } : {},
838
+ export: exportDir2,
839
+ change: {
840
+ id: change.id,
841
+ title: change.title,
842
+ signed_off: change.signed_off,
843
+ level: change.level,
844
+ depends_on: change.depends_on
845
+ },
846
+ track,
847
+ after: work.after,
848
+ proposal: {
849
+ path: proposal,
850
+ why: sectionText(x, x.sectionShard(proposal, "Why")),
851
+ what: sectionText(x, x.sectionShard(proposal, "What changes"))
852
+ },
853
+ ...delta ? { delta: proposal.replace(/proposal\.md$/, "delta.md") } : {},
854
+ objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key)))
855
+ };
856
+ if (track.kind === "backend") {
857
+ const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)));
858
+ const named2 = (kind) => [
859
+ .../* @__PURE__ */ new Set([
860
+ ...work.objects.filter((k) => idsIn(k, [kind]).length === 1 && idsIn(k, [kind])[0] === k),
861
+ ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c))), [kind]))
862
+ ])
863
+ ];
864
+ const items2 = (ids) => ids.flatMap((id) => {
865
+ const file = x.fileOf(id);
866
+ const path = file && x.itemShard(file, id);
867
+ return path ? [{ id, path, text: shardText(x, path) }] : [];
868
+ });
869
+ ctx.acceptance = capabilities.flatMap((id) => {
870
+ const path = x.sectionShard(x.fileOf(id), "Acceptance criteria");
871
+ return path ? [{ id, path, text: sectionText(x, path) }] : [];
872
+ });
873
+ ctx.rules = items2(named2("rule"));
874
+ ctx.events = items2(named2("event"));
875
+ ctx.operations = x.has(OPERATIONS_FILE) ? capabilities.flatMap((id) => {
876
+ const path = x.shards(OPERATIONS_FILE).find((p) => new RegExp(`/\\d{2}-${slug(id)}(-|\\.md$)`).test(p));
877
+ return path ? [{ id, path, text: shardText(x, path) }] : [];
878
+ }) : [];
879
+ } else {
880
+ const existing = (p) => x.has(p) ? p : void 0;
881
+ const screens = [...new Set(work.objects.map(screenOf).filter((s) => !!s))];
882
+ ctx.screens = screens.map((id) => ({
883
+ id,
884
+ file: x.fileOf(id),
885
+ contract: existing(contractPath(id, track.code)),
886
+ page: existing(mockupPath(track.code, id))
887
+ }));
888
+ ctx.design = {
889
+ designSystem: existing(designSystemPath(track.code)),
890
+ patterns: existing(patternsPath(track.code))
891
+ };
892
+ }
893
+ return ctx;
894
+ }
895
+ var fence = (text, lang = "") => {
896
+ const ticks = "`".repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map((m) => m[0].length + 1)));
897
+ return `${ticks}${lang}
898
+ ${text}
899
+ ${ticks}`;
900
+ };
901
+ function renderContext(c) {
902
+ const out = [
903
+ `# ${c.task}: ${c.change.title}`,
904
+ "",
905
+ `Track ${c.track.code} (${c.track.kind}${c.track.channels.length ? `: ${c.track.channels.join(", ")}` : ""}). Change ${c.change.id}, signed off ${c.change.signed_off}, level ${c.change.level}. Paths are relative to the export, ${c.export}.`
906
+ ];
907
+ if (c.after.length) out.push("", `Waits for: ${c.after.map((a) => `${a.change}/${a.track}`).join(", ")}.`);
908
+ out.push("");
909
+ if (!c.checklist)
910
+ out.push("This export has no checklist (work.json format 1): the task\u2019s progress is its status only.");
911
+ else {
912
+ const list2 = c.checklist;
913
+ const done = list2.items.filter((i) => i.covered).length;
914
+ out.push(
915
+ `## Checklist (${list2.known ? `${done} of ${list2.items.length} covered` : `${list2.items.length} item${list2.items.length === 1 ? "" : "s"}`})`,
916
+ "",
917
+ "Name an item in `Alterspec-Covers` on the commit with which its tests pass.",
918
+ ...list2.note ? ["", `Covered items unknown: ${list2.note}`] : [],
919
+ "",
920
+ ...list2.items.map(
921
+ (i) => `- [${i.covered ? "x" : " "}] \`${i.item}\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ""}`
922
+ )
923
+ );
924
+ }
925
+ out.push("", `## Why (${c.proposal.path})`, "", c.proposal.why || "(none written)");
926
+ out.push("", "## What changes", "", c.proposal.what || "(none written)");
927
+ out.push("", "## The task\u2019s objects", "");
928
+ if (c.delta) out.push(`The whole record of the change: ${c.delta}.`, "");
929
+ for (const o of c.objects) {
930
+ const where = o.file ? `\`${o.file}\`${o.shards ? `, shards in \`${o.shards}/\`` : ""}` : "not in the export now";
931
+ const status = o.status && o.status.before !== o.status.after ? `, ${o.status.before ?? "\u2014"} \u2192 ${o.status.after ?? "\u2014"}` : "";
932
+ out.push(`### ${o.key}`, "", `${o.change ?? "no delta entry"}${status}; ${where}.`);
933
+ if (o.unrecoverable) out.push("", `The delta could not recover it: ${o.unrecoverable}.`);
934
+ if (o.diff) out.push("", o.diff.startsWith("binary:") ? o.diff : fence(o.diff, "diff"));
935
+ out.push("");
936
+ }
937
+ const pieces = (title, list2) => {
938
+ if (!list2?.length) return;
939
+ out.push(`## ${title}`, "");
940
+ for (const p of list2) out.push(`### ${p.id} (\`${p.path}\`)`, "", p.text ?? "", "");
941
+ };
942
+ pieces("Acceptance criteria", c.acceptance);
943
+ pieces("Rules", c.rules);
944
+ pieces("Events", c.events);
945
+ pieces("Operations for other systems", c.operations);
946
+ if (c.screens) {
947
+ out.push("## Screens", "");
948
+ for (const s of c.screens) {
949
+ out.push(`- **${s.id}**: \`${s.file ?? "not in the export"}\``);
950
+ if (s.contract) out.push(` - experience contract: \`${s.contract}\``);
951
+ if (s.page) out.push(` - mockup page: \`${s.page}\``);
952
+ }
953
+ out.push("");
954
+ if (c.design?.designSystem || c.design?.patterns)
955
+ out.push(
956
+ "## The channel\u2019s design",
957
+ "",
958
+ ...[c.design.designSystem, c.design.patterns].filter(Boolean).map((p) => `- \`${p}\``),
959
+ ""
960
+ );
961
+ }
962
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
963
+ }
964
+
965
+ // src/git.ts
966
+ import { execFileSync as execFileSync3 } from "child_process";
967
+ import { existsSync as existsSync4, realpathSync } from "fs";
968
+ import { join as join4, resolve as resolve2 } from "path";
969
+
970
+ // src/task.ts
971
+ var TRAILER = "Alterspec-Task";
972
+ var TaskError = class extends Error {
973
+ };
974
+ function parseTask(text) {
975
+ const m = /^(CHG-\d{3})\/([A-Z]{2,5})$/.exec(text.trim().toUpperCase());
976
+ if (!m)
977
+ throw new TaskError(`"${text}" is not a task: write it as CHG-012/BE (the change, a slash, the track).`);
978
+ return { id: `${m[1]}/${m[2]}`, change: m[1], track: m[2] };
979
+ }
980
+ var branchOf = (t) => `task/${t.change.toLowerCase()}-${t.track.toLowerCase()}`;
981
+ var folderOf = (t) => `${t.change.toLowerCase()}-${t.track.toLowerCase()}`;
982
+ var COVERS = "Alterspec-Covers";
983
+ function taskOfBranch(branch) {
984
+ const m = /^task\/(chg-\d{3})-([a-z]{2,5})$/.exec(branch?.trim() ?? "");
985
+ return m ? parseTask(`${m[1]}/${m[2]}`) : void 0;
986
+ }
987
+
988
+ // src/git.ts
989
+ var GitError = class extends Error {
990
+ };
991
+ function git2(cwd, args) {
992
+ try {
993
+ return execFileSync3("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
994
+ } catch (e) {
995
+ const stderr = String(e.stderr ?? "").trim();
996
+ throw new GitError(`git ${args.join(" ")} failed in ${cwd}${stderr ? `: ${stderr}` : ""}`);
997
+ }
998
+ }
999
+ var tryGit = (cwd, args) => {
1000
+ try {
1001
+ return git2(cwd, args);
1002
+ } catch {
1003
+ return void 0;
1004
+ }
1005
+ };
1006
+ var isAncestor = (cwd, a, b) => tryGit(cwd, ["merge-base", "--is-ancestor", a, b]) !== void 0;
1007
+ function exportHead(dir, latest) {
1008
+ if (!existsSync4(join4(dir, ".git")) && tryGit(dir, ["rev-parse", "--git-dir"]) === void 0)
1009
+ throw new GitError(`${dir} is not a clone of the export repository.`);
1010
+ const pulled = tryGit(dir, ["pull", "--ff-only", "--quiet"]) !== void 0;
1011
+ const head = git2(dir, ["rev-parse", "HEAD"]);
1012
+ if (!latest) return { head, pulled, send: head, behind: 0 };
1013
+ const known = tryGit(dir, ["rev-parse", "--verify", "--quiet", `${latest}^{commit}`]);
1014
+ if (!known) {
1015
+ if (!pulled) return { head, pulled, latest, send: head, behind: null };
1016
+ throw rewritten(latest);
1017
+ }
1018
+ if (known === head) return { head, pulled, latest, send: head, behind: 0 };
1019
+ if (isAncestor(dir, known, head)) return { head, pulled, latest, send: known, behind: 0 };
1020
+ if (isAncestor(dir, head, known))
1021
+ return {
1022
+ head,
1023
+ pulled,
1024
+ latest,
1025
+ send: head,
1026
+ behind: Number(git2(dir, ["rev-list", "--count", `${head}..${known}`]))
1027
+ };
1028
+ throw rewritten(latest);
1029
+ }
1030
+ var rewritten = (latest) => new GitError(
1031
+ `The export's history was rewritten: the dispatcher's latest export ${latest.slice(0, 12)} and your clone don't follow each other. Stop and tell an admin.`
1032
+ );
1033
+ function mainBranch(repo, configured) {
1034
+ if (configured) return configured;
1035
+ const head = tryGit(repo, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
1036
+ return head?.replace(/^origin\//, "") || "main";
1037
+ }
1038
+ var branchExists = (repo, branch) => tryGit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]) !== void 0;
1039
+ function taskWorktree(repo, task, opts) {
1040
+ const branch = branchOf(task);
1041
+ tryGit(repo, ["fetch", "--quiet", "origin", opts.main]);
1042
+ const base = `origin/${opts.main}`;
1043
+ if (opts.here) {
1044
+ const top = git2(repo, ["rev-parse", "--show-toplevel"]);
1045
+ if (tryGit(repo, ["symbolic-ref", "--short", "HEAD"]) === branch)
1046
+ return { path: top, branch, created: false };
1047
+ if (git2(repo, ["status", "--porcelain", "--untracked-files=no"]))
1048
+ throw new GitError(
1049
+ `This checkout has uncommitted work: commit or stash it before switching to ${branch}.`
1050
+ );
1051
+ if (branchExists(repo, branch)) {
1052
+ git2(repo, ["switch", "--quiet", branch]);
1053
+ return { path: top, branch, created: false };
1054
+ }
1055
+ git2(repo, ["switch", "--quiet", "--no-track", "-c", branch, base]);
1056
+ return { path: top, branch, created: true };
1057
+ }
1058
+ const path = resolve2(opts.worktreesDir, folderOf(task));
1059
+ const listed = git2(repo, ["worktree", "list", "--porcelain"]).split("\n").filter((l) => l.startsWith("worktree ")).map((l) => real(l.slice("worktree ".length)));
1060
+ if (listed.includes(real(path))) return { path, branch, created: false };
1061
+ if (branchExists(repo, branch)) git2(repo, ["worktree", "add", "--quiet", path, branch]);
1062
+ else git2(repo, ["worktree", "add", "--quiet", "--no-track", "-b", branch, path, base]);
1063
+ return { path, branch, created: true };
1064
+ }
1065
+ var real = (path) => existsSync4(path) ? realpathSync(path) : resolve2(path);
1066
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
1067
+ function mergedCommit(repo, task, main) {
1068
+ tryGit(repo, ["fetch", "--quiet", "origin", main]);
1069
+ const target = `origin/${main}`;
1070
+ if (!tryGit(repo, ["rev-parse", "--verify", "--quiet", target]))
1071
+ throw new GitError(`There is no ${target} here: is "${main}" the track's main branch?`);
1072
+ const trailer = new RegExp(`^${TRAILER}:\\s*${escape(task.id)}\\s*$`, "mi");
1073
+ const branch = new RegExp(`(^|[\\s'"/:])${escape(branchOf(task))}($|[\\s'".,)])`, "m");
1074
+ const log = git2(repo, ["log", "--first-parent", "--format=%H%x1f%P%x1f%B%x1e", target]);
1075
+ for (const record of log.split("")) {
1076
+ const [sha, parents, body] = record.trim().split("");
1077
+ if (!sha || body === void 0) continue;
1078
+ if (trailer.test(body)) return sha;
1079
+ if (parents.trim().includes(" ") && branch.test(body)) return sha;
1080
+ }
1081
+ const carrying = git2(repo, ["log", "--format=%H", "-F", `--grep=${TRAILER}: ${task.id}`, target]).split("\n").filter(Boolean).find((sha) => trailer.test(git2(repo, ["show", "-s", "--format=%B", sha])));
1082
+ if (!carrying) return void 0;
1083
+ return git2(repo, [
1084
+ "rev-list",
1085
+ "--first-parent",
1086
+ "--ancestry-path",
1087
+ "--reverse",
1088
+ `${carrying}..${target}`
1089
+ ]).split("\n")[0];
1090
+ }
1091
+
1092
+ // src/install.ts
1093
+ import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync5, readdirSync as readdirSync3, statSync, writeFileSync as writeFileSync4 } from "fs";
1094
+ import { join as join6, relative } from "path";
1095
+ import { fileURLToPath } from "url";
1096
+
1097
+ // ../src/install/installer.ts
1098
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync4, readdirSync as readdirSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
1099
+ import { dirname as dirname2, join as join5 } from "path";
1100
+
1101
+ // ../src/install/hash.ts
1102
+ import { createHash as createHash2 } from "crypto";
1103
+ var sha256 = (content) => createHash2("sha256").update(content).digest("hex");
1104
+
1105
+ // ../src/install/installer.ts
1106
+ var MANIFEST_PATH = ".alterspec/manifest.json";
1107
+ function readManifest(root, path = MANIFEST_PATH) {
1108
+ const p = join5(root, path);
1109
+ if (!existsSync5(p)) return void 0;
1110
+ try {
1111
+ return JSON.parse(readFileSync4(p, "utf8"));
1112
+ } catch {
1113
+ return void 0;
1114
+ }
1115
+ }
1116
+ function write(root, path, content) {
1117
+ const full = join5(root, path);
1118
+ mkdirSync(dirname2(full), { recursive: true });
1119
+ writeFileSync3(full, content);
1120
+ }
1121
+ function install(root, plan, opts) {
1122
+ const result = {
1123
+ created: [],
1124
+ updated: [],
1125
+ unchanged: [],
1126
+ kept: [],
1127
+ outdated: [],
1128
+ conflicts: [],
1129
+ removed: []
1130
+ };
1131
+ const manifestPath = opts.manifestPath ?? MANIFEST_PATH;
1132
+ const emptiedFolder = opts.emptiedFolder ?? /\.claude\/skills\/[^/]+$/;
1133
+ const previous = readManifest(root, manifestPath);
1134
+ const next = { version: opts.version, files: {} };
1135
+ for (const file of plan) {
1136
+ const full = join5(root, file.path);
1137
+ const newHash = sha256(file.content);
1138
+ if (!existsSync5(full)) {
1139
+ write(root, file.path, file.content);
1140
+ result.created.push(file.path);
1141
+ if (file.policy !== "user") next.files[file.path] = newHash;
1142
+ continue;
1143
+ }
1144
+ if (file.policy === "user") {
1145
+ result.kept.push(file.path);
1146
+ continue;
1147
+ }
1148
+ const diskHash = sha256(readFileSync4(full, "utf8"));
1149
+ if (diskHash === newHash) {
1150
+ result.unchanged.push(file.path);
1151
+ next.files[file.path] = newHash;
1152
+ continue;
1153
+ }
1154
+ if (opts.mode === "init") {
1155
+ result.outdated.push(file.path);
1156
+ next.files[file.path] = previous?.files[file.path] ?? diskHash;
1157
+ continue;
1158
+ }
1159
+ const userModified = file.policy === "wrapper" && previous?.files[file.path] !== diskHash;
1160
+ if (userModified && !opts.force) {
1161
+ result.conflicts.push(file.path);
1162
+ next.files[file.path] = previous?.files[file.path] ?? diskHash;
1163
+ continue;
1164
+ }
1165
+ write(root, file.path, file.content);
1166
+ result.updated.push(file.path);
1167
+ next.files[file.path] = newHash;
1168
+ }
1169
+ if (opts.mode === "update" && previous) {
1170
+ const planned = new Set(plan.map((f) => f.path));
1171
+ for (const [path, hash] of Object.entries(previous.files)) {
1172
+ if (planned.has(path)) continue;
1173
+ const full = join5(root, path);
1174
+ if (!existsSync5(full)) continue;
1175
+ if (sha256(readFileSync4(full, "utf8")) === hash) {
1176
+ rmSync2(full);
1177
+ result.removed.push(path);
1178
+ const folder = dirname2(full);
1179
+ if (emptiedFolder.test(folder) && readdirSync2(folder).length === 0)
1180
+ rmSync2(folder, { recursive: true });
1181
+ } else {
1182
+ result.conflicts.push(path);
1183
+ }
1184
+ }
1185
+ }
1186
+ write(root, manifestPath, JSON.stringify(next, null, 2) + "\n");
1187
+ return result;
1188
+ }
1189
+
1190
+ // src/install.ts
1191
+ var ASSETS_DIR = fileURLToPath(new URL("../assets", import.meta.url));
1192
+ var CLIENT_DIR = ".alterspec-client";
1193
+ var PROMPTS_DIR = `${CLIENT_DIR}/prompts`;
1194
+ var MANIFEST_PATH2 = `${CLIENT_DIR}/manifest.json`;
1195
+ var MCP_JSON = ".mcp.json";
1196
+ var MCP_SERVER = "dispatcher";
1197
+ var MCP_ENTRY = { command: "npx", args: ["@alterset/alterspec-client", "mcp"] };
1198
+ function walk(dir) {
1199
+ return readdirSync3(dir).sort().flatMap((n) => statSync(join6(dir, n)).isDirectory() ? walk(join6(dir, n)) : [join6(dir, n)]);
1200
+ }
1201
+ var assetFiles = (sub) => walk(join6(ASSETS_DIR, sub)).map((f) => ({
1202
+ rel: relative(join6(ASSETS_DIR, sub), f).split("\\").join("/"),
1203
+ content: readFileSync5(f, "utf8")
1204
+ }));
1205
+ function buildClientPlan(version) {
1206
+ return [
1207
+ ...assetFiles("skills").map((f) => ({
1208
+ path: `.claude/skills/${f.rel}`,
1209
+ content: f.content,
1210
+ policy: "wrapper"
1211
+ })),
1212
+ ...assetFiles("prompts").map((f) => ({
1213
+ path: `${PROMPTS_DIR}/${f.rel}`,
1214
+ content: f.content,
1215
+ policy: "framework"
1216
+ })),
1217
+ { path: `${CLIENT_DIR}/version`, content: `${version}
1218
+ `, policy: "framework" }
1219
+ ];
1220
+ }
1221
+ function writeMcpJson(root) {
1222
+ const path = join6(root, MCP_JSON);
1223
+ let data = {};
1224
+ const before = existsSync6(path) ? readFileSync5(path, "utf8") : void 0;
1225
+ if (before !== void 0)
1226
+ try {
1227
+ data = JSON.parse(before);
1228
+ } catch {
1229
+ throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);
1230
+ }
1231
+ data.mcpServers = { ...data.mcpServers ?? {}, [MCP_SERVER]: MCP_ENTRY };
1232
+ const after = JSON.stringify(data, null, 2) + "\n";
1233
+ if (after === before) return "unchanged";
1234
+ writeFileSync4(path, after);
1235
+ return before === void 0 ? "created" : "updated";
1236
+ }
1237
+ var CLAUDE_SETTINGS = ".claude/settings.json";
1238
+ var HOOK_COMMAND = "npx @alterset/alterspec-client progress --hook";
1239
+ var HOOK_ENTRY = {
1240
+ type: "command",
1241
+ if: "Bash(git commit *)",
1242
+ command: HOOK_COMMAND,
1243
+ timeout: 60,
1244
+ async: true
1245
+ };
1246
+ var isOurs = (h) => typeof h.command === "string" && h.command.includes("@alterset/alterspec-client progress");
1247
+ function writeClaudeSettings(root) {
1248
+ const path = join6(root, CLAUDE_SETTINGS);
1249
+ const before = existsSync6(path) ? readFileSync5(path, "utf8") : void 0;
1250
+ let data = {};
1251
+ if (before !== void 0)
1252
+ try {
1253
+ data = JSON.parse(before);
1254
+ } catch {
1255
+ throw new ConfigError(`${path} is not valid JSON: fix it, then run init again.`);
1256
+ }
1257
+ const hooks = data.hooks ??= {};
1258
+ const groups = hooks.PostToolUse ??= [];
1259
+ let found = false;
1260
+ for (const group of groups)
1261
+ group.hooks = group.hooks?.flatMap((h) => {
1262
+ if (!isOurs(h)) return [h];
1263
+ if (found) return [];
1264
+ found = true;
1265
+ return [HOOK_ENTRY];
1266
+ });
1267
+ if (!found) groups.push({ matcher: "Bash", hooks: [HOOK_ENTRY] });
1268
+ const after = JSON.stringify(data, null, 2) + "\n";
1269
+ if (before !== void 0 && JSON.stringify(JSON.parse(before)) === JSON.stringify(data)) return "unchanged";
1270
+ mkdirSync2(join6(root, ".claude"), { recursive: true });
1271
+ writeFileSync4(path, after);
1272
+ return before === void 0 ? "created" : "updated";
1273
+ }
1274
+ function initClient(root, opts, version) {
1275
+ const { force, ...given } = opts;
1276
+ const existing = readConfigAt(root);
1277
+ const defined = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== void 0));
1278
+ const parsed = ClientConfigSchema.safeParse({ ...existing, ...defined });
1279
+ if (!parsed.success) {
1280
+ const missing = parsed.error.issues.map((i) => i.path.join(".")).filter(Boolean);
1281
+ throw new ConfigError(
1282
+ existing ? `The configuration would not be valid: ${parsed.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}.` : `init needs --dispatcher <url> and --export <path to your clone of the export>${missing.length ? ` (missing or wrong: ${missing.join(", ")})` : ""}.`
1283
+ );
1284
+ }
1285
+ const before = existing && JSON.stringify(existing);
1286
+ const config = !existing ? "created" : before === JSON.stringify(parsed.data) ? "unchanged" : "updated";
1287
+ if (config !== "unchanged") writeConfig(root, parsed.data);
1288
+ const mcp = writeMcpJson(root);
1289
+ const hook = writeClaudeSettings(root);
1290
+ const files = install(root, buildClientPlan(version), {
1291
+ mode: "update",
1292
+ force,
1293
+ version,
1294
+ manifestPath: MANIFEST_PATH2,
1295
+ emptiedFolder: /\.claude\/skills\/alterspec-[^/]+$/
1296
+ });
1297
+ return { config, mcp, hook, files };
1298
+ }
1299
+
1300
+ // src/mcp.ts
1301
+ import { createInterface } from "readline";
1302
+ var isRequest = (m) => m.method !== void 0 && m.id !== void 0;
1303
+ async function callTool(session, name, args = {}) {
1304
+ const res = await session.fetch("/mcp", {
1305
+ method: "POST",
1306
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
1307
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } })
1308
+ });
1309
+ const text = await res.text();
1310
+ if (!res.ok)
1311
+ throw new DispatcherError(`HTTP_${res.status}`, `The dispatcher answered ${res.status}.`, res.status);
1312
+ const answer = messagesOf(res.headers.get("content-type") ?? "", text)[0];
1313
+ if (!answer?.result)
1314
+ throw new DispatcherError(
1315
+ "MCP_ERROR",
1316
+ answer?.error?.message ?? `The dispatcher gave no answer to ${name}.`
1317
+ );
1318
+ const out = answer.result.structuredContent ?? {};
1319
+ if (answer.result.isError) {
1320
+ const err = out.error;
1321
+ throw new DispatcherError(
1322
+ err?.code ?? "TOOL_ERROR",
1323
+ err?.message ?? answer.result.content?.map((c) => c.text ?? "").join("\n") ?? `${name} failed.`
1324
+ );
1325
+ }
1326
+ return out;
1327
+ }
1328
+ function messagesOf(contentType, text) {
1329
+ if (!text.trim()) return [];
1330
+ if (!contentType.includes("text/event-stream")) return [JSON.parse(text)];
1331
+ const out = [];
1332
+ for (const event of text.split(/\r?\n\r?\n/)) {
1333
+ const data = event.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
1334
+ if (data.trim()) out.push(JSON.parse(data));
1335
+ }
1336
+ return out;
1337
+ }
1338
+ function runProxy(opts) {
1339
+ const { session, input, output, version } = opts;
1340
+ const log = opts.log ?? ((line) => process.stderr.write(`alterspec-client: ${line}
1341
+ `));
1342
+ let protocolVersion;
1343
+ const pending = /* @__PURE__ */ new Set();
1344
+ const send = (message) => void output.write(JSON.stringify(message) + "\n");
1345
+ const result = (id, value) => send({ jsonrpc: "2.0", id, result: value });
1346
+ const error = (id, message, code = -32e3) => send({ jsonrpc: "2.0", id, error: { code, message } });
1347
+ function refused(m, e) {
1348
+ if (!isRequest(m)) return;
1349
+ const id = m.id;
1350
+ switch (m.method) {
1351
+ case "initialize":
1352
+ return result(id, {
1353
+ protocolVersion: m.params?.protocolVersion ?? "2025-06-18",
1354
+ capabilities: { tools: {} },
1355
+ serverInfo: { name: "alterspec-client", version },
1356
+ instructions: e.advice
1357
+ });
1358
+ case "ping":
1359
+ return result(id, {});
1360
+ case "tools/list":
1361
+ return result(id, {
1362
+ tools: [
1363
+ {
1364
+ name: "whoami",
1365
+ description: "Who you are to the dispatcher. Your SSH key is refused: this says what to do.",
1366
+ inputSchema: { type: "object", properties: {} }
1367
+ }
1368
+ ]
1369
+ });
1370
+ case "tools/call":
1371
+ return result(id, {
1372
+ content: [{ type: "text", text: e.advice }],
1373
+ structuredContent: {
1374
+ error: { code: e.code, message: e.advice },
1375
+ key: { line: e.key.line, fingerprint: e.key.fingerprint }
1376
+ },
1377
+ isError: true
1378
+ });
1379
+ default:
1380
+ return error(id, e.advice);
1381
+ }
1382
+ }
1383
+ async function forward(m) {
1384
+ try {
1385
+ const headers = {
1386
+ "content-type": "application/json",
1387
+ accept: "application/json, text/event-stream"
1388
+ };
1389
+ if (protocolVersion) headers["mcp-protocol-version"] = protocolVersion;
1390
+ const res = await session.fetch("/mcp", { method: "POST", headers, body: JSON.stringify(m) });
1391
+ const text = await res.text();
1392
+ if (!res.ok && res.status !== 202) {
1393
+ let message = `The dispatcher answered ${res.status}.`;
1394
+ try {
1395
+ message = JSON.parse(text).error?.message ?? message;
1396
+ } catch {
1397
+ }
1398
+ if (isRequest(m)) error(m.id, message);
1399
+ return;
1400
+ }
1401
+ for (const answer of messagesOf(res.headers.get("content-type") ?? "", text)) {
1402
+ const pv = answer.result?.protocolVersion;
1403
+ if (m.method === "initialize" && typeof pv === "string") protocolVersion = pv;
1404
+ send(answer);
1405
+ }
1406
+ } catch (e) {
1407
+ if (e instanceof KeyRefused) {
1408
+ log(e.advice.split("\n")[0]);
1409
+ return refused(m, e);
1410
+ }
1411
+ const message = e instanceof DispatcherError ? e.message : `The client failed: ${e.message}`;
1412
+ log(message);
1413
+ if (!isRequest(m)) return;
1414
+ if (m.method === "tools/call")
1415
+ return result(m.id, { content: [{ type: "text", text: message }], isError: true });
1416
+ error(m.id, message);
1417
+ }
1418
+ }
1419
+ return new Promise((resolve3) => {
1420
+ const lines = createInterface({ input, crlfDelay: Infinity });
1421
+ lines.on("line", (line) => {
1422
+ if (!line.trim()) return;
1423
+ let m;
1424
+ try {
1425
+ m = JSON.parse(line);
1426
+ } catch {
1427
+ return error(null, "Parse error: not a JSON-RPC message.", -32700);
1428
+ }
1429
+ const p = forward(m).finally(() => pending.delete(p));
1430
+ pending.add(p);
1431
+ });
1432
+ lines.on("close", () => void Promise.allSettled([...pending]).then(() => resolve3()));
1433
+ });
1434
+ }
1435
+
1436
+ // src/open.ts
1437
+ import { spawn } from "child_process";
1438
+ var OPENABLE = ["dispatcher"];
1439
+ function openInBrowser(url) {
1440
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
1441
+ spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
1442
+ }
1443
+ async function openDispatcher(session, open = openInBrowser) {
1444
+ const res = await session.fetch("/auth/link", { method: "POST" });
1445
+ if (!res.ok) throw new DispatcherError("HTTP_" + res.status, `The dispatcher answered ${res.status}.`);
1446
+ const { url } = await res.json();
1447
+ open(url);
1448
+ return url;
1449
+ }
1450
+
1451
+ // src/progress.ts
1452
+ import { execFileSync as execFileSync4 } from "child_process";
1453
+ import { createHash as createHash3 } from "crypto";
1454
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync5 } from "fs";
1455
+ import { join as join7 } from "path";
1456
+ var git3 = (cwd, args) => execFileSync4("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
1457
+ function currentTask(repo) {
1458
+ try {
1459
+ return taskOfBranch(git3(repo, ["symbolic-ref", "--short", "HEAD"]));
1460
+ } catch {
1461
+ return void 0;
1462
+ }
1463
+ }
1464
+ function coveredItems(repo, task) {
1465
+ const trailer = (key) => `%(trailers:key=${key},valueonly,separator=%x1d)`;
1466
+ const log = git3(repo, [
1467
+ "log",
1468
+ "--reverse",
1469
+ "--topo-order",
1470
+ `--format=%H%x1f${trailer(TRAILER)}%x1f${trailer(COVERS)}%x1e`,
1471
+ "HEAD"
1472
+ ]);
1473
+ const first = /* @__PURE__ */ new Map();
1474
+ for (const record of log.split("")) {
1475
+ const [sha, tasks = "", covers = ""] = record.trim().split("");
1476
+ if (!sha) continue;
1477
+ if (!tasks.split("").some((t) => t.trim().toUpperCase() === task.id)) continue;
1478
+ for (const item of covers.replaceAll("", ",").split(/[,\s]+/).filter(Boolean))
1479
+ if (!first.has(item)) first.set(item, sha);
1480
+ }
1481
+ return [...first].map(([item, commit]) => ({ item, commit })).sort((a, b) => a.item < b.item ? -1 : a.item > b.item ? 1 : 0);
1482
+ }
1483
+ var unknownOf = (e) => e.message.split("\n").slice(1).map((l) => l.trim()).filter(Boolean);
1484
+ async function reportProgress(session, task, covered) {
1485
+ try {
1486
+ const answer = await callTool(session, "report_progress", { id: task.id, covered });
1487
+ return { task: task.id, covered, unknown: [], answer };
1488
+ } catch (e) {
1489
+ if (!(e instanceof DispatcherError) || e.code !== "UNKNOWN_ITEM") throw e;
1490
+ const unknown = unknownOf(e);
1491
+ const known = covered.filter((c) => !unknown.includes(c.item));
1492
+ if (!unknown.length || known.length === covered.length) throw e;
1493
+ const answer = await callTool(session, "report_progress", { id: task.id, covered: known });
1494
+ return { task: task.id, covered: known, unknown, answer };
1495
+ }
1496
+ }
1497
+ function progressText(r) {
1498
+ const progress = r.answer.progress;
1499
+ const eta = r.answer.eta;
1500
+ const count = progress ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %)` : "no checklist (its export predates task items)";
1501
+ const when = !eta ? "" : eta.by === "done" ? "; done" : eta.date ? `; ETA ${eta.at_least ? "at least " : ""}${eta.date}${eta.by === "developer" ? ` (yours; computed ${eta.computed?.date ?? "unknown"})` : ""}` : "; ETA unknown";
1502
+ const lines = [`${r.task}: ${count}${when}.`];
1503
+ if (r.unknown.length) lines.unshift(unknownLine(r));
1504
+ return lines.join("\n") + "\n";
1505
+ }
1506
+ var unknownLine = (r) => `${r.task} has no item ${r.unknown.join(", ")}; left out of the report: name only the task's items (context lists them).`;
1507
+ var THROTTLE_MS = 15 * 6e4;
1508
+ var statePath = (repo, task) => join7(
1509
+ git3(repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"]),
1510
+ "alterspec-client",
1511
+ `progress-${folderOf(task)}.json`
1512
+ );
1513
+ var hashOf = (covered) => createHash3("sha256").update(JSON.stringify(covered)).digest("hex").slice(0, 16);
1514
+ function readState(path) {
1515
+ try {
1516
+ return existsSync7(path) ? JSON.parse(readFileSync6(path, "utf8")) : void 0;
1517
+ } catch {
1518
+ return void 0;
1519
+ }
1520
+ }
1521
+ async function progressHook(opts) {
1522
+ const now = opts.now ?? Date.now;
1523
+ try {
1524
+ const task = currentTask(opts.repo);
1525
+ if (!task) return "off-task";
1526
+ const covered = coveredItems(opts.repo, task);
1527
+ const path = statePath(opts.repo, task);
1528
+ const state = readState(path);
1529
+ const hash = hashOf(covered);
1530
+ if (state?.reported === hash) return "unchanged";
1531
+ if (state && now() - Date.parse(state.at) < THROTTLE_MS) return "throttled";
1532
+ await reportProgress(opts.session(), task, covered);
1533
+ mkdirSync3(join7(path, ".."), { recursive: true });
1534
+ writeFileSync5(path, JSON.stringify({ reported: hash, at: new Date(now()).toISOString() }) + "\n");
1535
+ return "reported";
1536
+ } catch {
1537
+ return "failed";
1538
+ }
1539
+ }
1540
+ async function hookCwd(input, waitMs = 1e3) {
1541
+ if (input.isTTY) return void 0;
1542
+ const text = await new Promise((resolve3) => {
1543
+ let data = "";
1544
+ const done = () => resolve3(data);
1545
+ const timer = setTimeout(done, waitMs);
1546
+ input.on("data", (c) => data += c.toString());
1547
+ input.on("end", () => {
1548
+ clearTimeout(timer);
1549
+ done();
1550
+ });
1551
+ input.on("error", done);
1552
+ });
1553
+ try {
1554
+ const cwd = JSON.parse(text).cwd;
1555
+ return typeof cwd === "string" && cwd ? cwd : void 0;
1556
+ } catch {
1557
+ return void 0;
1558
+ }
1559
+ }
1560
+
1561
+ // src/version.ts
1562
+ import { readFileSync as readFileSync7 } from "fs";
6
1563
  function packageVersion() {
7
- const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
1564
+ const pkg = JSON.parse(readFileSync7(new URL("../package.json", import.meta.url), "utf8"));
8
1565
  return pkg.version;
9
1566
  }
1567
+
1568
+ // src/cli.ts
1569
+ var tryConfig = () => {
1570
+ try {
1571
+ return loadConfig();
1572
+ } catch {
1573
+ return void 0;
1574
+ }
1575
+ };
1576
+ async function coveredState(loaded, task) {
1577
+ try {
1578
+ const answer = await callTool(sessionOf(loaded), "task", { id: task.id });
1579
+ const items = answer.items ?? [];
1580
+ return {
1581
+ covered: new Map(items.flatMap((i) => i.covered_commit ? [[i.item, i.covered_commit]] : []))
1582
+ };
1583
+ } catch (e) {
1584
+ return { unknown: e.message.split("\n")[0] };
1585
+ }
1586
+ }
1587
+ var run = (fn) => async (...args) => {
1588
+ try {
1589
+ await fn(...args);
1590
+ } catch (e) {
1591
+ process.stderr.write(`${e instanceof KeyRefused ? e.advice : e.message}
1592
+ `);
1593
+ process.exit(1);
1594
+ }
1595
+ };
10
1596
  var program = new Command();
11
1597
  program.name("alterspec-client").description("alterspec client \u2014 takes tasks of an alterspec export from the dispatcher.").version(packageVersion());
12
- program.parse();
1598
+ program.command("init").description(
1599
+ "set the client up in this repository: configuration, the dispatcher in .mcp.json, the progress hook, the skills"
1600
+ ).option("--dispatcher <url>", "the dispatcher\u2019s URL").option("--export <path>", "your clone of the export repository").option("--track <code...>", "the tracks this repository builds (BE, WEB, \u2026)").option("--worktrees <path>", "where task worktrees go (default ../<repo>-tasks)").option("--key <key>", "the public key to sign with: a .pub path or the key line").option("--branch <name>", "the track\u2019s main branch (default the remote\u2019s HEAD)").option("--force", "replace skills you modified").action(
1601
+ run(
1602
+ (opts) => {
1603
+ const root = process.cwd();
1604
+ const { track, ...rest } = opts;
1605
+ const tracks = track?.flatMap((t) => t.split(",")).map((t) => t.trim().toUpperCase()).filter(Boolean);
1606
+ const r = initClient(root, { ...rest, ...tracks ? { tracks } : {} }, packageVersion());
1607
+ const f = r.files;
1608
+ const lines = [
1609
+ `${CONFIG_FILE}: ${r.config}`,
1610
+ `${MCP_JSON} (server "dispatcher"): ${r.mcp}`,
1611
+ `${CLAUDE_SETTINGS} (progress hook after git commit): ${r.hook}`,
1612
+ `Skills and ${PROMPTS_DIR}/: ${f.created.length} created, ${f.updated.length} updated, ${f.unchanged.length} unchanged${f.removed.length ? `, ${f.removed.length} removed` : ""}.`,
1613
+ ...f.conflicts.map((p) => `Kept your modified ${p}; --force replaces it.`),
1614
+ "",
1615
+ "Commit .mcp.json, .claude/settings.json, .claude/skills/alterspec-* and .alterspec-client/, so task worktrees have them too."
1616
+ ];
1617
+ try {
1618
+ const key = keyOf({ root, config: readConfigAt(root) });
1619
+ lines.push("", "Send this public key to the dispatcher\u2019s admin:", key.line, key.fingerprint);
1620
+ } catch (e) {
1621
+ lines.push("", e.message);
1622
+ }
1623
+ process.stdout.write(lines.join("\n") + "\n");
1624
+ }
1625
+ )
1626
+ );
1627
+ program.command("key").description("print the public key and fingerprint the client signs with, to send to the admin").action(
1628
+ run(() => {
1629
+ const key = keyOf(tryConfig());
1630
+ process.stdout.write(`${key.line}
1631
+ ${key.fingerprint}
1632
+ `);
1633
+ })
1634
+ );
1635
+ program.command("open").description("sign in and open the dispatcher\u2019s pages in the browser (a one-time link)").argument("<what>", `what to open: ${OPENABLE.join(", ")}`).action(
1636
+ run(async (what) => {
1637
+ if (!OPENABLE.includes(what))
1638
+ throw new Error(`Nothing to open called "${what}": ${OPENABLE.join(", ")}.`);
1639
+ const loaded = loadConfig();
1640
+ const url = await openDispatcher(sessionOf(loaded));
1641
+ process.stdout.write(
1642
+ `Opened ${new URL(url).origin} in the browser (the link works once, for a minute).
1643
+ `
1644
+ );
1645
+ })
1646
+ );
1647
+ program.command("mcp").description(
1648
+ "the local MCP server Claude Code starts over stdio (from .mcp.json); forwards to the dispatcher"
1649
+ ).action(
1650
+ run(async () => {
1651
+ const loaded = loadConfig();
1652
+ const session = sessionOf(loaded);
1653
+ await runProxy({ session, input: process.stdin, output: process.stdout, version: packageVersion() });
1654
+ })
1655
+ );
1656
+ program.command("export-head").description("pull the export clone and print its HEAD and the commit to send the dispatcher (JSON)").option("--latest <sha>", "the dispatcher\u2019s latest_export").action(
1657
+ run((opts) => {
1658
+ const head = exportHead(exportDir(loadConfig()), opts.latest);
1659
+ process.stdout.write(JSON.stringify(head, null, 2) + "\n");
1660
+ })
1661
+ );
1662
+ program.command("context").description("print a task\u2019s brief, assembled from the export").argument("<task>", "the task, e.g. CHG-012/BE").option("--json", "print it as JSON").action(
1663
+ run(async (id, opts) => {
1664
+ const loaded = loadConfig();
1665
+ const dir = exportDir(loaded);
1666
+ const x = readExport(dir);
1667
+ const task = parseTask(id);
1668
+ const ctx = taskContext(x, task, dir, await coveredState(loaded, task));
1669
+ process.stdout.write(opts.json ? JSON.stringify(ctx, null, 2) + "\n" : renderContext(ctx));
1670
+ })
1671
+ );
1672
+ program.command("progress").description("report the items the task\u2019s commits cover to the dispatcher").argument("[task]", "the task, e.g. CHG-012/BE; default the one of the current branch task/<chg>-<track>").option("--hook", "as the Claude Code hook after a commit: silent, throttled, never failing").option("--json", "print the dispatcher\u2019s answer as JSON").action(async (id, opts) => {
1673
+ if (opts.hook) {
1674
+ setTimeout(() => process.exit(0), 3e4).unref();
1675
+ const repo = await hookCwd(process.stdin) ?? process.cwd();
1676
+ await progressHook({ repo, session: () => sessionOf(loadConfig(repo)) });
1677
+ process.exit(0);
1678
+ }
1679
+ await run(async () => {
1680
+ const repo = process.cwd();
1681
+ const task = id ? parseTask(id) : currentTask(repo);
1682
+ if (!task)
1683
+ throw new Error(
1684
+ "This branch is no task branch (task/<chg>-<track>): name the task, e.g. `progress CHG-012/BE`."
1685
+ );
1686
+ const report = await reportProgress(sessionOf(loadConfig()), task, coveredItems(repo, task));
1687
+ process.stdout.write(opts.json ? JSON.stringify(report, null, 2) + "\n" : progressText(report));
1688
+ })();
1689
+ });
1690
+ program.command("worktree").description("create the task\u2019s branch task/<chg>-<track> from origin/<main>, in a worktree of its own").argument("<task>", "the task, e.g. CHG-012/BE").option("--here", "make the branch in this checkout instead of a worktree").action(
1691
+ run((id, opts) => {
1692
+ const loaded = loadConfig();
1693
+ const wt = taskWorktree(process.cwd(), parseTask(id), {
1694
+ main: mainBranch(process.cwd(), loaded.config.branch),
1695
+ worktreesDir: worktreesDir(loaded),
1696
+ here: opts.here
1697
+ });
1698
+ process.stdout.write(JSON.stringify(wt, null, 2) + "\n");
1699
+ })
1700
+ );
1701
+ program.command("merged").description("print the commit on origin/<main> that brought the task in").argument("<task>", "the task, e.g. CHG-012/BE").action(
1702
+ run((id) => {
1703
+ const loaded = loadConfig();
1704
+ const main = mainBranch(process.cwd(), loaded.config.branch);
1705
+ const task = parseTask(id);
1706
+ const sha = mergedCommit(process.cwd(), task, main);
1707
+ if (!sha)
1708
+ throw new Error(
1709
+ `${task.id} is not on origin/${main} yet: merge its branch, or commit with the trailer "Alterspec-Task: ${task.id}", and push.`
1710
+ );
1711
+ process.stdout.write(sha + "\n");
1712
+ })
1713
+ );
1714
+ await program.parseAsync();
13
1715
  //# sourceMappingURL=cli.js.map