@alterset/alterspec-client 0.4.5 → 0.6.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
@@ -89,14 +89,18 @@ instructions, wherever you keep them.
89
89
  You talk to Claude Code; the skills call the dispatcher and the CLI for you.
90
90
 
91
91
  1. **Take work.** `/alterspec-task-next`, or just "give me the next task". Name a track or ask for several at once:
92
- `/alterspec-task-next BE 2`. With one task, the client makes its branch `task/<chg>-<track>` in this checkout and
93
- continues with the brief. With several, it makes a worktree for each. Start a Claude Code session in each folder
94
- and type `/alterspec-task-context <task>` there.
92
+ `/alterspec-task-next BE 2`. It only assigns: with one task it continues with the brief, with several it lists
93
+ them; type `/alterspec-task-context <task>` wherever you work on each. It creates no branch or worktree; where you
94
+ work is yours to choose (`worktree <task>` makes one when you want it).
95
95
  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;
96
+ - the checklist, with the items the dispatcher already holds covered and what changed in each;
97
97
  - why the change was made;
98
98
  - the before and after of each object;
99
- - for `BE`: the acceptance criteria, rules, events and operations;
99
+ - for `BE`: the changed acceptance criteria on the checklist and the operations, whole; the rules and events the
100
+ checklist's criteria or the change's text name, whole; the others the capabilities name, as paths;
101
+ - for `BE`: the entities the capabilities work with, as paths;
102
+ - the decisions and glossary terms the change's text names, whole; the other decisions its objects name, as
103
+ paths;
100
104
  - for a UI track: the screens, their experience contracts, the mockup pages and the design system.
101
105
 
102
106
  You build it in your own technology. When the spec is silent or disagrees with the code, Claude asks you; it does
@@ -123,7 +127,7 @@ Other skills:
123
127
  | ----------------------------------------- | ---------------------------------------------------------------------------- |
124
128
  | `/alterspec-task-status [track]` | Your tasks with progress and ETA, what is available, what is blocked and by what, and the open changes per level. |
125
129
  | `/alterspec-task-eta <task> <YYYY-MM-DD\|clear> <reason>` | Set your own date for a task, or `clear` it so the dispatcher's computed ETA applies again. |
126
- | `/alterspec-task-release <task> [reason]` | Give a task back. Its branch and worktree stay. |
130
+ | `/alterspec-task-release <task> [reason]` | Give a task back. Your code and branches stay as they are. |
127
131
  | `/alterspec-spec-ask <question>` | Answer a question about the product from the export, citing IDs. Read-only. |
128
132
 
129
133
  You only ever type `task-done`, `task-eta` and `task-release` yourself, because each is your word. Claude starts
@@ -21,9 +21,7 @@ dispatcher's pages.
21
21
  developer's clone of it. It says what the product does in business terms and names everything by ID; it never
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
- - **The CLI does the deterministic work**: which commit to send, the task's brief and checklist, its branch and
25
- worktree, the items its commits cover, the commit that brought it in. Never work these out yourself, never pick a
26
- branch name.
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.
27
25
  - **Progress and ETA are the dispatcher's arithmetic.** Never compute a percentage or a date yourself, and never
28
26
  guess one: say what the dispatcher answered. The developer's own date is theirs to set, with
29
27
  `/alterspec-task-eta`.
@@ -36,7 +34,7 @@ dispatcher's pages.
36
34
  that follow (the public key and its fingerprint) exactly, for the developer to send to an admin. Stop.
37
35
  - There is no `whoami` tool: the `dispatcher` MCP server isn't loaded. Tell the developer to run
38
36
  `npx @alterset/alterspec-client init` here (it writes the server to `.mcp.json` and approves it in the
39
- git-ignored `.claude/settings.local.json`; in a task worktree `alterspec-client worktree` did that), or to approve
37
+ git-ignored `.claude/settings.local.json`; in a worktree `alterspec-client worktree` made, it did that), or to approve
40
38
  it with `/mcp` in an interactive `claude` terminal, and then to start a new session. Stop.
41
39
  2. Run `alterspec-client export-head --latest <latest_export.commit>` (without `--latest` while it is null). Its JSON
42
40
  has `send`, the commit to give the dispatcher as `export`, and `behind`:
@@ -55,8 +53,9 @@ dispatcher's pages.
55
53
 
56
54
  ## Commits of a task
57
55
 
58
- Work on the task's branch, which `alterspec-client worktree <task>` makes (`--here` in this checkout). Every commit
59
- of the task ends with a trailer block, after a blank line:
56
+ Work where the developer works: the client makes no branch or worktree for a task, and you make none unless the
57
+ developer asks (then `alterspec-client worktree <task>` makes the branch `task/<chg>-<track>` in a worktree of its own,
58
+ `--here` in this checkout). Every commit of the task ends with a trailer block, after a blank line:
60
59
 
61
60
  ```
62
61
  Alterspec-Task: CHG-012/BE
@@ -3,14 +3,18 @@
3
3
  Read `.alterspec-client/prompts/_shared.md` first and follow it.
4
4
 
5
5
  Arguments: `[CHG-NNN/TRACK]`. Without one, take the developer's task in progress from `whoami`'s `in_progress`; when
6
- there are several, the one whose branch this checkout is on (`git branch --show-current` prints `task/<chg>-<track>`);
7
- when that doesn't settle it, ask which.
6
+ there are several, the one whose branch this checkout is on (`git branch --show-current` prints `task/<chg>-<track>`)
7
+ or whose `Alterspec-Task` trailer the last commit carries; when that doesn't settle it, ask which.
8
8
 
9
9
  1. Start as `_shared.md` says (`whoami`, `export-head`).
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
@@ -11,11 +11,13 @@ the developer wants in progress at once (default 1).
11
11
  3. Call `next_task` with `export` = `send` from `export-head`, `tracks` and `parallel`.
12
12
  4. Say each `reasons` entry in one line (none available, blocked by what, at the limit, more after pulling).
13
13
  5. The tasks it assigned:
14
- - **One**: run `alterspec-client worktree <task> --here` (it refuses while this checkout has uncommitted work; then
15
- say so and stop), then continue with `.alterspec-client/prompts/task-context.md` for that task.
16
- - **Several**: run `alterspec-client worktree <task>` for each. List each task with its title and the `path` it
17
- printed, and say: start a Claude Code session in each folder and type `/alterspec-task-context <task>` there.
18
- Work on none of them in this session.
14
+ - **One**: continue with `.alterspec-client/prompts/task-context.md` for that task, here, on whatever branch the
15
+ developer is on.
16
+ - **Several**: list each task with its title, and say: type `/alterspec-task-context <task>` where you want to work
17
+ on it. Work on none of them in this session.
19
18
  - **None**: say so, with the reasons. Stop.
20
19
 
20
+ Taking a task assigns it, nothing more: never create a branch or a worktree, switch branches or stash anything. Where
21
+ and how the developer works on it is theirs to decide.
22
+
21
23
  Never ask for more tasks than the developer asked for.
@@ -9,4 +9,4 @@ Without a task, ask for it; never guess it.
9
9
  2. The reason is the developer's words after the task. Without one, ask once why (one line, for whoever takes it
10
10
  next); an empty answer is fine.
11
11
  3. Call `release` with the task and the reason. Say the result in one line: the task is available again.
12
- 4. Its branch and worktree stay as they are; say so, so the developer can delete them or hand them over.
12
+ 4. The developer's code, branches and commits stay as they are; touch none of them.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: alterspec-task-next
3
- description: "Use when the developer wants work from the dispatcher: \"give me work\", \"next task\", \"take two BE tasks\". Takes the next task(s) on their tracks and opens it here, or a worktree for each when several."
3
+ description: "Use when the developer wants work from the dispatcher: \"give me work\", \"next task\", \"take two BE tasks\". Takes the next task(s) on their tracks and shows the brief of one; creates no branch or worktree."
4
4
  argument-hint: "[track] [parallel]"
5
5
  allowed-tools: Read Glob Grep Bash(npx @alterset/alterspec-client *) Bash(git *) mcp__dispatcher__*
6
6
  ---
@@ -98,8 +98,6 @@ git clone <code-repo>
98
98
 
99
99
  The export is **read-only**: never edit, commit or switch branches in it. The client pulls it for you.
100
100
 
101
- Task worktrees (step 6, "Several tasks at once") are created next to your code repository, in `<code-repo>-tasks/`.
102
-
103
101
  ## Step 4: Set the client up in your code repository
104
102
 
105
103
  In the root of your code repository:
@@ -163,19 +161,20 @@ server. Then talk to it in plain words; the skills do the rest.
163
161
 
164
162
  | You say or type | What happens |
165
163
  | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
166
- | "give me work" / `/alterspec-task-next` | takes the next available task on your track, creates its branch `task/chg-023-be` from `origin/<branch>` here, and shows the brief |
167
- | "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 |
164
+ | "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), 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 |
168
166
  | "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 |
169
167
  | "what does RULE-… say?" / `/alterspec-spec-ask` | answers about the product from the spec, citing IDs; reads only |
170
168
  | `/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 |
171
- | `/alterspec-task-release CHG-023/BE <reason>` | gives the task back so someone else can take it; its branch stays |
169
+ | `/alterspec-task-release CHG-023/BE <reason>` | gives the task back so someone else can take it; your code and branches stay as they are |
172
170
  | `/alterspec-task-eta CHG-023/BE <YYYY-MM-DD> <reason>` | sets your own date when the computed ETA is wrong; `clear` instead of the date removes it |
173
171
 
174
172
  **done**, **release** and **eta** happen only when you type them; Claude never does them on its own.
175
173
 
176
174
  ### A task, start to finish
177
175
 
178
- 1. "Give me work." Claude takes a task, creates its branch and shows the brief and its checklist.
176
+ 1. "Give me work." Claude takes a task and shows the brief and its checklist. Work on it in the branch (or worktree) you
177
+ choose.
179
178
  2. Build it with Claude in your own technology. The spec says what, never how; a mockup shows the agreed look and
180
179
  behaviour, it is not code to copy. When the spec is silent or disagrees with the code, Claude asks you.
181
180
  3. Claude ends every commit of the task with a trailer:
@@ -188,20 +187,21 @@ server. Then talk to it in plain words; the skills do the rest.
188
187
  `Alterspec-Covers` names the checklist items whose tests pass with that commit, never items that aren't tested yet.
189
188
  After each commit a hook reports them in the background, and the task's progress on the dashboard moves.
190
189
 
191
- 4. Push the branch, open a pull request into the main branch as usual, get it reviewed and merged.
190
+ 4. Push your branch, open a pull request into the main branch as usual, get it reviewed and merged.
192
191
  5. Type `/alterspec-task-done CHG-023/BE`.
193
192
 
194
193
  ### Several tasks at once
195
194
 
196
- Ask for more than one: `/alterspec-task-next BE 2`. The client creates a worktree and branch for each task in
197
- `../<code-repo>-tasks/` and lists their folders. Start a separate Claude Code session in each folder and type
198
- `/alterspec-task-context <task>` there. The dispatcher never gives you two tasks on the same track that change the same
199
- objects, so the worktrees don't conflict.
195
+ Ask for more than one: `/alterspec-task-next BE 2`. Claude lists them and works on none; type
196
+ `/alterspec-task-context <task>` wherever you work on each, e.g. a session per worktree. If you want the client to
197
+ make a worktree for a task, run `npx @alterset/alterspec-client worktree CHG-023/BE`: it creates the branch
198
+ `task/chg-023-be` from `origin/<branch>` in `../<code-repo>-tasks/` (the `--worktrees` folder of `init`). The
199
+ dispatcher never gives you two tasks on the same track that change the same objects, so they don't conflict.
200
200
 
201
201
  ### Good to know
202
202
 
203
- - **Start from a clean checkout.** Taking a single task switches this checkout to its branch, which is refused while you
204
- have uncommitted changes to tracked files; commit or stash them first.
203
+ - **The trailer names the task.** Progress is read from the `Alterspec-Task` trailer of your commits, on any branch;
204
+ the hook takes the task from the last commit's trailer (or from a `task/<chg>-<track>` branch).
205
205
  - **A UI task waits for its `BE` task.** "Nothing available" on a UI track usually means the backend part isn't done
206
206
  yet; `/alterspec-task-status` says what blocks what.
207
207
  - **The scope is the spec's.** If the brief and the code disagree, or something in the spec looks wrong, ask whoever
package/dist/cli.js CHANGED
@@ -721,6 +721,43 @@ var ContextError = class extends Error {
721
721
  var shardText = (x, path) => path ? x.read(path)?.replace(/^<!-- source: [^\n]*-->\n\n/, "").trim() : void 0;
722
722
  var sectionText = (x, path) => shardText(x, path)?.replace(/^## [^\n]*\n*/, "");
723
723
  var screenOf = (key) => /^UX-(SCR-[A-Z]{2,6}-\d{2})-[A-Z]{2,5}$/.exec(key)?.[1] ?? /^file:experience\/[a-z]{2,5}\/mockups\/(SCR-[A-Z]{2,6}-\d{2})\.html$/.exec(key)?.[1] ?? (/^SCR-[A-Z]{2,6}-\d{2}$/.test(key) ? key : void 0);
724
+ 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, "");
725
+ function withSections(diff, before, after) {
726
+ const where = (text, line) => {
727
+ const lines2 = text.split("\n");
728
+ if (lines2[0] === "---") {
729
+ const end = lines2.indexOf("---", 1);
730
+ if (end > 0 && line - 1 <= end) return "front-matter";
731
+ }
732
+ let sub;
733
+ for (let i = Math.min(line, lines2.length) - 1; i >= 0; i--) {
734
+ const l = lines2[i];
735
+ if (sub === void 0 && /^### /.test(l)) sub = l.slice(4).split(/\s/)[0];
736
+ if (/^## /.test(l)) return sub ? `${l} \u203A ${sub}` : l;
737
+ }
738
+ return void 0;
739
+ };
740
+ const lines = diff.split("\n");
741
+ return lines.map((header, i) => {
742
+ const m = /^@@ -(\d+),\d+ \+(\d+),\d+ @@$/.exec(header);
743
+ if (!m) return header;
744
+ let k = i + 1;
745
+ while (lines[k]?.startsWith(" ")) k++;
746
+ const skipped = k - i - 1;
747
+ const name = lines[k]?.startsWith("+") ? where(after, Number(m[2]) + skipped) : where(before, Number(m[1]) + skipped);
748
+ return name ? `${header} ${name}` : header;
749
+ }).join("\n");
750
+ }
751
+ var BOOKKEEPING = /^(reviewed|page|dry|status|version|signed_off|base):/;
752
+ function firstAdded(key, entry) {
753
+ const added = (a, b) => diffLines(a, b).filter((l) => l.op === "+").map(
754
+ (l) => l.text.replace(/^\s*(?:[-*]|#+|\d+\.)\s+/, "").replace(/\*\*/g, "").trim()
755
+ ).find((t) => t && !/^(---|```)/.test(t) && !BOOKKEEPING.test(t));
756
+ const before = forDiff(key, entry.before);
757
+ const after = forDiff(key, entry.after);
758
+ const line = added(splitFrontMatter(before).body, splitFrontMatter(after).body) ?? added(splitFrontMatter(before).raw ?? "", splitFrontMatter(after).raw ?? "");
759
+ return line && line.length > 200 ? `${line.slice(0, 199)}\u2026` : line;
760
+ }
724
761
  function objectBrief(x, key, entry, why) {
725
762
  const file = x.fileOf(key);
726
763
  const held = file !== void 0 && x.has(file);
@@ -731,8 +768,11 @@ function objectBrief(x, key, entry, why) {
731
768
  brief.change = exportChange(entry);
732
769
  if (entry.status) brief.status = entry.status;
733
770
  if (entry.before !== void 0 || entry.after !== void 0) {
734
- const d = unifiedDiff(entry.before ?? "", entry.after ?? "");
735
- if (d) brief.diff = d;
771
+ const d = unifiedDiff(forDiff(key, entry.before), forDiff(key, entry.after));
772
+ if (d)
773
+ brief.diff = key.startsWith("file:") ? d : withSections(d, forDiff(key, entry.before), forDiff(key, entry.after));
774
+ else if (unifiedDiff(entry.before ?? "", entry.after ?? ""))
775
+ brief.diff = "Only its version, its fingerprints or the template\u2019s comments changed: nothing to build.";
736
776
  } else if (entry.binary) {
737
777
  brief.diff = `binary: ${[entry.binary.before, entry.binary.after].map((b) => b ? `${b.size} bytes` : "\u2014").join(" \u2192 ")}`;
738
778
  }
@@ -777,7 +817,7 @@ function criterionOf(x, cap, id) {
777
817
  const kept = (then >= 0 ? lines.slice(then) : lines).filter((l) => !/^Covers:/.test(l));
778
818
  return kept.join(" ") || void 0;
779
819
  }
780
- function itemWhat(x, item) {
820
+ function itemWhat(x, item, entry) {
781
821
  const ac = /^((CAP-[A-Z]{2,6}-\d{3})-AC-\d{2})$/.exec(item);
782
822
  if (ac) {
783
823
  const then = criterionOf(x, ac[2], ac[1]);
@@ -788,8 +828,8 @@ function itemWhat(x, item) {
788
828
  const [, scr, a] = action;
789
829
  const file = x.fileOf(scr);
790
830
  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();
831
+ const line2 = actions?.split("\n").map((l) => l.replace(/^\s*[-*]\s*/, "").trim()).find((l) => l.startsWith(`${a} `));
832
+ const label = line2?.slice(a.length).trim();
793
833
  return `action ${a}${label ? ` "${label.replace(/\s*→\s*/, '" \u2192 ')}` : ""}${label && !label.includes("\u2192") ? '"' : ""} on ${named(x, scr)}`;
794
834
  }
795
835
  const state = /^(UX-(SCR-[A-Z]{2,6}-\d{2})-[A-Z]{2,5})#(.+)$/.exec(item);
@@ -801,12 +841,17 @@ function itemWhat(x, item) {
801
841
  if (item.startsWith("file:")) {
802
842
  const path = item.slice(5);
803
843
  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)"}`;
844
+ 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";
845
+ return `${what2}: \`${path}\`${x.has(path) ? "" : " (not in the export now)"}`;
806
846
  }
807
847
  if (item.startsWith("term:")) return `glossary term "${item.slice(5)}"`;
808
848
  const kind = idKind(item);
809
- return `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ""}${named(x, item)}`;
849
+ const what = `${kind && KIND_WORDS[kind] ? `${KIND_WORDS[kind]} ` : ""}${named(x, item)}`;
850
+ if (!entry) return what;
851
+ const change = exportChange(entry);
852
+ if (change !== "modified") return `${what}, ${change}`;
853
+ const line = firstAdded(item, entry);
854
+ return line ? `${what}, modified: "${line}"` : `${what}, modified (see its delta)`;
810
855
  }
811
856
  function taskContext(x, task, exportDir2, state = {}) {
812
857
  const change = x.work.changes.find((c) => c.id === task.change);
@@ -829,7 +874,7 @@ function taskContext(x, task, exportDir2, state = {}) {
829
874
  checklist: {
830
875
  items: items.map((item) => {
831
876
  const covered = state.covered?.get(item);
832
- return { item, what: itemWhat(x, item), ...covered ? { covered } : {} };
877
+ return { item, what: itemWhat(x, item, entries.get(item)), ...covered ? { covered } : {} };
833
878
  }),
834
879
  known: state.covered !== void 0,
835
880
  ...state.unknown ? { note: state.unknown } : {}
@@ -853,25 +898,80 @@ function taskContext(x, task, exportDir2, state = {}) {
853
898
  ...delta ? { delta: proposal.replace(/proposal\.md$/, "delta.md") } : {},
854
899
  objects: work.objects.map((key) => objectBrief(x, key, entries.get(key), lost.get(key)))
855
900
  };
901
+ const added = work.objects.flatMap((key) => {
902
+ const e = entries.get(key);
903
+ return e ? diffLines(forDiff(key, e.before), forDiff(key, e.after)).filter((l) => l.op === "+") : [];
904
+ }).map((l) => l.text);
905
+ const written = [ctx.proposal.why ?? "", ctx.proposal.what ?? "", ...added];
906
+ const changed = new Set(work.objects);
907
+ const isNew = (id) => changed.has(id) && !entries.get(id)?.exported.before;
908
+ const piece = (id, bears) => {
909
+ const file = x.fileOf(id);
910
+ const path = file && x.itemShard(file, id);
911
+ if (!path) return [];
912
+ const title = titleOf(x, id);
913
+ const text = bears && !isNew(id) ? sectionText(x, path) : void 0;
914
+ return [
915
+ {
916
+ id,
917
+ path,
918
+ ...title ? { title } : {},
919
+ ...text ? { text } : {},
920
+ ...changed.has(id) ? { changed: true } : {}
921
+ }
922
+ ];
923
+ };
856
924
  if (track.kind === "backend") {
857
925
  const capabilities = work.objects.filter((k) => /^CAP-/.test(k) && x.fileOf(k) && x.has(x.fileOf(k)));
858
- const named2 = (kind) => [
926
+ const named3 = (kind) => [
859
927
  .../* @__PURE__ */ new Set([
860
928
  ...work.objects.filter((k) => idsIn(k, [kind]).length === 1 && idsIn(k, [kind])[0] === k),
861
929
  ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c))), [kind]))
862
930
  ])
863
931
  ];
864
- const items2 = (ids) => ids.flatMap((id) => {
865
- const file = x.fileOf(id);
866
- const path = file && x.itemShard(file, id);
867
- return path ? [{ id, path, text: shardText(x, path) }] : [];
868
- });
932
+ const onList = items && new Set(items);
869
933
  ctx.acceptance = capabilities.flatMap((id) => {
870
934
  const path = x.sectionShard(x.fileOf(id), "Acceptance criteria");
871
- return path ? [{ id, path, text: sectionText(x, path) }] : [];
935
+ if (!path) return [];
936
+ const chunks = (sectionText(x, path) ?? "").split(/^(?=### )/m).filter((c) => c.startsWith("### "));
937
+ const existed = new Set([...(entries.get(id)?.before ?? "").matchAll(/^### (\S+)/gm)].map((m) => m[1]));
938
+ const idOf2 = (c) => c.slice(4).split(/\s/)[0];
939
+ const listed = onList ? chunks.filter((c) => onList.has(idOf2(c))) : chunks;
940
+ written.push(...listed);
941
+ const kept = onList ? listed.filter((c) => existed.has(idOf2(c))) : chunks;
942
+ const added2 = listed.length - kept.length;
943
+ const title = titleOf(x, id);
944
+ const rest = [
945
+ added2 ? `${added2 === 1 ? "One new criterion is" : `${added2} new criteria are`} whole in its delta above.` : "",
946
+ chunks.length > listed.length ? `Its other criteria: \`${path}\`.` : ""
947
+ ].filter(Boolean).join(" ");
948
+ return [
949
+ {
950
+ id,
951
+ path,
952
+ ...title ? { title } : {},
953
+ ...kept.length ? { text: kept.join("").trim() } : {},
954
+ ...kept.length && rest ? { rest } : {}
955
+ }
956
+ ];
957
+ });
958
+ const carried = (kind) => {
959
+ const bearing2 = idsIn(written.join("\n"), [kind]);
960
+ return [.../* @__PURE__ */ new Set([...named3(kind), ...bearing2])].flatMap((id) => piece(id, bearing2.includes(id)));
961
+ };
962
+ ctx.rules = carried("rule");
963
+ ctx.events = carried("event");
964
+ ctx.entities = [
965
+ .../* @__PURE__ */ new Set([
966
+ ...work.objects.filter((k) => idKind(k) === "entity"),
967
+ ...capabilities.flatMap((c) => idsIn(frontMatterOf(x.read(x.fileOf(c))), ["entity"]))
968
+ ])
969
+ ].flatMap((id) => {
970
+ const file = x.fileOf(id);
971
+ if (!file || !x.has(file)) return [];
972
+ const title = titleOf(x, id);
973
+ return [{ id, path: file, ...title ? { title } : {}, ...changed.has(id) ? { changed: true } : {} }];
872
974
  });
873
- ctx.rules = items2(named2("rule"));
874
- ctx.events = items2(named2("event"));
875
975
  ctx.operations = x.has(OPERATIONS_FILE) ? capabilities.flatMap((id) => {
876
976
  const path = x.shards(OPERATIONS_FILE).find((p) => new RegExp(`/\\d{2}-${slug(id)}(-|\\.md$)`).test(p));
877
977
  return path ? [{ id, path, text: shardText(x, path) }] : [];
@@ -890,6 +990,19 @@ function taskContext(x, task, exportDir2, state = {}) {
890
990
  patterns: existing(patternsPath(track.code))
891
991
  };
892
992
  }
993
+ const bearing = idsIn(written.join("\n"), ["decision"]);
994
+ const named2 = idsIn(work.objects.map((k) => entries.get(k)?.after ?? "").join("\n"), ["decision"]);
995
+ ctx.decisions = [.../* @__PURE__ */ new Set([...bearing, ...named2])].flatMap((id) => piece(id, bearing.includes(id)));
996
+ const glossary = x.fileOf("term:");
997
+ const writtenText = written.join("\n");
998
+ ctx.terms = (glossary && x.has(glossary) ? x.shards(glossary) : []).filter((path) => !/\/\d{2}-[^/]*$/.test(path)).flatMap((path) => {
999
+ const name = /^## (.+)$/m.exec(shardText(x, path) ?? "")?.[1]?.trim();
1000
+ if (!name || changed.has(`term:${name}`)) return [];
1001
+ const term = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1002
+ if (!new RegExp(`(?<![\\w-])${term}(?:s|es)?(?![\\w-])`, "i").test(writtenText)) return [];
1003
+ const text = sectionText(x, path);
1004
+ return [{ id: name, path, ...text ? { text } : {} }];
1005
+ });
893
1006
  return ctx;
894
1007
  }
895
1008
  var fence = (text, lang = "") => {
@@ -931,18 +1044,54 @@ function renderContext(c) {
931
1044
  const status = o.status && o.status.before !== o.status.after ? `, ${o.status.before ?? "\u2014"} \u2192 ${o.status.after ?? "\u2014"}` : "";
932
1045
  out.push(`### ${o.key}`, "", `${o.change ?? "no delta entry"}${status}; ${where}.`);
933
1046
  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"));
1047
+ if (o.diff) out.push("", o.diff.startsWith("@@") ? fence(o.diff, "diff") : o.diff);
935
1048
  out.push("");
936
1049
  }
937
- const pieces = (title, list2) => {
1050
+ const pieces = (title, list2, intro) => {
938
1051
  if (!list2?.length) return;
939
1052
  out.push(`## ${title}`, "");
940
- for (const p of list2) out.push(`### ${p.id} (\`${p.path}\`)`, "", p.text ?? "", "");
1053
+ if (intro) out.push(intro, "");
1054
+ for (const p of list2.filter((p2) => p2.text))
1055
+ out.push(
1056
+ `### ${p.id}${p.title ? ` ${p.title}` : ""} (\`${p.path}\`)`,
1057
+ "",
1058
+ p.text,
1059
+ ...p.rest ? ["", p.rest] : [],
1060
+ ""
1061
+ );
1062
+ for (const p of list2.filter((p2) => !p2.text))
1063
+ out.push(
1064
+ `- ${p.id}${p.title ? ` ${p.title}` : ""}: \`${p.path}\`${p.changed ? " (this task changes it: its delta is above)" : ""}`
1065
+ );
1066
+ out.push("");
941
1067
  };
942
- pieces("Acceptance criteria", c.acceptance);
943
- pieces("Rules", c.rules);
944
- pieces("Events", c.events);
1068
+ pieces(
1069
+ "Acceptance criteria",
1070
+ c.acceptance,
1071
+ c.checklist ? "The changed criteria on the checklist, whole (new ones are whole in the delta above); the rest by shard." : void 0
1072
+ );
1073
+ pieces(
1074
+ "Rules",
1075
+ c.rules,
1076
+ "The rules the checklist\u2019s criteria or the change\u2019s text name, whole; the others the capabilities name, by path."
1077
+ );
1078
+ pieces(
1079
+ "Events",
1080
+ c.events,
1081
+ "The events the checklist\u2019s criteria or the change\u2019s text name, whole; the others the capabilities name, by path."
1082
+ );
1083
+ pieces(
1084
+ "Entities",
1085
+ c.entities,
1086
+ "The entities the task\u2019s capabilities work with; open one for its attributes, states and transitions."
1087
+ );
945
1088
  pieces("Operations for other systems", c.operations);
1089
+ pieces(
1090
+ "Decisions",
1091
+ c.decisions,
1092
+ "The decisions the change\u2019s text names, whole; the others its objects name, by path."
1093
+ );
1094
+ pieces("Terms", c.terms, "The glossary terms the change\u2019s text uses.");
946
1095
  if (c.screens) {
947
1096
  out.push("## Screens", "");
948
1097
  for (const s of c.screens) {
@@ -961,6 +1110,19 @@ function renderContext(c) {
961
1110
  }
962
1111
  return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
963
1112
  }
1113
+ function contextStats(markdown) {
1114
+ const sections = markdown.split(/^(?=## )/m).map((part, i) => ({
1115
+ name: i === 0 ? "(heading)" : part.split("\n")[0].slice(3),
1116
+ chars: part.length
1117
+ }));
1118
+ const width = Math.max(...sections.map((x) => x.name.length), "Total".length);
1119
+ const row = (name, chars) => `${name.padEnd(width)} ${String(Math.ceil(chars / 4)).padStart(7)} ${String(chars).padStart(8)}`;
1120
+ return [
1121
+ `${"Section".padEnd(width)} ${"~tokens".padStart(7)} ${"chars".padStart(8)}`,
1122
+ ...sections.map((x) => row(x.name, x.chars)),
1123
+ row("Total", markdown.length)
1124
+ ].join("\n") + "\n";
1125
+ }
964
1126
 
965
1127
  // src/git.ts
966
1128
  import { execFileSync as execFileSync3 } from "child_process";
@@ -1556,10 +1718,25 @@ import { join as join7 } from "path";
1556
1718
  var git3 = (cwd, args) => execFileSync4("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
1557
1719
  function currentTask(repo) {
1558
1720
  try {
1559
- return taskOfBranch(git3(repo, ["symbolic-ref", "--short", "HEAD"]));
1721
+ const task = taskOfBranch(git3(repo, ["symbolic-ref", "--short", "HEAD"]));
1722
+ if (task) return task;
1723
+ } catch {
1724
+ }
1725
+ try {
1726
+ const named2 = git3(repo, [
1727
+ "log",
1728
+ "-1",
1729
+ `--format=%(trailers:key=${TRAILER},valueonly,separator=%x1d)`,
1730
+ "HEAD"
1731
+ ]);
1732
+ for (const id of named2.split(""))
1733
+ try {
1734
+ return parseTask(id.trim());
1735
+ } catch {
1736
+ }
1560
1737
  } catch {
1561
- return void 0;
1562
1738
  }
1739
+ return void 0;
1563
1740
  }
1564
1741
  function coveredItems(repo, task) {
1565
1742
  const trailer = (key) => `%(trailers:key=${key},valueonly,separator=%x1d)`;
@@ -1767,17 +1944,22 @@ program.command("export-head").description("pull the export clone and print its
1767
1944
  process.stdout.write(JSON.stringify(head, null, 2) + "\n");
1768
1945
  })
1769
1946
  );
1770
- 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(
1947
+ 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(
1771
1948
  run(async (id, opts) => {
1772
1949
  const loaded = loadConfig();
1773
1950
  const dir = exportDir(loaded);
1774
1951
  const x = readExport(dir);
1775
1952
  const task = parseTask(id);
1776
1953
  const ctx = taskContext(x, task, dir, await coveredState(loaded, task));
1777
- process.stdout.write(opts.json ? JSON.stringify(ctx, null, 2) + "\n" : renderContext(ctx));
1954
+ process.stdout.write(
1955
+ opts.stats ? contextStats(renderContext(ctx)) : opts.json ? JSON.stringify(ctx, null, 2) + "\n" : renderContext(ctx)
1956
+ );
1778
1957
  })
1779
1958
  );
1780
- program.command("progress").description("report the items the task\u2019s commits cover to the dispatcher").argument("[task]", "the task, e.g. CHG-012/BE; default the one of the current branch task/<chg>-<track>").option("--hook", "as the Claude Code hook after a commit: silent, throttled, never failing").option("--json", "print the dispatcher\u2019s answer as JSON").action(async (id, opts) => {
1959
+ program.command("progress").description("report the items the task\u2019s commits cover to the dispatcher").argument(
1960
+ "[task]",
1961
+ "the task, e.g. CHG-012/BE; default the one of the branch task/<chg>-<track> or of the last commit\u2019s trailer"
1962
+ ).option("--hook", "as the Claude Code hook after a commit: silent, throttled, never failing").option("--json", "print the dispatcher\u2019s answer as JSON").action(async (id, opts) => {
1781
1963
  if (opts.hook) {
1782
1964
  setTimeout(() => process.exit(0), 3e4).unref();
1783
1965
  const repo = await hookCwd(process.stdin) ?? process.cwd();
@@ -1789,7 +1971,7 @@ program.command("progress").description("report the items the task\u2019s commit
1789
1971
  const task = id ? parseTask(id) : currentTask(repo);
1790
1972
  if (!task)
1791
1973
  throw new Error(
1792
- "This branch is no task branch (task/<chg>-<track>): name the task, e.g. `progress CHG-012/BE`."
1974
+ "Neither the branch (task/<chg>-<track>) nor the last commit\u2019s Alterspec-Task trailer names a task: name it, e.g. `progress CHG-012/BE`."
1793
1975
  );
1794
1976
  const report = await reportProgress(sessionOf(loadConfig()), task, coveredItems(repo, task));
1795
1977
  process.stdout.write(opts.json ? JSON.stringify(report, null, 2) + "\n" : progressText(report));