@alterset/alterspec-client 0.13.0 → 0.15.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
@@ -2,6 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { Command } from "commander";
5
+ import { join as join8 } from "path";
5
6
 
6
7
  // src/config.ts
7
8
  import { execFileSync } from "child_process";
@@ -32,7 +33,11 @@ var WorkTaskSchema = z.object({
32
33
  * Sorted, never empty.
33
34
  */
34
35
  items: z.array(z.string().min(1)).min(1),
35
- /** The tasks this one waits for, resolved: the same change's `BE` task, and the track's tasks it builds on. */
36
+ /**
37
+ * The tasks this one waits for, resolved and reduced: the same change's `BE` task, and the track's tasks of the
38
+ * changes it builds on that did the same work (an item of both, a line of a whole object this task edits again,
39
+ * or an object this task names that entered the export with the earlier change).
40
+ */
36
41
  after: z.array(z.object({ change: ChangeRef, track: TrackCode }).strict())
37
42
  }).strict();
38
43
  var WorkChangeSchema = z.object({
@@ -75,7 +80,7 @@ var ClientConfigSchema = z2.object({
75
80
  export: z2.string().min(1),
76
81
  /** The tracks this repository builds: the default of `next_task`. */
77
82
  tracks: z2.array(TrackCode).default([]),
78
- /** Where `worktree` puts a task's worktree; default `../<repo>-tasks`. */
83
+ /** Unused since 0.14.0 (the client makes no worktree); accepted so a configuration written before stays valid. */
79
84
  worktrees: z2.string().min(1).optional(),
80
85
  /** The public key to sign with: a `.pub` path or the key line; default ssh-agent, then `~/.ssh/id_ed25519.pub`. */
81
86
  key: z2.string().min(1).optional(),
@@ -127,7 +132,6 @@ function configPath(root, path) {
127
132
  return isAbsolute(path) ? path : resolve(root, path);
128
133
  }
129
134
  var exportDir = ({ root, config }) => configPath(root, config.export);
130
- var worktreesDir = ({ root, config }) => configPath(root, config.worktrees ?? `../${basename(root)}-tasks`);
131
135
  function writeConfig(root, config) {
132
136
  writeFileSync(join(root, CONFIG_FILE), JSON.stringify(config, null, 2) + "\n");
133
137
  }
@@ -681,6 +685,75 @@ function dataChangeText(sectionText2) {
681
685
  return text && !/^none\b/i.test(text) ? text : void 0;
682
686
  }
683
687
 
688
+ // ../src/changes/parts.ts
689
+ var FRONT_MATTER_PART = "front-matter";
690
+ var itemObject = (item) => item.startsWith("file:") ? item : item.replace(/-AC-\d{2}$/, "").replace(/[.#][^.#]*$/, "");
691
+ var forWork = (text) => text.replace(/^[^\S\n]*<!--[\s\S]*?-->[^\S\n]*\n/gm, "").replace(/<!--[\s\S]*?-->/g, "").replace(/^version:[^\S\n]*\d+[^\S\n]*\n/m, "").replace(/^(?:reviewed|dry|page):[^\n]*\n/gm, "");
692
+ function objectParts(text, kind) {
693
+ const out = /* @__PURE__ */ new Map();
694
+ const put = (label, heading, body2) => {
695
+ const base = label === "front-matter" ? FRONT_MATTER_PART : slug(heading);
696
+ let key = base;
697
+ for (let n = 2; out.has(key); n++) key = `${base}-${n}`;
698
+ out.set(key, { label, heading, text: body2 });
699
+ };
700
+ const t = forWork(text);
701
+ if (kind === "doc") {
702
+ const { raw, body: body2 } = splitFrontMatter(t);
703
+ if (raw) put("front-matter", FRONT_MATTER_PART, raw);
704
+ for (const s of headed(body2, "## ").sections) put("section", s.heading, s.text);
705
+ return out;
706
+ }
707
+ const yaml = /^```ya?ml\n([\s\S]*?)\n```[^\S\n]*$/m.exec(t);
708
+ if (yaml) put("front-matter", FRONT_MATTER_PART, yaml[1]);
709
+ const body = yaml ? t.slice(yaml.index + yaml[0].length) : t.replace(/^## [^\n]*\n?/, "");
710
+ const { sections } = headed(body, "### ");
711
+ if (sections.length) for (const s of sections) put("section", s.heading, s.text);
712
+ else for (const b of bullets(body)) put("line", b.heading, b.text);
713
+ return out;
714
+ }
715
+ function headed(text, marker) {
716
+ const sections = [];
717
+ let intro = "";
718
+ let fence2 = false;
719
+ for (const l of text.split("\n")) {
720
+ if (/^(?:```|~~~)/.test(l)) fence2 = !fence2;
721
+ if (!fence2 && l.startsWith(marker) && /\S/.test(l.slice(marker.length))) {
722
+ sections.push({ heading: l.slice(marker.length).trim(), text: "" });
723
+ continue;
724
+ }
725
+ if (sections.length) sections[sections.length - 1].text += `${l}
726
+ `;
727
+ else intro += `${l}
728
+ `;
729
+ }
730
+ return { intro, sections };
731
+ }
732
+ var BULLET = /^(?:[-*+]|\d+[.)])\s+(.*)$/;
733
+ function bullets(text) {
734
+ const out = [];
735
+ let current;
736
+ let fence2 = false;
737
+ for (const l of text.split("\n")) {
738
+ if (/^(?:```|~~~)/.test(l)) {
739
+ fence2 = !fence2;
740
+ current = void 0;
741
+ continue;
742
+ }
743
+ if (fence2) continue;
744
+ const m = BULLET.exec(l);
745
+ if (m) {
746
+ current = { heading: lead(m[1]), text: `${l}
747
+ ` };
748
+ out.push(current);
749
+ } else if (current && /^\s+\S/.test(l)) current.text += `${l}
750
+ `;
751
+ else current = void 0;
752
+ }
753
+ return out;
754
+ }
755
+ var lead = (s) => s.replace(/\*\*|__|`/g, "").split(/:\s|:$|\s[—–-]\s|\.\s|\.$/)[0].trim().split(/\s+/).slice(0, 8).join(" ");
756
+
684
757
  // ../src/lib/diff.ts
685
758
  var linesOf = (text) => text === "" ? [] : text.replace(/\n$/, "").split("\n");
686
759
  function diffLines(a, b) {
@@ -914,7 +987,7 @@ function runProxy(opts) {
914
987
  error(m.id, message);
915
988
  }
916
989
  }
917
- return new Promise((resolve3) => {
990
+ return new Promise((resolve2) => {
918
991
  const lines = createInterface({ input, crlfDelay: Infinity });
919
992
  lines.on("line", (line) => {
920
993
  if (!line.trim()) return;
@@ -927,7 +1000,7 @@ function runProxy(opts) {
927
1000
  const p = forward(m).finally(() => pending.delete(p));
928
1001
  pending.add(p);
929
1002
  });
930
- lines.on("close", () => void Promise.allSettled([...pending]).then(() => resolve3()));
1003
+ lines.on("close", () => void Promise.allSettled([...pending]).then(() => resolve2()));
931
1004
  });
932
1005
  }
933
1006
 
@@ -1119,22 +1192,26 @@ function withSections(diff, before, after) {
1119
1192
  }).join("\n");
1120
1193
  }
1121
1194
  var BOOKKEEPING = /^(reviewed|page|dry|status|version|signed_off|base):/;
1195
+ var firstAddedLine = (a, b) => diffLines(a, b).filter((l) => l.op === "+").map(
1196
+ (l) => l.text.replace(/^\s*(?:[-*]|#+|\d+\.)\s+/, "").replace(/\*\*/g, "").trim()
1197
+ ).find((t) => t && !/^(---|```)/.test(t) && !BOOKKEEPING.test(t));
1198
+ var clipped = (line) => line && line.length > 200 ? `${line.slice(0, 199)}\u2026` : line;
1122
1199
  function firstAdded(key, entry) {
1123
- const added = (a, b) => diffLines(a, b).filter((l) => l.op === "+").map(
1124
- (l) => l.text.replace(/^\s*(?:[-*]|#+|\d+\.)\s+/, "").replace(/\*\*/g, "").trim()
1125
- ).find((t) => t && !/^(---|```)/.test(t) && !BOOKKEEPING.test(t));
1126
1200
  const before = forDiff(key, entry.before);
1127
1201
  const after = forDiff(key, entry.after);
1128
- const line = added(splitFrontMatter(before).body, splitFrontMatter(after).body) ?? added(splitFrontMatter(before).raw ?? "", splitFrontMatter(after).raw ?? "");
1129
- return line && line.length > 200 ? `${line.slice(0, 199)}\u2026` : line;
1202
+ return clipped(
1203
+ firstAddedLine(splitFrontMatter(before).body, splitFrontMatter(after).body) ?? firstAddedLine(splitFrontMatter(before).raw ?? "", splitFrontMatter(after).raw ?? "")
1204
+ );
1130
1205
  }
1131
- function objectBrief(x, key, entry, why) {
1206
+ function objectBrief(x, key, entry, why, later = []) {
1132
1207
  const file = x.fileOf(key);
1133
1208
  const held = file !== void 0 && x.has(file);
1134
1209
  const brief = { key, ...held ? { file } : {} };
1135
1210
  if (held && x.shards(file).length) brief.shards = x.shards(file)[0].replace(/\/[^/]+$/, "");
1136
1211
  if (why) brief.unrecoverable = why;
1137
1212
  if (!entry) return brief;
1213
+ const differs = held && entry.exported.after && entry.after !== void 0 && !entry.binary && forDiff(key, entry.after).trim() !== forDiff(key, x.read(file)).trim();
1214
+ if (later.length || differs) brief.since = { changes: later, differs: !!differs };
1138
1215
  brief.change = exportChange(entry);
1139
1216
  if (entry.status) brief.status = entry.status;
1140
1217
  if (entry.before !== void 0 || entry.after !== void 0) {
@@ -1223,6 +1300,18 @@ function itemWhat(x, item, entry, track) {
1223
1300
  if (item.startsWith("term:")) return `glossary term "${item.slice(5)}"`;
1224
1301
  if (DATA_CHANGE_RE.test(item))
1225
1302
  return `the one-time change to the records the product already holds (the proposal's "${DATA_CHANGE_SECTION}", below)`;
1303
+ const part = /^([^#]+)#([^#]+)$/.exec(item);
1304
+ if (part && !/^UX-/.test(item)) {
1305
+ const [, key, slug2] = part;
1306
+ const k = idKind(key);
1307
+ const owner = `${k && KIND_WORDS[k] ? `${KIND_WORDS[k]} ` : ""}${named(x, key)}`;
1308
+ const kind2 = entry?.kind === "item" ? "item" : "doc";
1309
+ const after = entry?.after !== void 0 ? objectParts(entry.after, kind2).get(slug2) : void 0;
1310
+ const before = entry?.before !== void 0 ? objectParts(entry.before, kind2).get(slug2) : void 0;
1311
+ const label = !after ? `the part "${slug2}"` : after.label === "front-matter" ? "the front-matter" : after.label === "section" ? `the section "${after.heading}"` : `the line "${after.heading}"`;
1312
+ const line2 = after ? clipped(firstAddedLine(before?.text ?? "", after.text)) : void 0;
1313
+ return `${label} of ${owner}${line2 ? `: "${line2}"` : ""}`;
1314
+ }
1226
1315
  const kind = idKind(item);
1227
1316
  const what = `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ""}${named(x, item)}`;
1228
1317
  if (!entry) return what;
@@ -1285,6 +1374,60 @@ function whereUsed(x, objects, entries, changed) {
1285
1374
  }
1286
1375
  return out;
1287
1376
  }
1377
+ function laterChanges(x, change, key) {
1378
+ const order = x.work.changes.map((c) => c.id);
1379
+ const at = order.indexOf(change);
1380
+ const touched = x.sources.get(key)?.changed_by ?? [];
1381
+ return touched.filter((c) => order.indexOf(c) > at).sort((a, b) => order.indexOf(a) - order.indexOf(b));
1382
+ }
1383
+ function lifecycleOf(x, id) {
1384
+ const e = x.index()?.entities.find((e2) => e2.id === id);
1385
+ if (!e?.states?.length) return void 0;
1386
+ const states = e.states.map((s) => s === e.initial_state ? `${s} (initial)` : s).join(", ");
1387
+ const transitions = (e.transitions ?? []).map((t) => `${t.from}->${t.to}${t.by === "time" ? ` by time${t.at ? ` at ${t.at}` : ""}` : ""}`).join(", ");
1388
+ return `states ${states}${transitions ? `; transitions ${transitions}` : "; no transitions"}`;
1389
+ }
1390
+ function reachOf(x, id, kind, changed) {
1391
+ const index = x.index();
1392
+ if (!index) return void 0;
1393
+ const piece = (pid, title2, scope) => ({
1394
+ id: pid,
1395
+ path: x.fileOf(pid) ?? "",
1396
+ ...title2 ? { title: title2 } : {},
1397
+ ...changed.has(pid) ? { changed: true } : {},
1398
+ ...scope ? { scope } : {}
1399
+ });
1400
+ const screenPiece = (sid) => piece(sid, index.screens.find((s) => s.id === sid)?.title ?? titleOf(x, sid));
1401
+ const title = titleOf(x, id);
1402
+ if (kind === "rule") {
1403
+ const caps2 = index.capabilities.filter((c) => (c.rules ?? []).includes(id));
1404
+ const criteria = caps2.flatMap((c) => {
1405
+ const file = x.fileOf(c.id);
1406
+ const text = file && x.has(file) ? sectionText(x, x.sectionShard(file, "Acceptance criteria")) : void 0;
1407
+ return (text ?? "").split(/^(?=### )/m).filter(
1408
+ (chunk) => chunk.startsWith("### ") && new RegExp(`^\\s*[-*]?\\s*\\**Covers:?\\**[^\\n]*\\b${id}\\b`, "m").test(chunk)
1409
+ ).map((chunk) => chunk.slice(4).split(/\s/)[0]);
1410
+ });
1411
+ const screens2 = [...new Set(caps2.flatMap((c) => c.screens ?? []))].filter((sid) => x.sources.has(sid));
1412
+ return {
1413
+ id,
1414
+ kind,
1415
+ ...title ? { title } : {},
1416
+ capabilities: caps2.map((c) => piece(c.id, c.title)),
1417
+ criteria,
1418
+ screens: screens2.map(screenPiece)
1419
+ };
1420
+ }
1421
+ const caps = index.capabilities.filter((c) => (c.roles ?? []).some((r) => r.role === id));
1422
+ const screens = index.screens.filter((s) => (s.roles ?? []).some((r) => r.role === id));
1423
+ return {
1424
+ id,
1425
+ kind,
1426
+ ...title ? { title } : {},
1427
+ capabilities: caps.map((c) => piece(c.id, c.title, c.roles?.find((r) => r.role === id)?.scope)),
1428
+ screens: screens.map((s) => piece(s.id, s.title))
1429
+ };
1430
+ }
1288
1431
  function taskContext(x, task, exportDir2, state = {}, questions) {
1289
1432
  const change = x.work.changes.find((c) => c.id === task.change);
1290
1433
  if (!change) throw new ContextError(`${task.change} is not in this export's work.json: pull the export.`);
@@ -1310,7 +1453,7 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1310
1453
  const covered = state.covered?.get(item);
1311
1454
  return {
1312
1455
  item,
1313
- what: itemWhat(x, item, entries.get(item), task.track),
1456
+ what: itemWhat(x, item, entries.get(itemObject(item)), task.track),
1314
1457
  ...covered ? { covered } : {}
1315
1458
  };
1316
1459
  }),
@@ -1336,7 +1479,9 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1336
1479
  ...dataChangeOf(sectionText(x, x.sectionShard(proposal, DATA_CHANGE_SECTION)))
1337
1480
  },
1338
1481
  ...delta ? { delta: proposal.replace(/proposal\.md$/, "delta.md") } : {},
1339
- objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key)))
1482
+ objects: work.objects.map(
1483
+ (key) => objectBrief(x, key, entries.get(key), lost.get(key), laterChanges(x, change.id, key))
1484
+ )
1340
1485
  };
1341
1486
  const added = work.objects.flatMap((key) => {
1342
1487
  const e = entries.get(key);
@@ -1403,6 +1548,13 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1403
1548
  };
1404
1549
  ctx.rules = carried("rule");
1405
1550
  ctx.events = carried("event");
1551
+ const whole = (kind) => {
1552
+ const bearing2 = idsIn(written.join("\n"), [kind]);
1553
+ const own = work.objects.filter((k) => idKind(k) === kind);
1554
+ return [.../* @__PURE__ */ new Set([...own, ...bearing2])].flatMap((id) => piece(id, true));
1555
+ };
1556
+ ctx.nfr = whole("nfr");
1557
+ ctx.integrations = whole("integration");
1406
1558
  ctx.entities = [
1407
1559
  .../* @__PURE__ */ new Set([
1408
1560
  ...work.objects.filter((k) => idKind(k) === "entity"),
@@ -1412,7 +1564,16 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1412
1564
  const file = x.fileOf(id);
1413
1565
  if (!file || !x.has(file)) return [];
1414
1566
  const title = titleOf(x, id);
1415
- return [{ id, path: file, ...title ? { title } : {}, ...changed.has(id) ? { changed: true } : {} }];
1567
+ const note = lifecycleOf(x, id);
1568
+ return [
1569
+ {
1570
+ id,
1571
+ path: file,
1572
+ ...title ? { title } : {},
1573
+ ...changed.has(id) ? { changed: true } : {},
1574
+ ...note ? { note } : {}
1575
+ }
1576
+ ];
1416
1577
  });
1417
1578
  ctx.operations = x.has(OPERATIONS_FILE) ? capabilities.flatMap((id) => {
1418
1579
  const path = x.shards(OPERATIONS_FILE).find((p) => new RegExp(`/\\d{2}-${slug(id)}(-|\\.md$)`).test(p));
@@ -1442,6 +1603,18 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1442
1603
  const bearing = idsIn(written.join("\n"), ["decision"]);
1443
1604
  const named2 = idsIn(work.objects.map((k) => entries.get(k)?.after ?? "").join("\n"), ["decision"]);
1444
1605
  ctx.decisions = [.../* @__PURE__ */ new Set([...bearing, ...named2])].flatMap((id) => piece(id, bearing.includes(id)));
1606
+ const rules = [
1607
+ .../* @__PURE__ */ new Set([
1608
+ ...work.objects.filter((k) => idKind(k) === "rule"),
1609
+ ...(ctx.rules ?? []).filter((r) => r.text).map((r) => r.id)
1610
+ ])
1611
+ ];
1612
+ const roles = work.objects.filter((k) => idKind(k) === "role");
1613
+ ctx.reach = [
1614
+ ...rules.map((id) => reachOf(x, id, "rule", changed)),
1615
+ ...roles.map((id) => reachOf(x, id, "role", changed))
1616
+ ].filter((r) => !!r);
1617
+ if (!ctx.reach.length) delete ctx.reach;
1445
1618
  const glossary = x.fileOf("term:");
1446
1619
  const writtenText = written.join("\n");
1447
1620
  ctx.terms = (glossary && x.has(glossary) ? x.shards(glossary) : []).filter((path) => !/\/\d{2}-[^/]*$/.test(path)).flatMap((path) => {
@@ -1470,7 +1643,7 @@ function renderContext(c) {
1470
1643
  if (c.startFrom?.length)
1471
1644
  out.push(
1472
1645
  "",
1473
- `Start from ${c.startFrom.map((s) => `\`${s.branch}\` (${s.id}${s.commit ? ` done at ${s.commit.slice(0, 12)}` : ""})`).join(", then ")}, not from the main branch: the predecessor's work is pushed there and not merged yet (\`alterspec-client worktree ${c.task} --from ${c.startFrom[c.startFrom.length - 1].branch}\`).`
1646
+ `Start from ${c.startFrom.map((s) => `\`${s.branch}\` (${s.id}${s.commit ? ` done at ${s.commit.slice(0, 12)}` : ""})`).join(", then ")}, not from the main branch: the predecessor's work is pushed there and not merged yet (fetch it and base your branch on \`origin/${c.startFrom[c.startFrom.length - 1].branch}\`).`
1474
1647
  );
1475
1648
  out.push("");
1476
1649
  if (c.questions?.length) out.push(...questionsSection(c.questions));
@@ -1509,6 +1682,13 @@ function renderContext(c) {
1509
1682
  const status = o.status && o.status.before !== o.status.after ? `, ${o.status.before ?? "\u2014"} \u2192 ${o.status.after ?? "\u2014"}` : "";
1510
1683
  out.push(`### ${o.key}`, "", `${o.change ?? "no delta entry"}${status}; ${where}.`);
1511
1684
  if (o.unrecoverable) out.push("", `The delta could not recover it: ${o.unrecoverable}.`);
1685
+ if (o.since) {
1686
+ const later = o.since.changes.length ? `Changed since this sign-off by ${o.since.changes.join(", ")} (later in the change map; their deltas are next to their proposals). ` : "";
1687
+ out.push(
1688
+ "",
1689
+ o.since.differs ? `${later}The current text differs from this delta\u2019s after: build to the current file, the checklist follows the current text.` : `${later}The current text still equals this delta\u2019s after.`
1690
+ );
1691
+ }
1512
1692
  if (o.diff) out.push("", o.diff.startsWith("@@") ? fence(o.diff, "diff") : o.diff);
1513
1693
  out.push("");
1514
1694
  }
@@ -1538,6 +1718,33 @@ function renderContext(c) {
1538
1718
  }
1539
1719
  out.push("");
1540
1720
  }
1721
+ if (c.reach?.length) {
1722
+ out.push(
1723
+ "## Reach",
1724
+ "",
1725
+ "Where the export enforces, holds or shows the rules and roles this task touches or names; a capability or screen not in the export isn\u2019t listed.",
1726
+ ""
1727
+ );
1728
+ const list2 = (ps) => ps.map((p) => `${p.id}${p.scope ? ` (${p.scope})` : ""}${p.changed ? " (this task changes it)" : ""}`).join(", ");
1729
+ for (const r of c.reach) {
1730
+ const name = `${r.id}${r.title ? ` ${r.title}` : ""}`;
1731
+ if (r.kind === "rule") {
1732
+ const parts = [
1733
+ r.capabilities.length ? `enforced by ${list2(r.capabilities)}` : "no capability lists it",
1734
+ r.criteria?.length ? `covered by ${r.criteria.join(", ")}` : "no criterion covers it",
1735
+ r.screens.length ? `on ${list2(r.screens)}` : "on no screen"
1736
+ ];
1737
+ out.push(`- ${name}: ${parts.join("; ")}.`);
1738
+ } else {
1739
+ const parts = [
1740
+ r.capabilities.length ? `may perform ${list2(r.capabilities)}` : "may perform no capability",
1741
+ r.screens.length ? `on ${list2(r.screens)}` : "on no screen"
1742
+ ];
1743
+ out.push(`- ${name}: ${parts.join("; ")}.`);
1744
+ }
1745
+ }
1746
+ out.push("");
1747
+ }
1541
1748
  const pieces = (title, list2, intro) => {
1542
1749
  if (!list2?.length) return;
1543
1750
  out.push(`## ${title}`, "");
@@ -1552,7 +1759,7 @@ function renderContext(c) {
1552
1759
  );
1553
1760
  for (const p of list2.filter((p2) => !p2.text))
1554
1761
  out.push(
1555
- `- ${p.id}${p.title ? ` ${p.title}` : ""}: \`${p.path}\`${p.changed ? " (this task changes it: its delta is above)" : ""}`
1762
+ `- ${p.id}${p.title ? ` ${p.title}` : ""}: \`${p.path}\`${p.changed ? " (this task changes it: its delta is above)" : ""}${p.note ? `; ${p.note}` : ""}`
1556
1763
  );
1557
1764
  out.push("");
1558
1765
  };
@@ -1574,7 +1781,17 @@ function renderContext(c) {
1574
1781
  pieces(
1575
1782
  "Entities",
1576
1783
  c.entities,
1577
- "The entities the task\u2019s capabilities work with; open one for its attributes, states and transitions."
1784
+ "The entities the task\u2019s capabilities work with, each with its lifecycle; open one for its attributes."
1785
+ );
1786
+ pieces(
1787
+ "Quality requirements",
1788
+ c.nfr,
1789
+ "The quality requirements the task touches or the change\u2019s text names, whole (one the task adds is whole in its delta above)."
1790
+ );
1791
+ pieces(
1792
+ "Integrations",
1793
+ c.integrations,
1794
+ "The integrations the task touches or the change\u2019s text names, whole (one the task adds is whole in its delta above)."
1578
1795
  );
1579
1796
  pieces("Operations for other systems", c.operations);
1580
1797
  pieces(
@@ -1617,8 +1834,8 @@ function contextStats(markdown) {
1617
1834
 
1618
1835
  // src/git.ts
1619
1836
  import { execFileSync as execFileSync3 } from "child_process";
1620
- import { existsSync as existsSync4, lstatSync, readdirSync as readdirSync2, readlinkSync, realpathSync, symlinkSync } from "fs";
1621
- import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative, resolve as resolve2 } from "path";
1837
+ import { existsSync as existsSync4 } from "fs";
1838
+ import { join as join4 } from "path";
1622
1839
 
1623
1840
  // src/task.ts
1624
1841
  var TRAILER = "Alterspec-Task";
@@ -1688,106 +1905,6 @@ function mainBranch(repo, configured) {
1688
1905
  const head = tryGit(repo, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
1689
1906
  return head?.replace(/^origin\//, "") || "main";
1690
1907
  }
1691
- var branchExists = (repo, branch) => tryGit(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]) !== void 0;
1692
- function taskWorktree(repo, task, opts) {
1693
- const branch = branchOf(task);
1694
- const from = opts.from?.replace(/^origin\//, "") || opts.main;
1695
- if (tryGit(repo, ["fetch", "--quiet", "origin", from]) === void 0 && from !== opts.main)
1696
- throw new GitError(`origin has no branch ${from}: was the predecessor's branch pushed?`);
1697
- const base = `origin/${from}`;
1698
- if (!tryGit(repo, ["rev-parse", "--verify", "--quiet", base]))
1699
- throw new GitError(`There is no ${base} here: is "${from}" a branch of origin?`);
1700
- if (opts.here) {
1701
- const top2 = git2(repo, ["rev-parse", "--show-toplevel"]);
1702
- if (tryGit(repo, ["symbolic-ref", "--short", "HEAD"]) === branch)
1703
- return { path: top2, branch, created: false, base };
1704
- if (git2(repo, ["status", "--porcelain", "--untracked-files=no"]))
1705
- throw new GitError(
1706
- `This checkout has uncommitted work: commit or stash it before switching to ${branch}.`
1707
- );
1708
- if (branchExists(repo, branch)) {
1709
- git2(repo, ["switch", "--quiet", branch]);
1710
- return { path: top2, branch, created: false, base };
1711
- }
1712
- git2(repo, ["switch", "--quiet", "--no-track", "-c", branch, base]);
1713
- return { path: top2, branch, created: true, base };
1714
- }
1715
- const path = resolve2(opts.worktreesDir, folderOf(task));
1716
- const listed = git2(repo, ["worktree", "list", "--porcelain"]).split("\n").filter((l) => l.startsWith("worktree ")).map((l) => real(l.slice("worktree ".length)));
1717
- const top = git2(repo, ["rev-parse", "--show-toplevel"]);
1718
- if (listed.includes(real(path))) {
1719
- const bridges = bridgeTrackedLinks(top, path);
1720
- return { path, branch, created: false, base, bridges, dangling: danglingLinks(path) };
1721
- }
1722
- if (branchExists(repo, branch)) git2(repo, ["worktree", "add", "--quiet", path, branch]);
1723
- else git2(repo, ["worktree", "add", "--quiet", "--no-track", "-b", branch, path, base]);
1724
- return {
1725
- path,
1726
- branch,
1727
- created: true,
1728
- base,
1729
- links: mirrorIgnoredLinks(top, path),
1730
- bridges: bridgeTrackedLinks(top, path),
1731
- dangling: danglingLinks(path)
1732
- };
1733
- }
1734
- var danglingLinks = (worktree) => readdirSync2(worktree, { withFileTypes: true }).filter((e) => e.isSymbolicLink() && !existsSync4(join4(worktree, e.name))).map((e) => e.name);
1735
- function mirrorIgnoredLinks(top, worktree) {
1736
- const links = readdirSync2(top, { withFileTypes: true }).filter((e) => e.isSymbolicLink()).map((e) => e.name);
1737
- if (!links.length) return [];
1738
- const ignored = new Set((tryGit(top, ["check-ignore", "--", ...links]) ?? "").split("\n").filter(Boolean));
1739
- const at = real(worktree);
1740
- return links.filter((name) => {
1741
- if (!ignored.has(name) || present(join4(at, name))) return false;
1742
- const target = readlinkSync(join4(top, name));
1743
- symlinkSync(isAbsolute2(target) ? target : relative(at, resolve2(top, target)), join4(at, name));
1744
- return true;
1745
- });
1746
- }
1747
- function bridgeTrackedLinks(top, worktree) {
1748
- const at = real(worktree);
1749
- const bridges = [];
1750
- for (const entry of readdirSync2(at, { withFileTypes: true })) {
1751
- const link = join4(at, entry.name);
1752
- if (!entry.isSymbolicLink() || existsSync4(link)) continue;
1753
- const target = readlinkSync(link);
1754
- const source = resolve2(top, target);
1755
- if (isAbsolute2(target) || !existsSync4(source)) continue;
1756
- let missing = resolve2(at, target);
1757
- let from = source;
1758
- while (!present(dirname2(missing))) {
1759
- missing = dirname2(missing);
1760
- from = dirname2(from);
1761
- }
1762
- const inside = (dir) => !relative(dir, missing).startsWith("..");
1763
- const refuse = (why, fix) => new GitError(
1764
- `${entry.name} in ${at} points to ${target}, which resolves from the checkout but not from the worktree, and ${why}: ${fix}.`
1765
- );
1766
- const untrack = "keep the link out of git (ignored, not committed), so the client links it into each worktree";
1767
- if (inside(at) || inside(top))
1768
- throw refuse(`the folder it misses, ${missing}, lies inside a checkout`, untrack);
1769
- const parent = dirname2(missing);
1770
- if (present(missing) || !existsSync4(parent) || realpathSync(parent) !== parent) {
1771
- const blocking = present(missing) ? missing : parent;
1772
- throw refuse(
1773
- `${blocking} is in the way`,
1774
- `remove it, or make it lead to ${present(missing) ? from : parent}`
1775
- );
1776
- }
1777
- symlinkSync(relative(parent, from), missing);
1778
- bridges.push(missing);
1779
- }
1780
- return bridges;
1781
- }
1782
- var present = (path) => {
1783
- try {
1784
- lstatSync(path);
1785
- return true;
1786
- } catch {
1787
- return false;
1788
- }
1789
- };
1790
- var real = (path) => existsSync4(path) ? realpathSync(path) : resolve2(path);
1791
1908
  var escape = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
1792
1909
  function mergedCommit(repo, task, main) {
1793
1910
  const branch = branchOf(task);
@@ -1825,13 +1942,22 @@ function mergedInto(repo, task, target) {
1825
1942
 
1826
1943
  // src/install.ts
1827
1944
  import { spawnSync } from "child_process";
1828
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync as readFileSync5, readdirSync as readdirSync4, statSync, writeFileSync as writeFileSync4 } from "fs";
1829
- import { join as join6, relative as relative2 } from "path";
1945
+ import {
1946
+ existsSync as existsSync6,
1947
+ lstatSync,
1948
+ mkdirSync as mkdirSync2,
1949
+ readFileSync as readFileSync5,
1950
+ readdirSync as readdirSync3,
1951
+ realpathSync,
1952
+ statSync,
1953
+ writeFileSync as writeFileSync4
1954
+ } from "fs";
1955
+ import { join as join6, relative } from "path";
1830
1956
  import { fileURLToPath } from "url";
1831
1957
 
1832
1958
  // ../src/install/installer.ts
1833
- import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync4, readdirSync as readdirSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
1834
- import { dirname as dirname3, join as join5 } from "path";
1959
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync4, readdirSync as readdirSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
1960
+ import { dirname as dirname2, join as join5 } from "path";
1835
1961
 
1836
1962
  // ../src/install/hash.ts
1837
1963
  import { createHash as createHash2 } from "crypto";
@@ -1850,7 +1976,7 @@ function readManifest(root, path = MANIFEST_PATH) {
1850
1976
  }
1851
1977
  function write(root, path, content) {
1852
1978
  const full = join5(root, path);
1853
- mkdirSync(dirname3(full), { recursive: true });
1979
+ mkdirSync(dirname2(full), { recursive: true });
1854
1980
  writeFileSync3(full, content);
1855
1981
  }
1856
1982
  function install(root, plan, opts) {
@@ -1910,8 +2036,8 @@ function install(root, plan, opts) {
1910
2036
  if (sha256(readFileSync4(full, "utf8")) === hash) {
1911
2037
  rmSync2(full);
1912
2038
  result.removed.push(path);
1913
- const folder = dirname3(full);
1914
- if (emptiedFolder.test(folder) && readdirSync3(folder).length === 0)
2039
+ const folder = dirname2(full);
2040
+ if (emptiedFolder.test(folder) && readdirSync2(folder).length === 0)
1915
2041
  rmSync2(folder, { recursive: true });
1916
2042
  } else {
1917
2043
  result.conflicts.push(path);
@@ -1931,10 +2057,10 @@ var MCP_JSON = ".mcp.json";
1931
2057
  var MCP_SERVER = "dispatcher";
1932
2058
  var MCP_ENTRY = { command: "npx", args: ["@alterset/alterspec-client", "mcp"] };
1933
2059
  function walk(dir) {
1934
- return readdirSync4(dir).sort().flatMap((n) => statSync(join6(dir, n)).isDirectory() ? walk(join6(dir, n)) : [join6(dir, n)]);
2060
+ return readdirSync3(dir).sort().flatMap((n) => statSync(join6(dir, n)).isDirectory() ? walk(join6(dir, n)) : [join6(dir, n)]);
1935
2061
  }
1936
2062
  var assetFiles = (sub) => walk(join6(ASSETS_DIR, sub)).map((f) => ({
1937
- rel: relative2(join6(ASSETS_DIR, sub), f).split("\\").join("/"),
2063
+ rel: relative(join6(ASSETS_DIR, sub), f).split("\\").join("/"),
1938
2064
  content: readFileSync5(f, "utf8")
1939
2065
  }));
1940
2066
  function buildClientPlan(version) {
@@ -2029,6 +2155,28 @@ function writeLocalSettings(root) {
2029
2155
  writeFileSync4(path, JSON.stringify(data, null, 2) + "\n");
2030
2156
  return before === void 0 ? "created" : "updated";
2031
2157
  }
2158
+ function approveHere(configRoot, cwd = process.cwd()) {
2159
+ const top = spawnSync("git", ["rev-parse", "--show-toplevel"], {
2160
+ cwd,
2161
+ encoding: "utf8",
2162
+ stdio: ["ignore", "pipe", "ignore"]
2163
+ }).stdout?.trim();
2164
+ const same = (a, b) => {
2165
+ try {
2166
+ return realpathSync(a) === realpathSync(b);
2167
+ } catch {
2168
+ return a === b;
2169
+ }
2170
+ };
2171
+ if (!top || same(top, configRoot)) return { root: configRoot, outcome: "unchanged" };
2172
+ if (!existsSync6(join6(top, MCP_JSON))) return { root: top, outcome: "unchanged" };
2173
+ const claude = join6(top, ".claude");
2174
+ try {
2175
+ if (lstatSync(claude).isSymbolicLink() && !existsSync6(claude)) return { root: top, outcome: "unchanged" };
2176
+ } catch {
2177
+ }
2178
+ return { root: top, outcome: writeLocalSettings(top) };
2179
+ }
2032
2180
  function ignoreLocalSettings(root) {
2033
2181
  const git4 = (...args) => spawnSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).status;
2034
2182
  if (git4("ls-files", "--error-unmatch", CLAUDE_LOCAL_SETTINGS) === 0) return "tracked";
@@ -2493,9 +2641,9 @@ async function progressHook(opts) {
2493
2641
  }
2494
2642
  async function hookCwd(input, waitMs = 1e3) {
2495
2643
  if (input.isTTY) return void 0;
2496
- const text = await new Promise((resolve3) => {
2644
+ const text = await new Promise((resolve2) => {
2497
2645
  let data = "";
2498
- const done = () => resolve3(data);
2646
+ const done = () => resolve2(data);
2499
2647
  const timer = setTimeout(done, waitMs);
2500
2648
  input.on("data", (c) => data += c.toString());
2501
2649
  input.on("end", () => {
@@ -2556,11 +2704,19 @@ var ignoreLines = (o) => o === "added" ? [`Added ${CLAUDE_LOCAL_SETTINGS} to .gi
2556
2704
  ] : o === "unknown" ? [
2557
2705
  `Make sure git ignores ${CLAUDE_LOCAL_SETTINGS} (where .claude is a symlink, in the repository it points to).`
2558
2706
  ] : [];
2707
+ function approveWorktree(loaded) {
2708
+ const { root, outcome } = approveHere(loaded.root);
2709
+ if (outcome === "unchanged") return;
2710
+ process.stderr.write(
2711
+ `Approved the "dispatcher" server for you in ${join8(root, CLAUDE_LOCAL_SETTINGS)} (this checkout had no approval of its own); its tools appear in the next Claude Code session here.
2712
+ `
2713
+ );
2714
+ }
2559
2715
  var program = new Command();
2560
2716
  program.name("alterspec-client").description("alterspec client \u2014 takes tasks of an alterspec export from the dispatcher.").version(packageVersion());
2561
2717
  program.command("init").description(
2562
2718
  "set the client up in this repository: configuration, the dispatcher in .mcp.json, the progress hook, the skills"
2563
- ).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(
2719
+ ).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("--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(
2564
2720
  run(
2565
2721
  (opts) => {
2566
2722
  const root = process.cwd();
@@ -2621,13 +2777,16 @@ program.command("mcp").description(
2621
2777
  );
2622
2778
  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(
2623
2779
  run((opts) => {
2624
- const head = exportHead(exportDir(loadConfig()), opts.latest);
2780
+ const loaded = loadConfig();
2781
+ approveWorktree(loaded);
2782
+ const head = exportHead(exportDir(loaded), opts.latest);
2625
2783
  process.stdout.write(JSON.stringify(head, null, 2) + "\n");
2626
2784
  })
2627
2785
  );
2628
2786
  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").option("--stats", "print its size by section instead").action(
2629
2787
  run(async (id, opts) => {
2630
2788
  const loaded = loadConfig();
2789
+ approveWorktree(loaded);
2631
2790
  const dir = exportDir(loaded);
2632
2791
  const x = readExport(dir);
2633
2792
  const task = parseTask(id);
@@ -2668,34 +2827,6 @@ program.command("progress").description("report the items the task\u2019s commit
2668
2827
  process.stdout.write(opts.json ? JSON.stringify(report, null, 2) + "\n" : progressText(report));
2669
2828
  })();
2670
2829
  });
2671
- program.command("worktree").description(
2672
- "create the task\u2019s branch task/<chg>-<track> from origin/<main>, or from the predecessor\u2019s branch, in a worktree of its own"
2673
- ).argument("<task>", "the task, e.g. CHG-012/BE").option("--here", "make the branch in this checkout instead of a worktree").option(
2674
- "--from <branch>",
2675
- "the branch to start from: the one next_task named on a done predecessor of the same track (fetched as origin/<branch>)"
2676
- ).action(
2677
- run((id, opts) => {
2678
- const loaded = loadConfig();
2679
- const wt = taskWorktree(process.cwd(), parseTask(id), {
2680
- main: mainBranch(process.cwd(), loaded.config.branch),
2681
- worktreesDir: worktreesDir(loaded),
2682
- here: opts.here,
2683
- from: opts.from
2684
- });
2685
- process.stderr.write(
2686
- wt.created ? `Created ${wt.branch} from ${wt.base}.
2687
- ` : `${wt.branch} exists already; it was not rebased on ${wt.base}.
2688
- `
2689
- );
2690
- if (wt.dangling?.length)
2691
- process.stderr.write(
2692
- `In ${wt.path}, ${wt.dangling.join(", ")} ${wt.dangling.length === 1 ? "points" : "point"} nowhere. A symlink git tracks is checked out as it is, so a relative target made for the checkout doesn't resolve from the worktree: keep such links out of git (ignored, not committed) and the client links them into each worktree, or fix them there.
2693
- `
2694
- );
2695
- if (!opts.here && !wt.dangling?.includes(".claude")) writeLocalSettings(wt.path);
2696
- process.stdout.write(JSON.stringify(wt, null, 2) + "\n");
2697
- })
2698
- );
2699
2830
  program.command("lookup").description(
2700
2831
  "where in the export a question is answered: what to read first, and what before calling it silent"
2701
2832
  ).argument("[ref...]", "IDs and terms the question is about").option("--question <text>", "the question, in full").option("--task <task>", "the task it came up in, e.g. CHG-012/BE").option("--item <item>", "the checklist item it concerns").option("--unread <path...>", "the paths that were opened: print what must still be, and exit 1 when any").option("--json", "print it as JSON").action(