@alterset/alterspec-client 0.15.0 → 0.17.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
@@ -14,6 +14,7 @@ import { z as z2 } from "zod";
14
14
  // ../src/schemas/work.ts
15
15
  import { z } from "zod";
16
16
  var TrackCode = z.string().regex(/^[A-Z]{2,5}$/, { message: "must be BE or a channel code" });
17
+ var WorkWeight = z.number().int().min(1).max(100);
17
18
  var ChangeRef = z.string().regex(/^CHG-\d{3,}$/);
18
19
  var Day = z.iso.date();
19
20
  var WorkTrackSchema = z.object({
@@ -38,7 +39,14 @@ var WorkTaskSchema = z.object({
38
39
  * changes it builds on that did the same work (an item of both, a line of a whole object this task edits again,
39
40
  * or an object this task names that entered the export with the earlier change).
40
41
  */
41
- after: z.array(z.object({ change: ChangeRef, track: TrackCode }).strict())
42
+ after: z.array(z.object({ change: ChangeRef, track: TrackCode }).strict()),
43
+ /**
44
+ * The weight of each item (format 3): how much specified behaviour it adds or changes, 1–100, reasoned at the
45
+ * change's sign-off against alterspec's rubric (a typical acceptance criterion about 10), never anyone's code.
46
+ * An item the sign-off didn't weigh takes the median of the task's weighed items; a task of a change signed off
47
+ * without weights has no `weights`, and a reader counts each of its items as 10. For weighing progress and ETA.
48
+ */
49
+ weights: z.record(z.string().min(1), WorkWeight).optional()
42
50
  }).strict();
43
51
  var WorkChangeSchema = z.object({
44
52
  id: ChangeRef,
@@ -52,7 +60,7 @@ var WorkChangeSchema = z.object({
52
60
  /** One per track the change is on; empty = no work. */
53
61
  tasks: z.array(WorkTaskSchema)
54
62
  }).strict();
55
- var WORK_FORMAT = 2;
63
+ var WORK_FORMAT = 3;
56
64
  var WorkSchema = z.object({
57
65
  format: z.literal(WORK_FORMAT),
58
66
  /** The alterspec version that wrote the export. */
@@ -64,12 +72,17 @@ var WorkSchema = z.object({
64
72
  /** Every change signed off after the baseline, in the change map's order. */
65
73
  changes: z.array(WorkChangeSchema)
66
74
  }).strict();
67
- var WorkTaskV1Schema = WorkTaskSchema.omit({ items: true });
75
+ var WorkTaskV2Schema = WorkTaskSchema.omit({ weights: true });
76
+ var WorkV2Schema = WorkSchema.extend({
77
+ format: z.literal(2),
78
+ changes: z.array(WorkChangeSchema.extend({ tasks: z.array(WorkTaskV2Schema) }).strict())
79
+ }).strict();
80
+ var WorkTaskV1Schema = WorkTaskV2Schema.omit({ items: true });
68
81
  var WorkV1Schema = WorkSchema.extend({
69
82
  format: z.literal(1),
70
83
  changes: z.array(WorkChangeSchema.extend({ tasks: z.array(WorkTaskV1Schema) }).strict())
71
84
  }).strict();
72
- var AnyWorkSchema = z.discriminatedUnion("format", [WorkV1Schema, WorkSchema]);
85
+ var AnyWorkSchema = z.discriminatedUnion("format", [WorkV1Schema, WorkV2Schema, WorkSchema]);
73
86
 
74
87
  // src/config.ts
75
88
  var CONFIG_FILE = ".alterspec-client.json";
@@ -319,9 +332,8 @@ function keyOf(loaded) {
319
332
  }
320
333
  var sessionOf = (loaded) => new Session(loaded.config.dispatcher, keyOf(loaded));
321
334
 
322
- // ../src/export/read.ts
323
- import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "fs";
324
- import { join as join3 } from "path";
335
+ // src/bugs.ts
336
+ import { z as z8 } from "zod";
325
337
 
326
338
  // ../src/schemas/delta.ts
327
339
  import { z as z6 } from "zod";
@@ -466,13 +478,25 @@ var ChangeSchema = z5.object({
466
478
  * rewritten, so a channel added later gives an old change no task.
467
479
  */
468
480
  tracks: z5.record(TrackCode, z5.array(z5.string())).optional(),
481
+ /**
482
+ * The weight of each task item (`work.json`), 1–100: how much specified behaviour the item adds or changes,
483
+ * reasoned by the sign-off skill against the rubric (`_weights.md`), never anyone's code. Written by
484
+ * `change weigh`, frozen at sign-off next to `tracks` (`{}` = signed off without weighing); absent = signed off
485
+ * before weights existed. The dispatcher weighs progress and ETA by it.
486
+ */
487
+ weights: z5.record(z5.string(), WorkWeight).optional(),
469
488
  /**
470
489
  * In a team project: the draft IDs the change and what it creates carried until the sign-off numbered them
471
490
  * (draft → final). Written by the CLI at sign-off.
472
491
  */
473
492
  drafted_as: z5.record(z5.string(), z5.string()).optional(),
474
493
  /** The first 16 hex of the sha256 of the change's `delta.json`, written with it at sign-off, never rewritten. */
475
- delta: z5.string().regex(/^[0-9a-f]{16}$/).optional()
494
+ delta: z5.string().regex(/^[0-9a-f]{16}$/).optional(),
495
+ /**
496
+ * Accepted findings on the archived change itself (`delta-chain`: a merge of parallel sign-offs no delta
497
+ * recorded), each on a decided decision naming the change; history can't be fixed, only accepted.
498
+ */
499
+ accepts: list(AcceptSchema)
476
500
  }).strict().superRefine((c, ctx) => {
477
501
  for (const key of Object.keys(c.base)) {
478
502
  if (!ObjectKey.safeParse(key).success) {
@@ -533,6 +557,26 @@ function exportChange(e) {
533
557
  return "not in the export";
534
558
  }
535
559
 
560
+ // ../src/changes/data-change.ts
561
+ var DATA_CHANGE_SECTION = "One-time data change";
562
+ var DATA_CHANGE_ITEM = "data-change";
563
+ var DATA_CHANGE_RE = new RegExp(`^(CHG-\\d{3,})#${DATA_CHANGE_ITEM}$`);
564
+ function dataChangeText(sectionText2) {
565
+ const text = sectionText2?.trim();
566
+ return text && !/^none\b/i.test(text) ? text : void 0;
567
+ }
568
+
569
+ // ../src/export/paths.ts
570
+ var EXPORT_JSON = "export.json";
571
+ var WORK_JSON = "work.json";
572
+ var SHARDS_DIR = "_shards";
573
+ var slug = (text) => text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[đłøæœßþ]/g, (c) => ({ \u0111: "d", \u0142: "l", \u00F8: "o", \u00E6: "ae", \u0153: "oe", \u00DF: "ss", \u00FE: "th" })[c] ?? c).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "section";
574
+ var shardDir = (path) => `${SHARDS_DIR}/${path.replace(/\.md$/, "")}`;
575
+ var itemShardName = (key) => `${key.startsWith("term:") ? slug(key.slice(5)) : key}.md`;
576
+ var itemShardPath = (path, key) => `${shardDir(path)}/${itemShardName(key)}`;
577
+ var FRONT_MATTER_SHARD = "00-front-matter.yaml";
578
+ var isSectionShard = (name, heading) => new RegExp(`^\\d{2}-${slug(heading)}\\.md$`).test(name);
579
+
536
580
  // ../src/lib/frontmatter-split.ts
537
581
  var FRONT_MATTER = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;
538
582
  function splitFrontMatter(source) {
@@ -545,6 +589,79 @@ function splitFrontMatter(source) {
545
589
  };
546
590
  }
547
591
 
592
+ // ../src/changes/parts.ts
593
+ var FRONT_MATTER_PART = "front-matter";
594
+ var itemObject = (item) => item.startsWith("file:") ? item : item.replace(/-AC-\d{2}$/, "").replace(/[.#][^.#]*$/, "");
595
+ 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, "");
596
+ function objectParts(text, kind) {
597
+ const out = /* @__PURE__ */ new Map();
598
+ const put = (label, heading, body2) => {
599
+ const base = label === "front-matter" ? FRONT_MATTER_PART : slug(heading);
600
+ let key = base;
601
+ for (let n = 2; out.has(key); n++) key = `${base}-${n}`;
602
+ out.set(key, { label, heading, text: body2 });
603
+ };
604
+ const t = forWork(text);
605
+ if (kind === "doc") {
606
+ const { raw, body: body2 } = splitFrontMatter(t);
607
+ if (raw) put("front-matter", FRONT_MATTER_PART, raw);
608
+ for (const s of headed(body2, "## ").sections) put("section", s.heading, s.text);
609
+ return out;
610
+ }
611
+ const yaml = /^```ya?ml\n([\s\S]*?)\n```[^\S\n]*$/m.exec(t);
612
+ if (yaml) put("front-matter", FRONT_MATTER_PART, yaml[1]);
613
+ const body = yaml ? t.slice(yaml.index + yaml[0].length) : t.replace(/^## [^\n]*\n?/, "");
614
+ const { sections } = headed(body, "### ");
615
+ if (sections.length) for (const s of sections) put("section", s.heading, s.text);
616
+ else for (const b of bullets(body)) put("line", b.heading, b.text);
617
+ return out;
618
+ }
619
+ function headed(text, marker) {
620
+ const sections = [];
621
+ let intro = "";
622
+ let fence2 = false;
623
+ for (const l of text.split("\n")) {
624
+ if (/^(?:```|~~~)/.test(l)) fence2 = !fence2;
625
+ if (!fence2 && l.startsWith(marker) && /\S/.test(l.slice(marker.length))) {
626
+ sections.push({ heading: l.slice(marker.length).trim(), text: "" });
627
+ continue;
628
+ }
629
+ if (sections.length) sections[sections.length - 1].text += `${l}
630
+ `;
631
+ else intro += `${l}
632
+ `;
633
+ }
634
+ return { intro, sections };
635
+ }
636
+ var BULLET = /^(?:[-*+]|\d+[.)])\s+(.*)$/;
637
+ function bullets(text) {
638
+ const out = [];
639
+ let current;
640
+ let fence2 = false;
641
+ for (const l of text.split("\n")) {
642
+ if (/^(?:```|~~~)/.test(l)) {
643
+ fence2 = !fence2;
644
+ current = void 0;
645
+ continue;
646
+ }
647
+ if (fence2) continue;
648
+ const m = BULLET.exec(l);
649
+ if (m) {
650
+ current = { heading: lead(m[1]), text: `${l}
651
+ ` };
652
+ out.push(current);
653
+ } else if (current && /^\s+\S/.test(l)) current.text += `${l}
654
+ `;
655
+ else current = void 0;
656
+ }
657
+ return out;
658
+ }
659
+ var lead = (s) => s.replace(/\*\*|__|`/g, "").split(/:\s|:$|\s[—–-]\s|\.\s|\.$/)[0].trim().split(/\s+/).slice(0, 8).join(" ");
660
+
661
+ // ../src/export/read.ts
662
+ import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "fs";
663
+ import { join as join3 } from "path";
664
+
548
665
  // ../src/spec/layout.ts
549
666
  var ROOT_DOCS = {
550
667
  application: "application.md",
@@ -590,17 +707,6 @@ var ARCHIVED_PROPOSAL = new RegExp(
590
707
  String.raw`^(?:${MODULES_DIR}\/(?<mod>[^/]+)\/)?${CHANGES_DIR}\/archive\/(?<change>[^/]+)\/proposal\.md$`
591
708
  );
592
709
 
593
- // ../src/export/paths.ts
594
- var EXPORT_JSON = "export.json";
595
- var WORK_JSON = "work.json";
596
- var SHARDS_DIR = "_shards";
597
- 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";
598
- var shardDir = (path) => `${SHARDS_DIR}/${path.replace(/\.md$/, "")}`;
599
- var itemShardName = (key) => `${key.startsWith("term:") ? slug(key.slice(5)) : key}.md`;
600
- var itemShardPath = (path, key) => `${shardDir(path)}/${itemShardName(key)}`;
601
- var FRONT_MATTER_SHARD = "00-front-matter.yaml";
602
- var isSectionShard = (name, heading) => new RegExp(`^\\d{2}-${slug(heading)}\\.md$`).test(name);
603
-
604
710
  // ../src/export/read.ts
605
711
  var ExportReadError = class extends Error {
606
712
  };
@@ -676,84 +782,6 @@ function idsIn(text, kinds) {
676
782
  }
677
783
  var frontMatterOf = (text) => splitFrontMatter(text).raw ?? "";
678
784
 
679
- // ../src/changes/data-change.ts
680
- var DATA_CHANGE_SECTION = "One-time data change";
681
- var DATA_CHANGE_ITEM = "data-change";
682
- var DATA_CHANGE_RE = new RegExp(`^(CHG-\\d{3,})#${DATA_CHANGE_ITEM}$`);
683
- function dataChangeText(sectionText2) {
684
- const text = sectionText2?.trim();
685
- return text && !/^none\b/i.test(text) ? text : void 0;
686
- }
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
-
757
785
  // ../src/lib/diff.ts
758
786
  var linesOf = (text) => text === "" ? [] : text.replace(/\n$/, "").split("\n");
759
787
  function diffLines(a, b) {
@@ -1443,6 +1471,7 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1443
1471
  const entries = new Map(delta?.objects.map((e) => [e.key, e]));
1444
1472
  const lost = new Map(delta?.unrecoverable?.map((u) => [u.key, u.why]));
1445
1473
  const items = work.items;
1474
+ const weights = work.weights;
1446
1475
  const ctx = {
1447
1476
  task: task.id,
1448
1477
  ...questions ? { questions } : {},
@@ -1451,10 +1480,12 @@ function taskContext(x, task, exportDir2, state = {}, questions) {
1451
1480
  checklist: {
1452
1481
  items: items.map((item) => {
1453
1482
  const covered = state.covered?.get(item);
1483
+ const weight = weights?.[item];
1454
1484
  return {
1455
1485
  item,
1456
1486
  what: itemWhat(x, item, entries.get(itemObject(item)), task.track),
1457
- ...covered ? { covered } : {}
1487
+ ...covered ? { covered } : {},
1488
+ ...weight === void 0 ? {} : { weight }
1458
1489
  };
1459
1490
  }),
1460
1491
  known: state.covered !== void 0,
@@ -1653,14 +1684,21 @@ function renderContext(c) {
1653
1684
  else {
1654
1685
  const list2 = c.checklist;
1655
1686
  const done = list2.items.filter((i) => i.covered).length;
1687
+ const weighed = list2.items.some((i) => i.weight !== void 0);
1688
+ const sum = (items) => items.reduce((a, i) => a + (i.weight ?? 0), 0);
1689
+ const weight = weighed ? list2.known ? `, ${sum(list2.items.filter((i) => i.covered))} of ${sum(list2.items)} weight` : `, ${sum(list2.items)} weight` : "";
1656
1690
  out.push(
1657
- `## Checklist (${list2.known ? `${done} of ${list2.items.length} covered` : `${list2.items.length} item${list2.items.length === 1 ? "" : "s"}`})`,
1691
+ `## Checklist (${list2.known ? `${done} of ${list2.items.length} covered` : `${list2.items.length} item${list2.items.length === 1 ? "" : "s"}`}${weight})`,
1658
1692
  "",
1659
1693
  "Name an item in `Alterspec-Covers` on the commit with which its tests pass.",
1694
+ ...weighed ? [
1695
+ "The weight (w) is how much specified behaviour an item is, 1\u2013100, reasoned at the sign-off from the spec alone;",
1696
+ "progress and the ETA count weight, not items. Start with the heavy ones."
1697
+ ] : [],
1660
1698
  ...list2.note ? ["", `Covered items unknown: ${list2.note}`] : [],
1661
1699
  "",
1662
1700
  ...list2.items.map(
1663
- (i) => `- [${i.covered ? "x" : " "}] \`${i.item}\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ""}`
1701
+ (i) => `- [${i.covered ? "x" : " "}] \`${i.item}\`${i.weight === void 0 ? "" : ` (w ${i.weight})`}: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ""}`
1664
1702
  )
1665
1703
  );
1666
1704
  }
@@ -1832,6 +1870,188 @@ function contextStats(markdown) {
1832
1870
  ].join("\n") + "\n";
1833
1871
  }
1834
1872
 
1873
+ // src/bugs.ts
1874
+ var BugTaskSchema = z8.object({
1875
+ id: z8.string(),
1876
+ track: z8.string(),
1877
+ status: z8.string(),
1878
+ developer: z8.string().nullish(),
1879
+ items: z8.array(z8.string()).default([]),
1880
+ /** The built tasks it waits for. */
1881
+ after: z8.array(z8.string()).default([]),
1882
+ branch: z8.string().nullish(),
1883
+ in_main: z8.boolean().nullish()
1884
+ });
1885
+ var BugSchema = z8.object({
1886
+ id: z8.string(),
1887
+ title: z8.string(),
1888
+ description: z8.string(),
1889
+ /** The reporter. */
1890
+ developer: z8.string(),
1891
+ at: z8.string(),
1892
+ export: z8.string().nullish(),
1893
+ cites: z8.array(z8.string()).default([]),
1894
+ /** The changes of the tasks it waits for. */
1895
+ origin: z8.array(z8.string()).default([]),
1896
+ status: z8.enum(["open", "done", "dismissed"]).default("open"),
1897
+ dismissed: z8.object({ by: z8.string(), at: z8.string(), reason: z8.string(), duplicate_of: z8.string().nullish() }).nullish(),
1898
+ tasks: z8.array(BugTaskSchema).default([])
1899
+ });
1900
+ var BugsError = class extends Error {
1901
+ };
1902
+ async function listBugs(session, filter = {}) {
1903
+ const answer = await callTool(session, "bugs", {
1904
+ ...filter.about ? { about: filter.about } : { mine: true },
1905
+ ...filter.status ? { status: filter.status } : {},
1906
+ ...filter.track ? { track: filter.track } : {}
1907
+ });
1908
+ const parsed = z8.array(BugSchema).safeParse(answer.bugs ?? []);
1909
+ if (!parsed.success) throw new BugsError("The dispatcher\u2019s bugs are not in a form this client reads.");
1910
+ return parsed.data;
1911
+ }
1912
+ var one2 = (text) => text.replace(/\s+/g, " ").trim();
1913
+ function bugTaskWords(t) {
1914
+ const who = t.developer ? ` (${t.developer})` : "";
1915
+ const where = t.status === "blocked" && t.after.length ? `, after ${t.after.join(", ")}` : t.status === "done" ? t.in_main ? ", in main" : t.branch ? `, on \`${t.branch}\`` : "" : "";
1916
+ return `${t.id} ${t.status}${who}${where}`;
1917
+ }
1918
+ function bugLines(b) {
1919
+ const state = b.status === "dismissed" ? `dismissed by ${b.dismissed?.by ?? "an admin"}${b.dismissed?.duplicate_of ? `, duplicate of ${b.dismissed.duplicate_of}` : ""}` : b.status;
1920
+ const lines = [`- ${b.id} (${state}; ${b.developer}, ${b.at.slice(0, 10)}): ${one2(b.title)}`];
1921
+ if (b.cites.length) lines.push(` - Cites: ${b.cites.join(", ")}`);
1922
+ if (b.dismissed) lines.push(` - Reason: ${one2(b.dismissed.reason)}`);
1923
+ else if (b.tasks.length) lines.push(` - Tasks: ${b.tasks.map(bugTaskWords).join("; ")}`);
1924
+ return lines;
1925
+ }
1926
+ function bugsText(bugs) {
1927
+ if (!bugs.length) return "No bugs.\n";
1928
+ return bugs.flatMap(bugLines).join("\n") + "\n";
1929
+ }
1930
+ function parseBug(raw) {
1931
+ const parsed = BugSchema.safeParse(raw);
1932
+ return parsed.success ? parsed.data : void 0;
1933
+ }
1934
+ async function bugTaskState(session, task) {
1935
+ let answer;
1936
+ try {
1937
+ answer = await callTool(session, "task", { id: task.id });
1938
+ } catch (e) {
1939
+ throw new BugsError(
1940
+ `${task.id} is a bug's task, and only the dispatcher holds a bug: ${e.message.split("\n")[0]}`
1941
+ );
1942
+ }
1943
+ const bug = parseBug(answer.bug);
1944
+ if (!bug) throw new BugsError(`The dispatcher sent no bug for ${task.id} this client reads.`);
1945
+ const items = answer.items ?? [];
1946
+ const from = startFrom(task.track, answer.after);
1947
+ return {
1948
+ bug,
1949
+ objects: z8.array(z8.string()).catch([]).parse(answer.objects),
1950
+ after: (answer.after ?? []).flatMap((a) => a.id ? [a.id] : []),
1951
+ covered: new Map(items.flatMap((i) => i.covered_commit ? [[i.item, i.covered_commit]] : [])),
1952
+ ...from.length ? { startFrom: from } : {}
1953
+ };
1954
+ }
1955
+ var objectOfItem = (item, objects) => [...objects].filter(
1956
+ (o) => item === o || item.startsWith(`${o}-`) || item.startsWith(`${o}.`) || item.startsWith(`${o}#`)
1957
+ ).sort((a, b) => b.length - a.length)[0] ?? item.replace(/(-AC-\d+|\.A\d+|#.+)$/, "");
1958
+ function bugContext(x, task, exportDir2, state, questions) {
1959
+ const track = x.work.tracks.find((t) => t.code === task.track) ?? {
1960
+ code: task.track,
1961
+ kind: "ui",
1962
+ channels: []
1963
+ };
1964
+ const keys = [
1965
+ ...new Set(state.objects.length ? state.objects : state.bug.cites.map((c) => objectOfItem(c, [])))
1966
+ ];
1967
+ const objects = keys.map((key) => {
1968
+ const file = x.fileOf(key);
1969
+ const held = file !== void 0 && x.has(file);
1970
+ const o = { key, ...held ? { file } : {} };
1971
+ if (held && x.shards(file).length) o.shards = x.shards(file)[0].replace(/\/[^/]+$/, "");
1972
+ const by = x.sources.get(key)?.changed_by;
1973
+ if (by?.length) o.changed_by = by;
1974
+ return o;
1975
+ });
1976
+ return {
1977
+ task: task.id,
1978
+ bug: state.bug,
1979
+ track: { code: track.code, kind: track.kind, channels: track.channels },
1980
+ export: exportDir2,
1981
+ ...questions?.length ? { questions } : {},
1982
+ after: state.after,
1983
+ ...state.startFrom?.length ? { startFrom: state.startFrom } : {},
1984
+ checklist: {
1985
+ items: state.bug.cites.map((item) => {
1986
+ const covered = state.covered?.get(item);
1987
+ return { item, what: itemWhat(x, item, void 0, task.track), ...covered ? { covered } : {} };
1988
+ })
1989
+ },
1990
+ objects,
1991
+ origin: state.bug.origin.map((id) => {
1992
+ const change = x.work.changes.find((c) => c.id === id);
1993
+ const proposal = x.proposalPath(id);
1994
+ return { id, ...change ? { title: change.title } : {}, ...proposal ? { proposal } : {} };
1995
+ })
1996
+ };
1997
+ }
1998
+ function renderBugContext(c) {
1999
+ const b = c.bug;
2000
+ const out = [
2001
+ `# ${c.task}: ${b.title}`,
2002
+ "",
2003
+ `Track ${c.track.code} (${c.track.kind}${c.track.channels.length ? `: ${c.track.channels.join(", ")}` : ""}). Bug ${b.id}, raised by ${b.developer} on ${b.at.slice(0, 10)}${b.export ? `, groomed against export ${b.export.slice(0, 12)}` : ""}${b.origin.length ? `, in what ${b.origin.join(", ")} built` : ""}. Paths are relative to the export, ${c.export}.`
2004
+ ];
2005
+ if (c.after.length) out.push("", `Waits for: ${c.after.join(", ")}.`);
2006
+ if (c.startFrom?.length)
2007
+ out.push(
2008
+ "",
2009
+ `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 work the bug is in is pushed there and not merged yet (fetch it and base your branch on \`origin/${c.startFrom[c.startFrom.length - 1].branch}\`).`
2010
+ );
2011
+ out.push("");
2012
+ if (c.questions?.length) out.push(...questionsSection(c.questions));
2013
+ out.push(
2014
+ "## The bug",
2015
+ "",
2016
+ "The reporter\u2019s words, naming IDs; what the spec says is in the export, under the objects below. The product deviates from the cited items: make it do what they say, and nothing else. The tasks that built them stay as they are; this task is the fix.",
2017
+ "",
2018
+ b.description.trim(),
2019
+ "",
2020
+ `Cites: ${b.cites.join(", ")}.`
2021
+ );
2022
+ const done = c.checklist.items.filter((i) => i.covered).length;
2023
+ out.push(
2024
+ "",
2025
+ `## Checklist (${done} of ${c.checklist.items.length} covered)`,
2026
+ "",
2027
+ "The cited items. Name an item in `Alterspec-Covers` on the commit with which its tests pass again.",
2028
+ "",
2029
+ ...c.checklist.items.map(
2030
+ (i) => `- [${i.covered ? "x" : " "}] \`${i.item}\`: ${i.what}${i.covered ? ` (covered by ${i.covered.slice(0, 12)})` : ""}`
2031
+ )
2032
+ );
2033
+ out.push("", "## The objects", "", "What the spec says now; a bug is fixed against the current text.", "");
2034
+ for (const o of c.objects) {
2035
+ const where = o.file ? `\`${o.file}\`${o.shards ? `, shards in \`${o.shards}/\`` : ""}` : "not in the export now";
2036
+ out.push(
2037
+ `- ${o.key}: ${where}${o.changed_by?.length ? `; last changed by ${o.changed_by.join(", ")}` : ""}.`
2038
+ );
2039
+ }
2040
+ if (c.origin.length) {
2041
+ out.push(
2042
+ "",
2043
+ "## The changes it originates in",
2044
+ "",
2045
+ "What was built and found wanting; their proposals say why.",
2046
+ ""
2047
+ );
2048
+ for (const ch of c.origin)
2049
+ out.push(`- ${ch.id}${ch.title ? ` ${ch.title}` : ""}${ch.proposal ? `: ${ch.proposal}` : ""}`);
2050
+ }
2051
+ out.push("");
2052
+ return out.join("\n");
2053
+ }
2054
+
1835
2055
  // src/git.ts
1836
2056
  import { execFileSync as execFileSync3 } from "child_process";
1837
2057
  import { existsSync as existsSync4 } from "fs";
@@ -1842,16 +2062,23 @@ var TRAILER = "Alterspec-Task";
1842
2062
  var TaskError = class extends Error {
1843
2063
  };
1844
2064
  function parseTask(text) {
1845
- const m = /^(CHG-\d{3})\/([A-Z]{2,5})$/.exec(text.trim().toUpperCase());
2065
+ const m = /^(CHG-\d{3}|BUG-[1-9]\d*)\/([A-Z]{2,5})$/.exec(text.trim().toUpperCase());
1846
2066
  if (!m)
1847
- throw new TaskError(`"${text}" is not a task: write it as CHG-012/BE (the change, a slash, the track).`);
1848
- return { id: `${m[1]}/${m[2]}`, change: m[1], track: m[2] };
2067
+ throw new TaskError(
2068
+ `"${text}" is not a task: write it as CHG-012/BE (the change, a slash, the track), or BUG-3/BE for a bug's.`
2069
+ );
2070
+ return {
2071
+ id: `${m[1]}/${m[2]}`,
2072
+ change: m[1],
2073
+ track: m[2],
2074
+ kind: m[1].startsWith("BUG-") ? "bug" : "change"
2075
+ };
1849
2076
  }
1850
2077
  var branchOf = (t) => `task/${t.change.toLowerCase()}-${t.track.toLowerCase()}`;
1851
2078
  var folderOf = (t) => `${t.change.toLowerCase()}-${t.track.toLowerCase()}`;
1852
2079
  var COVERS = "Alterspec-Covers";
1853
2080
  function taskOfBranch(branch) {
1854
- const m = /^task\/(chg-\d{3})-([a-z]{2,5})$/.exec(branch?.trim() ?? "");
2081
+ const m = /^task\/(chg-\d{3}|bug-[1-9]\d*)-([a-z]{2,5})$/.exec(branch?.trim() ?? "");
1855
2082
  return m ? parseTask(`${m[1]}/${m[2]}`) : void 0;
1856
2083
  }
1857
2084
 
@@ -2598,8 +2825,9 @@ async function reportProgress(session, task, covered) {
2598
2825
  }
2599
2826
  function progressText(r) {
2600
2827
  const progress = r.answer.progress;
2828
+ const weight = r.answer.weight;
2601
2829
  const eta = r.answer.eta;
2602
- const count = progress ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %)` : "no checklist (its export predates task items)";
2830
+ const count = progress ? `${progress.covered} of ${progress.of} items covered (${progress.percent} %${weight ? `, ${weight.covered} of ${weight.total} weight` : ""})` : "no checklist (its export predates task items)";
2603
2831
  const when = !eta ? "" : eta.by === "done" ? "; done" : eta.date ? `; ETA ${eta.at_least ? "at least " : ""}${eta.date}${eta.by === "developer" ? ` (yours; computed ${eta.computed?.date ?? "unknown"})` : ""}` : "; ETA unknown";
2604
2832
  const lines = [`${r.task}: ${count}${when}.`];
2605
2833
  if (r.unknown.length) lines.unshift(unknownLine(r));
@@ -2783,13 +3011,27 @@ program.command("export-head").description("pull the export clone and print its
2783
3011
  process.stdout.write(JSON.stringify(head, null, 2) + "\n");
2784
3012
  })
2785
3013
  );
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(
3014
+ program.command("context").description("print a task\u2019s brief, assembled from the export").argument("<task>", "the task, e.g. CHG-012/BE or BUG-3/BE").option("--json", "print it as JSON").option("--stats", "print its size by section instead").action(
2787
3015
  run(async (id, opts) => {
2788
3016
  const loaded = loadConfig();
2789
3017
  approveWorktree(loaded);
2790
3018
  const dir = exportDir(loaded);
2791
3019
  const x = readExport(dir);
2792
3020
  const task = parseTask(id);
3021
+ if (task.kind === "bug") {
3022
+ const session = sessionOf(loaded);
3023
+ const ctx2 = bugContext(
3024
+ x,
3025
+ task,
3026
+ dir,
3027
+ await bugTaskState(session, task),
3028
+ await changeQuestions(session, [task.id])
3029
+ );
3030
+ process.stdout.write(
3031
+ opts.stats ? contextStats(renderBugContext(ctx2)) : opts.json ? JSON.stringify(ctx2, null, 2) + "\n" : renderBugContext(ctx2)
3032
+ );
3033
+ return;
3034
+ }
2793
3035
  const tasks = [
2794
3036
  task.id,
2795
3037
  ...(x.work.changes.find((c) => c.id === task.change)?.tasks ?? []).map((t) => `${task.change}/${t.track}`).filter((t) => t !== task.id)
@@ -2873,6 +3115,18 @@ program.command("questions").description("print the questions the dispatcher kee
2873
3115
  process.stdout.write(opts.json ? JSON.stringify(questions, null, 2) + "\n" : questionsText(questions));
2874
3116
  })
2875
3117
  );
3118
+ program.command("bugs").description("print the bugs the dispatcher keeps: the ones naming some IDs, or without --about your own").option("--about <id...>", "everyone\u2019s bugs whose cites, title or description name these IDs").option("--status <status>", "only the open, done or dismissed ones").option("--track <code>", "only those with a task on this track").option("--json", "print them as JSON").action(
3119
+ run(async (opts) => {
3120
+ if (opts.status && !["open", "done", "dismissed"].includes(opts.status))
3121
+ throw new Error(`--status takes open, done or dismissed, not "${opts.status}".`);
3122
+ const bugs = await listBugs(sessionOf(loadConfig()), {
3123
+ ...opts.about ? { about: opts.about } : {},
3124
+ ...opts.status ? { status: opts.status } : {},
3125
+ ...opts.track ? { track: opts.track.toUpperCase() } : {}
3126
+ });
3127
+ process.stdout.write(opts.json ? JSON.stringify(bugs, null, 2) + "\n" : bugsText(bugs));
3128
+ })
3129
+ );
2876
3130
  program.command("merged").description(
2877
3131
  "print the commit and branch to report done with: the pushed task branch\u2019s head, or the commit on origin/<main> that brought the task in"
2878
3132
  ).argument("<task>", "the task, e.g. CHG-012/BE").option("--json", "print { commit, branch } as JSON").action(