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