@alterset/alterspec-client 0.5.0 → 0.8.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/README.md CHANGED
@@ -28,6 +28,11 @@ reference.
28
28
  another's design is built in that channel's track.
29
29
  - **Checklist**: a task's items, such as acceptance criteria (`CAP-CAT-001-AC-03`), screen actions (`SCR-PRC-01.A02`)
30
30
  and experience states (`UX-SCR-PRC-01-WEB#error`). Progress counts the items your commits cover.
31
+ - **Then and Shown**: a criterion's `Then` is what the system guarantees (the backend's), its `Shown` what the screen
32
+ shows (a UI track's). A task's checklist holds a criterion for its own part only; one without `Shown` is all the
33
+ backend's.
34
+ - **Feedback**: when a task's checklist is covered, the agent tells the dispatcher what in the spec was unclear, what
35
+ it had to open beyond the brief and what it decided itself, naming IDs, so the product side can fix the spec.
31
36
 
32
37
  ## Set up a repository
33
38
 
@@ -93,10 +98,14 @@ You talk to Claude Code; the skills call the dispatcher and the CLI for you.
93
98
  them; type `/alterspec-task-context <task>` wherever you work on each. It creates no branch or worktree; where you
94
99
  work is yours to choose (`worktree <task>` makes one when you want it).
95
100
  2. **Build from the brief.** `/alterspec-task-context [task]` reads the task's brief from the export:
96
- - the checklist, with the items the dispatcher already holds covered;
101
+ - the checklist, with the items the dispatcher already holds covered and what changed in each;
97
102
  - why the change was made;
98
103
  - the before and after of each object;
99
- - for `BE`: the acceptance criteria, rules, events and operations;
104
+ - for `BE`: the changed acceptance criteria on the checklist and the operations, whole; the rules and events the
105
+ checklist's criteria or the change's text name, whole; the others the capabilities name, as paths;
106
+ - for `BE`: the entities the capabilities work with, as paths;
107
+ - the decisions and glossary terms the change's text names, whole; the other decisions its objects name, as
108
+ paths;
100
109
  - for a UI track: the screens, their experience contracts, the mockup pages and the design system.
101
110
 
102
111
  You build it in your own technology. When the spec is silent or disagrees with the code, Claude asks you; it does
@@ -3,7 +3,7 @@
3
3
  The CLI is `npx @alterset/alterspec-client`. Below it is written as `alterspec-client`; always run it as
4
4
  `npx @alterset/alterspec-client ...` from the repository (or the task's worktree). The dispatcher's tools come from
5
5
  the MCP server `dispatcher` that `.mcp.json` starts: `whoami`, `next_task`, `list_tasks`, `list_changes`, `task`,
6
- `touch`, `set_eta`, `done`, `release`. Progress reaches the dispatcher through `alterspec-client progress`, never by
6
+ `touch`, `set_eta`, `feedback` (when the dispatcher lists it), `done`, `release`. Progress reaches the dispatcher through `alterspec-client progress`, never by
7
7
  calling its tool yourself. Never call `force_release` or `mark_done`: they are an administrator's, in the
8
8
  dispatcher's pages.
9
9
 
@@ -22,6 +22,11 @@ dispatcher's pages.
22
22
  says how to build it, which is this repository's business. Cite IDs when you refer to it. The clone is read-only:
23
23
  never edit, commit or switch branches in it; `alterspec-client` pulls it.
24
24
  - **The CLI does the deterministic work**: which commit to send, the task's brief and checklist, the items its commits cover, the commit that brought it in. Never work these out yourself.
25
+ - **Feedback is how the spec gets better.** Once per task, when its checklist is covered, call `feedback` with three
26
+ short lists, each line naming the spec IDs it is about: `unclear` (what the spec left open or said in two ways),
27
+ `opened` (what you had to read beyond the brief, and why), `decided` (what you decided yourself that the spec
28
+ should have). No code and no copied spec text; empty lists are fine, an invented complaint is not. Skip it when
29
+ the dispatcher has no `feedback` tool.
25
30
  - **Progress and ETA are the dispatcher's arithmetic.** Never compute a percentage or a date yourself, and never
26
31
  guess one: say what the dispatcher answered. The developer's own date is theirs to set, with
27
32
  `/alterspec-task-eta`.
@@ -67,6 +72,9 @@ Alterspec-Covers: CAP-CAT-001-AC-03, CAP-CAT-002
67
72
  checklist writes them (`alterspec-client context <task>` lists them). Never an item whose tests don't pass yet,
68
73
  never one the checklist lacks, never "all". An item named once stays covered; don't name it again. A commit that
69
74
  covers nothing has no `Alterspec-Covers` line.
75
+ - A criterion's `Then` is what the system guarantees, its `Shown` what the screen shows. Build and test only your
76
+ track's part: `Then` on the backend, `Shown` on a UI track. The brief says when the other part is another task's;
77
+ don't build it here, and name the criterion in `Alterspec-Covers` once your part's tests pass.
70
78
 
71
79
  A hook reports the covered items to the dispatcher after each commit, by itself; when it asks, the developer runs
72
80
  `alterspec-client progress`. The task is done when its work is in the track's main branch.
@@ -10,7 +10,11 @@ or whose `Alterspec-Task` trailer the last commit carries; when that doesn't set
10
10
  2. Run `alterspec-client context <task>` and read the brief. It opens with the task's checklist: its items, what
11
11
  each is and which the dispatcher holds covered already; that is the work, and its progress. Then why the change
12
12
  was made, what changed, the delta of each of the task's objects (before and after) and where each is in the export
13
- now; for the backend the acceptance criteria, rules, events and operations the capabilities name; for a UI track
13
+ now; for the backend the changed criteria on the checklist, the operations, and the rules and events those
14
+ criteria or the change's text name, whole, and the capabilities' other criteria, rules and events by their shard
15
+ paths only, to open when one bears on the work, and its entities by path; the decisions and glossary terms the
16
+ change's text names, whole, the other decisions by path. Each hunk of a diff names the section it falls in. For a
17
+ UI track
14
18
  the screens, their experience contracts, the mockup pages and the channel's design system.
15
19
  3. Call `touch` with the task, then `task` with it. `followed_by` lists the later tasks on this track whose objects
16
20
  overlap this one's; say them in one line, e.g. "CHG-015/BE, after yours, changes some of the same objects; it will
@@ -22,7 +26,12 @@ or whose `Alterspec-Task` trailer the last commit carries; when that doesn't set
22
26
  the developer's. A mockup page is the agreed look and behaviour of a screen, a working example to follow, not code
23
27
  to copy. When the spec and the code disagree, or the spec is silent, ask the developer; never fill a gap with an
24
28
  invented business rule.
25
- 6. Work through the checklist. For each item, make its tests pass, then commit with the trailers of `_shared.md`:
26
- `Alterspec-Task: <task>` always, `Alterspec-Covers` with the items whose tests pass on that commit. The hook
27
- reports them. When the work is merged into the main branch, the developer types `/alterspec-task-done <task>`;
28
- never report it done yourself.
29
+ 6. Work through the checklist. A criterion item is your track's part of it (`Then` on the backend, `Shown` on a UI
30
+ track); leave the part the brief gives to another task. A contract state item comes with its mockup link
31
+ (`…/SCR-….html?state=<state>`): open that page in that state to see what you build (sign in as one of the
32
+ screen's roles on the channel's `index.html` first; the session stays). For each item, make its
33
+ tests pass, then commit with the trailers of `_shared.md`: `Alterspec-Task: <task>` always, `Alterspec-Covers`
34
+ with the items whose tests pass on that commit. The hook reports them. When the work is merged into the main
35
+ branch, the developer types `/alterspec-task-done <task>`; never report it done yourself.
36
+ 7. When every checklist item is covered, send your `feedback` once, as `_shared.md` says, while you still remember
37
+ what the work cost; then tell the developer the task is ready for `/alterspec-task-done <task>` once it is merged.
@@ -11,5 +11,7 @@ Without a task, ask for it; never guess it.
11
11
  3. Run `alterspec-client merged <task>`. It prints the commit on the track's main branch that brought the task in,
12
12
  or fails when the work isn't there yet: then say so (merge the task's branch, or push the commits carrying the
13
13
  trailer, first) and stop. Never report a task done whose work isn't on the main branch.
14
- 4. Call `done` with the task and that commit.
15
- 5. Say the result in one line. `NOT_IN_BRANCH`, `NOT_YOURS`, `NOT_IN_PROGRESS`: say the dispatcher's sentence.
14
+ 4. If this conversation built the task and sent no `feedback` for it yet, send it now, as `_shared.md` says (skip
15
+ when the dispatcher has no `feedback` tool, or when you didn't build it here: never invent one).
16
+ 5. Call `done` with the task and that commit.
17
+ 6. Say the result in one line. `NOT_IN_BRANCH`, `NOT_YOURS`, `NOT_IN_PROGRESS`: say the dispatcher's sentence.
@@ -17,6 +17,13 @@ You connect to it with the **alterspec client** (`@alterset/alterspec-client`, p
17
17
  - A task's **checklist** lists what it must deliver: acceptance criteria (`CAP-CAT-001-AC-03`), screen actions
18
18
  (`SCR-PRC-01.A02`), experience states (`UX-SCR-PRC-01-WEB#error`). Progress counts the items your commits cover;
19
19
  nobody types percentages.
20
+ - An acceptance criterion may have two outcomes: **Then**, what the system guarantees, and **Shown**, what the
21
+ person sees on the screen. The backend builds and tests the Then, a UI track the Shown, and each task's checklist
22
+ holds the criterion only for its own part; the brief shows you yours and says when the other part is another
23
+ task's. A criterion without Shown is all the backend's.
24
+ - When the checklist is covered, Claude sends the dispatcher short **feedback** on the task: what in the spec was
25
+ unclear, what it had to read beyond the brief, what it decided itself. The product side reads it to fix the spec;
26
+ it is never a grade of your work.
20
27
  - When you take a task it is yours until you report it **done** or **release** it; nobody else can.
21
28
  - A task is **done** when its work is merged into the track's main branch on the remote.
22
29
 
@@ -162,7 +169,7 @@ server. Then talk to it in plain words; the skills do the rest.
162
169
  | You say or type | What happens |
163
170
  | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
164
171
  | "give me work" / `/alterspec-task-next` | takes the next available task on your track and shows the brief; it creates no branch or worktree, you work wherever you like |
165
- | "let's work on my task" / `/alterspec-task-context` | the task's brief from the spec: why, the checklist, the objects it changes (before and after), rules, acceptance criteria; for a UI track also the screens, their contracts, mockups and design system |
172
+ | "let's work on my task" / `/alterspec-task-context` | the task's brief from the spec: why, the checklist, the objects it changes (before and after), the changed acceptance criteria, the rules, events, decisions and glossary terms they and the change name (the rest, and the entities, as paths); for a UI track also the screens, their contracts, mockups and design system |
166
173
  | "what am I on?" / `/alterspec-task-status` | your tasks with progress and ETA, what's available on your tracks, what is blocked and by what |
167
174
  | "what does RULE-… say?" / `/alterspec-spec-ask` | answers about the product from the spec, citing IDs; reads only |
168
175
  | `/alterspec-task-done CHG-023/BE` | after your branch is merged: reports the task done with the commit that brought it in; refused while the work isn't merged |
package/dist/cli.js CHANGED
@@ -715,12 +715,87 @@ function unifiedDiff(a, b, context = 3) {
715
715
  return out.join("\n");
716
716
  }
717
717
 
718
+ // ../src/lib/comments.ts
719
+ var blankComments = (text) => text.replace(/<!--[\s\S]*?-->/g, (c) => c.replace(/[^\n]/g, " "));
720
+
721
+ // ../src/spec/criteria.ts
722
+ var PART = /^\s*[-*]?\s*\*\*(Given|When|Then|Shown|And|Covers):?\*\*/i;
723
+ function criterionParts(chunk) {
724
+ const system = [];
725
+ const shown = [];
726
+ let label;
727
+ let inShown = false;
728
+ let hasThen = false;
729
+ for (const raw of blankComments(chunk).split("\n")) {
730
+ const line = raw.trimEnd();
731
+ if (!line.trim() || /^### /.test(line)) continue;
732
+ const m = PART.exec(line);
733
+ if (m && !line.slice(m[0].length).replace(/^:/, "").trim()) continue;
734
+ if (m) {
735
+ label = m[1].toLowerCase();
736
+ if (label === "shown") inShown = true;
737
+ else if (label !== "and") inShown = false;
738
+ if (label === "then") hasThen = true;
739
+ }
740
+ const text = line.trim();
741
+ if (inShown) shown.push(text);
742
+ else {
743
+ system.push(text);
744
+ if (label === "given" || label === "when" || label === "and" && !hasThen) shown.push(text);
745
+ }
746
+ }
747
+ const hasShown = shown.some((l) => PART.exec(l)?.[1]?.toLowerCase() === "shown");
748
+ return {
749
+ system: hasShown && !hasThen ? "" : system.join("\n"),
750
+ shown: hasShown ? shown.join("\n") : "",
751
+ hasThen,
752
+ hasShown
753
+ };
754
+ }
755
+
718
756
  // src/context.ts
719
757
  var ContextError = class extends Error {
720
758
  };
721
759
  var shardText = (x, path) => path ? x.read(path)?.replace(/^<!-- source: [^\n]*-->\n\n/, "").trim() : void 0;
722
760
  var sectionText = (x, path) => shardText(x, path)?.replace(/^## [^\n]*\n*/, "");
723
761
  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);
762
+ var forDiff = (key, text) => key.startsWith("file:") ? 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, "");
763
+ function withSections(diff, before, after) {
764
+ const where = (text, line) => {
765
+ const lines2 = text.split("\n");
766
+ if (lines2[0] === "---") {
767
+ const end = lines2.indexOf("---", 1);
768
+ if (end > 0 && line - 1 <= end) return "front-matter";
769
+ }
770
+ let sub;
771
+ for (let i = Math.min(line, lines2.length) - 1; i >= 0; i--) {
772
+ const l = lines2[i];
773
+ if (sub === void 0 && /^### /.test(l)) sub = l.slice(4).split(/\s/)[0];
774
+ if (/^## /.test(l)) return sub ? `${l} \u203A ${sub}` : l;
775
+ }
776
+ return void 0;
777
+ };
778
+ const lines = diff.split("\n");
779
+ return lines.map((header, i) => {
780
+ const m = /^@@ -(\d+),\d+ \+(\d+),\d+ @@$/.exec(header);
781
+ if (!m) return header;
782
+ let k = i + 1;
783
+ while (lines[k]?.startsWith(" ")) k++;
784
+ const skipped = k - i - 1;
785
+ const name = lines[k]?.startsWith("+") ? where(after, Number(m[2]) + skipped) : where(before, Number(m[1]) + skipped);
786
+ return name ? `${header} ${name}` : header;
787
+ }).join("\n");
788
+ }
789
+ var BOOKKEEPING = /^(reviewed|page|dry|status|version|signed_off|base):/;
790
+ function firstAdded(key, entry) {
791
+ const added = (a, b) => diffLines(a, b).filter((l) => l.op === "+").map(
792
+ (l) => l.text.replace(/^\s*(?:[-*]|#+|\d+\.)\s+/, "").replace(/\*\*/g, "").trim()
793
+ ).find((t) => t && !/^(---|```)/.test(t) && !BOOKKEEPING.test(t));
794
+ const before = forDiff(key, entry.before);
795
+ const after = forDiff(key, entry.after);
796
+ const line = added(splitFrontMatter(before).body, splitFrontMatter(after).body) ?? added(splitFrontMatter(before).raw ?? "", splitFrontMatter(after).raw ?? "");
797
+ return line && line.length > 200 ? `${line.slice(0, 199)}\u2026` : line;
798
+ }
724
799
  function objectBrief(x, key, entry, why) {
725
800
  const file = x.fileOf(key);
726
801
  const held = file !== void 0 && x.has(file);
@@ -731,8 +806,11 @@ function objectBrief(x, key, entry, why) {
731
806
  brief.change = exportChange(entry);
732
807
  if (entry.status) brief.status = entry.status;
733
808
  if (entry.before !== void 0 || entry.after !== void 0) {
734
- const d = unifiedDiff(entry.before ?? "", entry.after ?? "");
735
- if (d) brief.diff = d;
809
+ const d = unifiedDiff(forDiff(key, entry.before), forDiff(key, entry.after));
810
+ if (d)
811
+ brief.diff = key.startsWith("file:") ? d : withSections(d, forDiff(key, entry.before), forDiff(key, entry.after));
812
+ else if (unifiedDiff(entry.before ?? "", entry.after ?? ""))
813
+ brief.diff = "Only its version, its fingerprints or the template\u2019s comments changed: nothing to build.";
736
814
  } else if (entry.binary) {
737
815
  brief.diff = `binary: ${[entry.binary.before, entry.binary.after].map((b) => b ? `${b.size} bytes` : "\u2014").join(" \u2192 ")}`;
738
816
  }
@@ -765,22 +843,26 @@ var named = (x, id) => {
765
843
  const title = titleOf(x, id);
766
844
  return title ? `${id} ${title}` : `${id} (not in the export now)`;
767
845
  };
768
- function criterionOf(x, cap, id) {
846
+ function criterionOf(x, cap, id, track) {
769
847
  const file = x.fileOf(cap);
770
848
  const text = file && x.has(file) ? sectionText(x, x.sectionShard(file, "Acceptance criteria")) : void 0;
771
849
  const chunk = text?.split(/^### /m).find((c) => c.split(/\s/)[0] === id);
772
850
  if (!chunk) return void 0;
773
- const lines = chunk.split("\n").slice(1).map(
851
+ const parts = criterionParts(chunk.split("\n").slice(1).join("\n"));
852
+ const ui = track !== void 0 && track !== BACKEND;
853
+ const lines = (ui ? parts.shown : parts.system).split("\n").map(
774
854
  (l) => l.replace(/^\s*[-*]\s*/, "").replace(/\*\*/g, "").trim()
775
855
  ).filter(Boolean);
776
- const then = lines.findIndex((l) => /^Then\b/.test(l));
777
- const kept = (then >= 0 ? lines.slice(then) : lines).filter((l) => !/^Covers:/.test(l));
778
- return kept.join(" ") || void 0;
856
+ const from = lines.findIndex((l) => (ui ? /^Shown\b/ : /^Then\b/).test(l));
857
+ const kept = (from >= 0 ? lines.slice(from) : lines).filter((l) => !/^Covers:/.test(l));
858
+ const note = ui ? parts.hasThen ? " (what the system guarantees is the BE task\u2019s)" : "" : parts.hasShown ? " (what the screen shows is the UI task\u2019s)" : "";
859
+ return kept.length ? `${kept.join(" ")}${note}` : void 0;
779
860
  }
780
- function itemWhat(x, item) {
861
+ var BACKEND = "BE";
862
+ function itemWhat(x, item, entry, track) {
781
863
  const ac = /^((CAP-[A-Z]{2,6}-\d{3})-AC-\d{2})$/.exec(item);
782
864
  if (ac) {
783
- const then = criterionOf(x, ac[2], ac[1]);
865
+ const then = criterionOf(x, ac[2], ac[1], track);
784
866
  return `acceptance criterion of ${named(x, ac[2])}${then ? `: ${then}` : ""}`;
785
867
  }
786
868
  const action = /^(SCR-[A-Z]{2,6}-\d{2})\.(A\d{2})$/.exec(item);
@@ -788,25 +870,32 @@ function itemWhat(x, item) {
788
870
  const [, scr, a] = action;
789
871
  const file = x.fileOf(scr);
790
872
  const actions = file && x.has(file) ? sectionText(x, x.sectionShard(file, "Actions")) : void 0;
791
- const line = actions?.split("\n").map((l) => l.replace(/^\s*[-*]\s*/, "").trim()).find((l) => l.startsWith(`${a} `));
792
- const label = line?.slice(a.length).trim();
873
+ const line2 = actions?.split("\n").map((l) => l.replace(/^\s*[-*]\s*/, "").trim()).find((l) => l.startsWith(`${a} `));
874
+ const label = line2?.slice(a.length).trim();
793
875
  return `action ${a}${label ? ` "${label.replace(/\s*→\s*/, '" \u2192 ')}` : ""}${label && !label.includes("\u2192") ? '"' : ""} on ${named(x, scr)}`;
794
876
  }
795
- const state = /^(UX-(SCR-[A-Z]{2,6}-\d{2})-[A-Z]{2,5})#(.+)$/.exec(item);
877
+ const state = /^(UX-(SCR-[A-Z]{2,6}-\d{2})-([A-Z]{2,5}))#(.+)$/.exec(item);
796
878
  if (state) {
797
- const [, ux, scr, id] = state;
879
+ const [, ux, scr, code, id] = state;
798
880
  const rule = /^rule-(.+)$/.exec(id)?.[1];
799
- return `state "${id}" of ${ux} (${named(x, scr)})${rule ? `: the message of RULE-${rule.toUpperCase()}` : ""}`;
881
+ const page = mockupPath(code, scr);
882
+ const open = x.has(page) ? `; open \`${page}?state=${encodeURIComponent(id)}\`` : "";
883
+ return `state "${id}" of ${ux} (${named(x, scr)})${rule ? `: the message of RULE-${rule.toUpperCase()}` : ""}${open}`;
800
884
  }
801
885
  if (item.startsWith("file:")) {
802
886
  const path = item.slice(5);
803
887
  const page = /\/mockups\/(SCR-[A-Z]{2,6}-\d{2})\.html$/.exec(path)?.[1];
804
- const what = page ? `the mockup page of ${page}` : /\/design-system\.md$/.test(path) ? "the channel\u2019s design system" : /\/patterns\.md$/.test(path) ? "the channel\u2019s patterns" : "a file of the channel\u2019s experience";
805
- return `${what}: \`${path}\`${x.has(path) ? "" : " (not in the export now)"}`;
888
+ const what2 = page ? `the mockup page of ${page}` : /\/design-system\.md$/.test(path) ? "the channel\u2019s design system" : /\/patterns\.md$/.test(path) ? "the channel\u2019s patterns" : "a file of the channel\u2019s experience";
889
+ return `${what2}: \`${path}\`${x.has(path) ? "" : " (not in the export now)"}`;
806
890
  }
807
891
  if (item.startsWith("term:")) return `glossary term "${item.slice(5)}"`;
808
892
  const kind = idKind(item);
809
- return `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ""}${named(x, item)}`;
893
+ const what = `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ""}${named(x, item)}`;
894
+ if (!entry) return what;
895
+ const change = exportChange(entry);
896
+ if (change !== "modified") return `${what}, ${change}`;
897
+ const line = firstAdded(item, entry);
898
+ return line ? `${what}, modified: "${line}"` : `${what}, modified (see its delta)`;
810
899
  }
811
900
  function taskContext(x, task, exportDir2, state = {}) {
812
901
  const change = x.work.changes.find((c) => c.id === task.change);
@@ -829,7 +918,11 @@ function taskContext(x, task, exportDir2, state = {}) {
829
918
  checklist: {
830
919
  items: items.map((item) => {
831
920
  const covered = state.covered?.get(item);
832
- return { item, what: itemWhat(x, item), ...covered ? { covered } : {} };
921
+ return {
922
+ item,
923
+ what: itemWhat(x, item, entries.get(item), task.track),
924
+ ...covered ? { covered } : {}
925
+ };
833
926
  }),
834
927
  known: state.covered !== void 0,
835
928
  ...state.unknown ? { note: state.unknown } : {}
@@ -853,32 +946,95 @@ function taskContext(x, task, exportDir2, state = {}) {
853
946
  ...delta ? { delta: proposal.replace(/proposal\.md$/, "delta.md") } : {},
854
947
  objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key)))
855
948
  };
949
+ const added = work.objects.flatMap((key) => {
950
+ const e = entries.get(key);
951
+ return e ? diffLines(forDiff(key, e.before), forDiff(key, e.after)).filter((l) => l.op === "+") : [];
952
+ }).map((l) => l.text);
953
+ const written = [ctx.proposal.why ?? "", ctx.proposal.what ?? "", ...added];
954
+ const changed = new Set(work.objects);
955
+ const isNew = (id) => changed.has(id) && !entries.get(id)?.exported.before;
956
+ const piece = (id, bears) => {
957
+ const file = x.fileOf(id);
958
+ const path = file && x.itemShard(file, id);
959
+ if (!path) return [];
960
+ const title = titleOf(x, id);
961
+ const text = bears && !isNew(id) ? sectionText(x, path) : void 0;
962
+ return [
963
+ {
964
+ id,
965
+ path,
966
+ ...title ? { title } : {},
967
+ ...text ? { text } : {},
968
+ ...changed.has(id) ? { changed: true } : {}
969
+ }
970
+ ];
971
+ };
972
+ const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)));
973
+ const onList = items && new Set(items);
974
+ ctx.acceptance = capabilities.flatMap((id) => {
975
+ const path = x.sectionShard(x.fileOf(id), "Acceptance criteria");
976
+ if (!path) return [];
977
+ const chunks = (sectionText(x, path) ?? "").split(/^(?=### )/m).filter((c) => c.startsWith("### "));
978
+ const existed = new Set([...(entries.get(id)?.before ?? "").matchAll(/^### (\S+)/gm)].map((m) => m[1]));
979
+ const idOf2 = (c) => c.slice(4).split(/\s/)[0];
980
+ const listed = onList ? chunks.filter((c) => onList.has(idOf2(c))) : chunks;
981
+ written.push(...listed);
982
+ const kept = onList ? listed.filter((c) => existed.has(idOf2(c))) : chunks;
983
+ const added2 = listed.length - kept.length;
984
+ const title = titleOf(x, id);
985
+ const rest = [
986
+ added2 ? `${added2 === 1 ? "One new criterion is" : `${added2} new criteria are`} whole in its delta above.` : "",
987
+ chunks.length > listed.length ? `Its other criteria: \`${path}\`.` : ""
988
+ ].filter(Boolean).join(" ");
989
+ return [
990
+ {
991
+ id,
992
+ path,
993
+ ...title ? { title } : {},
994
+ ...kept.length ? { text: kept.join("").trim() } : {},
995
+ ...kept.length && rest ? { rest } : {}
996
+ }
997
+ ];
998
+ });
999
+ if (!ctx.acceptance.length) delete ctx.acceptance;
856
1000
  if (track.kind === "backend") {
857
- const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)));
858
- const named2 = (kind) => [
1001
+ const named3 = (kind) => [
859
1002
  .../* @__PURE__ */ new Set([
860
1003
  ...work.objects.filter((k) => idsIn(k, [kind]).length === 1 && idsIn(k, [kind])[0] === k),
861
1004
  ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c))), [kind]))
862
1005
  ])
863
1006
  ];
864
- const items2 = (ids) => ids.flatMap((id) => {
1007
+ const carried = (kind) => {
1008
+ const bearing2 = idsIn(written.join("\n"), [kind]);
1009
+ return [.../* @__PURE__ */ new Set([...named3(kind), ...bearing2])].flatMap((id) => piece(id, bearing2.includes(id)));
1010
+ };
1011
+ ctx.rules = carried("rule");
1012
+ ctx.events = carried("event");
1013
+ ctx.entities = [
1014
+ .../* @__PURE__ */ new Set([
1015
+ ...work.objects.filter((k) => idKind(k) === "entity"),
1016
+ ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c))), ["entity"]))
1017
+ ])
1018
+ ].flatMap((id) => {
865
1019
  const file = x.fileOf(id);
866
- const path = file && x.itemShard(file, id);
867
- return path ? [{ id, path, text: shardText(x, path) }] : [];
868
- });
869
- ctx.acceptance = capabilities.flatMap((id) => {
870
- const path = x.sectionShard(x.fileOf(id), "Acceptance criteria");
871
- return path ? [{ id, path, text: sectionText(x, path) }] : [];
1020
+ if (!file || !x.has(file)) return [];
1021
+ const title = titleOf(x, id);
1022
+ return [{ id, path: file, ...title ? { title } : {}, ...changed.has(id) ? { changed: true } : {} }];
872
1023
  });
873
- ctx.rules = items2(named2("rule"));
874
- ctx.events = items2(named2("event"));
875
1024
  ctx.operations = x.has(OPERATIONS_FILE) ? capabilities.flatMap((id) => {
876
1025
  const path = x.shards(OPERATIONS_FILE).find((p) => new RegExp(`/\\d{2}-${slug(id)}(-|\\.md$)`).test(p));
877
1026
  return path ? [{ id, path, text: shardText(x, path) }] : [];
878
1027
  }) : [];
879
1028
  } else {
880
1029
  const existing = (p) => x.has(p) ? p : void 0;
881
- const screens = [...new Set(work.objects.map(screenOf).filter((s) => !!s))];
1030
+ const performing = [...x.sources.keys()].filter(
1031
+ (id) => /^SCR-/.test(id) && x.has(contractPath(id, track.code)) && idsIn(frontMatterOf(x.read(x.fileOf(id)) ?? ""), ["capability"]).some(
1032
+ (c) => capabilities.includes(c)
1033
+ )
1034
+ );
1035
+ const screens = [
1036
+ .../* @__PURE__ */ new Set([...work.objects.map(screenOf).filter((s) => !!s), ...performing])
1037
+ ];
882
1038
  ctx.screens = screens.map((id) => ({
883
1039
  id,
884
1040
  file: x.fileOf(id),
@@ -890,6 +1046,19 @@ function taskContext(x, task, exportDir2, state = {}) {
890
1046
  patterns: existing(patternsPath(track.code))
891
1047
  };
892
1048
  }
1049
+ const bearing = idsIn(written.join("\n"), ["decision"]);
1050
+ const named2 = idsIn(work.objects.map((k) => entries.get(k)?.after ?? "").join("\n"), ["decision"]);
1051
+ ctx.decisions = [.../* @__PURE__ */ new Set([...bearing, ...named2])].flatMap((id) => piece(id, bearing.includes(id)));
1052
+ const glossary = x.fileOf("term:");
1053
+ const writtenText = written.join("\n");
1054
+ ctx.terms = (glossary && x.has(glossary) ? x.shards(glossary) : []).filter((path) => !/\/\d{2}-[^/]*$/.test(path)).flatMap((path) => {
1055
+ const name = /^## (.+)$/m.exec(shardText(x, path) ?? "")?.[1]?.trim();
1056
+ if (!name || changed.has(`term:${name}`)) return [];
1057
+ const term = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1058
+ if (!new RegExp(`(?<![\\w-])${term}(?:s|es)?(?![\\w-])`, "i").test(writtenText)) return [];
1059
+ const text = sectionText(x, path);
1060
+ return [{ id: name, path, ...text ? { text } : {} }];
1061
+ });
893
1062
  return ctx;
894
1063
  }
895
1064
  var fence = (text, lang = "") => {
@@ -931,19 +1100,55 @@ function renderContext(c) {
931
1100
  const status = o.status && o.status.before !== o.status.after ? `, ${o.status.before ?? "\u2014"} \u2192 ${o.status.after ?? "\u2014"}` : "";
932
1101
  out.push(`### ${o.key}`, "", `${o.change ?? "no delta entry"}${status}; ${where}.`);
933
1102
  if (o.unrecoverable) out.push("", `The delta could not recover it: ${o.unrecoverable}.`);
934
- if (o.diff) out.push("", o.diff.startsWith("binary:") ? o.diff : fence(o.diff, "diff"));
1103
+ if (o.diff) out.push("", o.diff.startsWith("@@") ? fence(o.diff, "diff") : o.diff);
935
1104
  out.push("");
936
1105
  }
937
- const pieces = (title, list2) => {
1106
+ const pieces = (title, list2, intro) => {
938
1107
  if (!list2?.length) return;
939
1108
  out.push(`## ${title}`, "");
940
- for (const p of list2) out.push(`### ${p.id} (\`${p.path}\`)`, "", p.text ?? "", "");
1109
+ if (intro) out.push(intro, "");
1110
+ for (const p of list2.filter((p2) => p2.text))
1111
+ out.push(
1112
+ `### ${p.id}${p.title ? ` ${p.title}` : ""} (\`${p.path}\`)`,
1113
+ "",
1114
+ p.text,
1115
+ ...p.rest ? ["", p.rest] : [],
1116
+ ""
1117
+ );
1118
+ for (const p of list2.filter((p2) => !p2.text))
1119
+ out.push(
1120
+ `- ${p.id}${p.title ? ` ${p.title}` : ""}: \`${p.path}\`${p.changed ? " (this task changes it: its delta is above)" : ""}`
1121
+ );
1122
+ out.push("");
941
1123
  };
942
- pieces("Acceptance criteria", c.acceptance);
943
- pieces("Rules", c.rules);
944
- pieces("Events", c.events);
1124
+ pieces(
1125
+ "Acceptance criteria",
1126
+ c.acceptance,
1127
+ c.checklist ? "The changed criteria on the checklist, whole (new ones are whole in the delta above); the rest by shard." : void 0
1128
+ );
1129
+ pieces(
1130
+ "Rules",
1131
+ c.rules,
1132
+ "The rules the checklist\u2019s criteria or the change\u2019s text name, whole; the others the capabilities name, by path."
1133
+ );
1134
+ pieces(
1135
+ "Events",
1136
+ c.events,
1137
+ "The events the checklist\u2019s criteria or the change\u2019s text name, whole; the others the capabilities name, by path."
1138
+ );
1139
+ pieces(
1140
+ "Entities",
1141
+ c.entities,
1142
+ "The entities the task\u2019s capabilities work with; open one for its attributes, states and transitions."
1143
+ );
945
1144
  pieces("Operations for other systems", c.operations);
946
- if (c.screens) {
1145
+ pieces(
1146
+ "Decisions",
1147
+ c.decisions,
1148
+ "The decisions the change\u2019s text names, whole; the others its objects name, by path."
1149
+ );
1150
+ pieces("Terms", c.terms, "The glossary terms the change\u2019s text uses.");
1151
+ if (c.screens?.length) {
947
1152
  out.push("## Screens", "");
948
1153
  for (const s of c.screens) {
949
1154
  out.push(`- **${s.id}**: \`${s.file ?? "not in the export"}\``);
@@ -961,6 +1166,19 @@ function renderContext(c) {
961
1166
  }
962
1167
  return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
963
1168
  }
1169
+ function contextStats(markdown) {
1170
+ const sections = markdown.split(/^(?=## )/m).map((part, i) => ({
1171
+ name: i === 0 ? "(heading)" : part.split("\n")[0].slice(3),
1172
+ chars: part.length
1173
+ }));
1174
+ const width = Math.max(...sections.map((x) => x.name.length), "Total".length);
1175
+ const row = (name, chars) => `${name.padEnd(width)} ${String(Math.ceil(chars / 4)).padStart(7)} ${String(chars).padStart(8)}`;
1176
+ return [
1177
+ `${"Section".padEnd(width)} ${"~tokens".padStart(7)} ${"chars".padStart(8)}`,
1178
+ ...sections.map((x) => row(x.name, x.chars)),
1179
+ row("Total", markdown.length)
1180
+ ].join("\n") + "\n";
1181
+ }
964
1182
 
965
1183
  // src/git.ts
966
1184
  import { execFileSync as execFileSync3 } from "child_process";
@@ -1782,14 +2000,16 @@ program.command("export-head").description("pull the export clone and print its
1782
2000
  process.stdout.write(JSON.stringify(head, null, 2) + "\n");
1783
2001
  })
1784
2002
  );
1785
- 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(
2003
+ 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(
1786
2004
  run(async (id, opts) => {
1787
2005
  const loaded = loadConfig();
1788
2006
  const dir = exportDir(loaded);
1789
2007
  const x = readExport(dir);
1790
2008
  const task = parseTask(id);
1791
2009
  const ctx = taskContext(x, task, dir, await coveredState(loaded, task));
1792
- process.stdout.write(opts.json ? JSON.stringify(ctx, null, 2) + "\n" : renderContext(ctx));
2010
+ process.stdout.write(
2011
+ opts.stats ? contextStats(renderContext(ctx)) : opts.json ? JSON.stringify(ctx, null, 2) + "\n" : renderContext(ctx)
2012
+ );
1793
2013
  })
1794
2014
  );
1795
2015
  program.command("progress").description("report the items the task\u2019s commits cover to the dispatcher").argument(