@rt-tools/agent-kit 0.38.0 → 0.39.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.
Files changed (59) hide show
  1. package/assets/checks/check-turn-map.mjs +4 -4
  2. package/assets/checks/decision-table.json +91 -24
  3. package/assets/checks/flow-data.mjs +22 -23
  4. package/assets/checks/flow-forecast.mjs +12 -8
  5. package/assets/checks/flow-guard.mjs +365 -163
  6. package/assets/checks/flow-step.mjs +188 -58
  7. package/assets/checks/flow-verdict.mjs +124 -9
  8. package/assets/checks/record-count.mjs +27 -0
  9. package/assets/checks/task-flow-script.mjs +33 -7
  10. package/assets/checks/work-result.mjs +92 -11
  11. package/assets/commands/night.md +3 -3
  12. package/assets/defaults/turn-map.md +4 -2
  13. package/assets/docs/GLOSSARY.md +1 -1
  14. package/assets/hooks/ask-judge.md +4 -2
  15. package/assets/hooks/facts.sh +66 -0
  16. package/assets/hooks/git-guard-delivery-epic.sh +2 -2
  17. package/assets/hooks/git-guard-delivery-rerun.sh +17 -5
  18. package/assets/hooks/git-guard-push-ahead.sh +24 -2
  19. package/assets/hooks/git-guard-push-marks.sh +209 -12
  20. package/assets/hooks/git-guard-push-tests.sh +29 -2
  21. package/assets/hooks/pre-push.sh +26 -2
  22. package/assets/hooks/push-ahead-call-guard.sh +447 -0
  23. package/assets/hooks/push-set.sh +31 -8
  24. package/assets/hooks/turn-exit-guard.sh +1 -1
  25. package/assets/hooks/turn-judge.md +16 -6
  26. package/assets/patterns/doc-style-human.md +36 -76
  27. package/assets/pitfalls/doc-style-human.md +112 -0
  28. package/assets/pitfalls/epic-flow.md +92 -0
  29. package/assets/pitfalls/mockups.needs-mockups.md +87 -0
  30. package/assets/pitfalls/observability.needs-app.md +186 -0
  31. package/assets/pitfalls/platform-access.md +94 -0
  32. package/assets/pitfalls/queue-audit.github.md +78 -0
  33. package/assets/pitfalls/task-flow-archive.md +2 -1
  34. package/assets/pitfalls/task-flow-close.2.md +2 -1
  35. package/assets/pitfalls/task-flow-owner.md +29 -0
  36. package/assets/pitfalls/task-flow-resume.md +2 -2
  37. package/assets/pitfalls/task-flow-start.md +1 -1
  38. package/assets/pitfalls/turn-conduct.md +1 -1
  39. package/assets/rules/autonomous-work.md +1 -1
  40. package/assets/rules/epic-flow.md +24 -63
  41. package/assets/rules/mockups.needs-mockups.md +25 -64
  42. package/assets/rules/observability.needs-app.md +43 -172
  43. package/assets/rules/platform-access.md +28 -75
  44. package/assets/rules/queue-audit.github.md +25 -52
  45. package/assets/rules/task-flow-owner.md +6 -6
  46. package/assets/rules/turn-conduct.md +22 -19
  47. package/assets/task-flow/flow.js +10 -14
  48. package/assets/task-flow/flow.md +7 -8
  49. package/assets/task-flow/measure/ci.mjs +184 -0
  50. package/assets/task-flow/measure/owner.mjs +13 -6
  51. package/assets/task-flow/measure/session.mjs +92 -15
  52. package/assets/task-flow/source/git.mjs +179 -11
  53. package/assets/task-flow/source/host.mjs +105 -0
  54. package/assets/task-flow/source/owner.mjs +33 -13
  55. package/assets/task-flow/source/session.mjs +47 -10
  56. package/lib/agent-checks.d.ts.map +1 -1
  57. package/lib/agent-checks.js +14 -2
  58. package/lib/agent-checks.js.map +1 -1
  59. package/package.json +1 -1
@@ -36,17 +36,21 @@
36
36
  outsideEpic: { git: source.git, host: source.host, tree: source.tree },
37
37
  outOfScenario: { git: source.git, host: source.host, tree: source.tree },
38
38
  },
39
- owner: { saidStop: { owner: source.owner }, nudged: { owner: source.owner } },
39
+ owner: { interrupted: { owner: source.owner }, nudged: { owner: source.owner } },
40
40
  session: {
41
41
  wrote: { session: source.session },
42
42
  role: { session: source.session },
43
43
  menuLost: { session: source.session },
44
44
  forbidden: { session: source.session },
45
- idle: { session: source.session },
45
+ idle: { session: source.session, tree: source.tree },
46
46
  unread: { session: source.session },
47
- waiting: { session: source.session },
47
+ waiting: { session: source.session, tree: source.tree },
48
+ hung: { session: source.session, tree: source.tree },
48
49
  },
49
50
  host: { silent: { host: source.host } },
51
+ // Read by the verdict before the release cases: a CI run nobody watches or a red run nobody read
52
+ // holds the stop, the end of the scenario included.
53
+ ci: { hold: { git: source.git, host: source.host, tree: source.tree, session: source.session, owner: source.owner } },
50
54
  },
51
55
 
52
56
  state: {
@@ -137,7 +141,8 @@
137
141
  order: 1,
138
142
  log: 'the end of the scenario',
139
143
  },
140
- stopWord: { when: measure.owner.saidStop, order: 2, log: 'a stop word of the owner' },
144
+ // No typed word stops the work; Esc does, and the turns a notice wakes after it are released.
145
+ interrupted: { when: measure.owner.interrupted, order: 2, log: 'the owner interrupted the turn' },
141
146
  // The state «работа-отдана» sends work to the background by its own action and goes on: there
142
147
  // the wait releases nothing.
143
148
  background: {
@@ -161,21 +166,12 @@
161
166
  },
162
167
 
163
168
  words: {
164
- stop: [
165
- 'стоп', 'стой', 'хватит', 'остановись', 'прекрати', 'не сейчас', 'подожди', 'погоди', 'жди',
166
- 'пауза', 'отбой', 'на сегодня всё', 'stop', 'wait', 'not now', 'pause',
167
- ],
168
- stopExcept: [
169
- 'продолжай', 'делай', 'работай', 'доделывай', 'иди дальше', 'делай дальше', 'сначала', 'спрашивать',
170
- 'спрашивай', 'asking', 'keep going', 'go on',
171
- ],
172
- holdAfter: ['стоять', 'останавлива', 'ждать'],
173
169
  nudge: '(?<![\\p{L}])(?<!не )(продолжай|доделывай|работай|делай дальше|работаешь)(?![\\p{L}])|почему (ты )?(стоишь|встал|остановил)|что дальше|дальше\\?|^(ну )?(и )?что там|^ну и\\s*[?!.]|какого .*останов',
174
170
  write: [
175
171
  'git commit', 'git push', 'git add', 'git merge', 'git rm', 'git mv', 'sed -i', 'perl -pi', 'gh pr', 'npm run task:new', 'pnpm run task:new', 'npm run task:move',
176
172
  'pnpm run task:move', 'npm run agent-kit:sync', 'pnpm run agent-kit:sync',
177
173
  ],
178
- menu: ['отложить RT-N', 'стоп'],
174
+ menu: ['отложить RT-N', 'подскажу путь'],
179
175
  legacyBranches: ['RT-3276-conversation-checks', 'RT-3329-task-flow-scenario'],
180
176
  },
181
177
 
@@ -29,7 +29,7 @@ The engine asks the cases in this order, and a met case lets the turn end before
29
29
  | Order | Case | When | Log |
30
30
  | --- | --- | --- | --- |
31
31
  | 1 | `scenarioEnd` | `any(measure.epic.finished, all(measure.copy.outsideEpic, measure.pr.handed))` | the end of the scenario |
32
- | 2 | `stopWord` | `measure.owner.saidStop` | a stop word of the owner |
32
+ | 2 | `interrupted` | `measure.owner.interrupted` | the owner interrupted the turn |
33
33
  | 3 | `background` | `all(measure.session.waiting, not(measure.pr.handed))` | a background task of the session runs |
34
34
  | 4 | `noWrite` | `any(measure.copy.outOfScenario, all(not(measure.session.wrote), not(measure.owner.nudged)))` | no write to the tree, or a branch outside the scenario |
35
35
  | 5 | `role` | `measure.session.role` | a role session |
@@ -55,16 +55,18 @@ The engine asks the cases in this order, and a met case lets the turn end before
55
55
  | `measure.pr.handed` | `source.git`, `source.host` |
56
56
  | `measure.copy.outsideEpic` | `source.git`, `source.host`, `source.tree` |
57
57
  | `measure.copy.outOfScenario` | `source.git`, `source.host`, `source.tree` |
58
- | `measure.owner.saidStop` | `source.owner` |
58
+ | `measure.owner.interrupted` | `source.owner` |
59
59
  | `measure.owner.nudged` | `source.owner` |
60
60
  | `measure.session.wrote` | `source.session` |
61
61
  | `measure.session.role` | `source.session` |
62
62
  | `measure.session.menuLost` | `source.session` |
63
63
  | `measure.session.forbidden` | `source.session` |
64
- | `measure.session.idle` | `source.session` |
64
+ | `measure.session.idle` | `source.session`, `source.tree` |
65
65
  | `measure.session.unread` | `source.session` |
66
- | `measure.session.waiting` | `source.session` |
66
+ | `measure.session.waiting` | `source.session`, `source.tree` |
67
+ | `measure.session.hung` | `source.session`, `source.tree` |
67
68
  | `measure.host.silent` | `source.host` |
69
+ | `measure.ci.hold` | `source.git`, `source.host`, `source.tree`, `source.session`, `source.owner` |
68
70
 
69
71
  ## Sources
70
72
 
@@ -83,12 +85,9 @@ The engine asks the cases in this order, and a met case lets the turn end before
83
85
 
84
86
  | Key | Words |
85
87
  | --- | --- |
86
- | `stop` | стоп, стой, хватит, остановись, прекрати, не сейчас, подожди, погоди, жди, пауза, отбой, на сегодня всё, stop, wait, not now, pause |
87
- | `stopExcept` | продолжай, делай, работай, доделывай, иди дальше, делай дальше, сначала, спрашивать, спрашивай, asking, keep going, go on |
88
- | `holdAfter` | стоять, останавлива, ждать |
89
88
  | `nudge` | `(?<![\p{L}])(?<!не )(продолжай\|доделывай\|работай\|делай дальше\|работаешь)(?![\p{L}])\|почему (ты )?(стоишь\|встал\|остановил)\|что дальше\|дальше\?\|^(ну )?(и )?что там\|^ну и\s*[?!.]\|какого .*останов` |
90
89
  | `write` | git commit, git push, git add, git merge, git rm, git mv, sed -i, perl -pi, gh pr, npm run task:new, pnpm run task:new, npm run task:move, pnpm run task:move, npm run agent-kit:sync, pnpm run agent-kit:sync |
91
- | `menu` | отложить RT-N, стоп |
90
+ | `menu` | отложить RT-N, подскажу путь |
92
91
  | `legacyBranches` | RT-3276-conversation-checks, RT-3329-task-flow-scenario |
93
92
 
94
93
  ## Expected forms
@@ -0,0 +1,184 @@
1
+ /**
2
+ * The measurer «measure.ci» — the CI runs the session answers for. The hold is read before the
3
+ * release cases: a turn does not end over a run nobody watches or a red run nobody read.
4
+ *
5
+ * The PRs judged are the open ones whose branch is the current one, the epic branch of the work, or
6
+ * a branch the session pushed in this record — by `git push`, or named by `--head` of `gh pr create`.
7
+ * A task merged into the epic branch moves the head of the epic's PR without any call of the
8
+ * session, so the epic branch is judged too. Only bases the pipeline wakes for are judged: a PR into
9
+ * another base never gets a run, and waiting for one is a dead end.
10
+ *
11
+ * A run on the head of such a PR holds the stop when:
12
+ * - it is running, and no background task of the session that has not ended names its number,
13
+ * the PR number or the head sha — the watch;
14
+ * - it ended red, and no unrefused call after its end names its number or reads the output of a
15
+ * watch of it — the read; a watch call stands before the end and reads nothing;
16
+ * - there is no run yet, and the head was pushed or the PR opened less than `FRESH_MINUTES` ago.
17
+ *
18
+ * No typed word of the owner passes the hold: a running run asks for one background watch, whose
19
+ * notice wakes the session when the run ends, and a red run holds until one call reads it. The
20
+ * owner's Esc does: after it a notice does not put the work back on until the owner writes again.
21
+ */
22
+ import { epicOfWork } from './epic-of.mjs';
23
+ import { interrupted } from './owner.mjs';
24
+
25
+ /** How long a head without a run holds the stop, in minutes: the hosting shows a run within seconds. */
26
+ export const FRESH_MINUTES = 2;
27
+
28
+ /** The conclusions that are no red: the run passed, or did not need to run. */
29
+ const NOT_RED = new Set(['success', 'skipped', 'neutral']);
30
+
31
+ /** A number or a sha as a whole word of a text: «3472» is not found inside «44884034720». */
32
+ const names = (text, value) =>
33
+ value !== null && value !== undefined && value !== '' && new RegExp(`(?<![\\w./-])${String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w-])`).test(text);
34
+
35
+ /** The text of a call that may name a run: its command, or its whole input. */
36
+ const callText = (event) => (typeof event.input?.command === 'string' ? event.input.command : JSON.stringify(event.input ?? {}));
37
+
38
+ /** The arguments of a command tail, with its redirections cut off: `> /tmp/push.log` names no branch. */
39
+ const argsOf = (tail) =>
40
+ tail
41
+ .replace(/\d*&?>>?\s*\S+/g, ' ')
42
+ .trim()
43
+ .split(/\s+/)
44
+ .filter((arg) => arg && !arg.startsWith('-') && !/[<>]/.test(arg));
45
+
46
+ /**
47
+ * A command as the shell splits it into words: a substitution `$(…)` or `\`…\`` is one word, a line
48
+ * continued by a backslash is one line, and a quoted text with a space or a separator in it is one
49
+ * word. The branch of `git push "https://…$(cat t)@…" X` and of `git -c h='!f() { …; }; f' push o X`
50
+ * is X.
51
+ */
52
+ const QUOTED_WORD = (quoted) => (/[\s;&|]/.test(quoted) ? 'QUOTED' : quoted);
53
+ const flat = (command) => {
54
+ let text = command.replace(/\\\n/g, ' ').replace(/'[^']*'/g, QUOTED_WORD).replace(/`[^`]*`/g, 'SUB');
55
+ for (let before = ''; before !== text; ) [before, text] = [text, text.replace(/\$\([^()]*\)/g, 'SUB')];
56
+ return text.replace(/"[^"]*"/g, QUOTED_WORD);
57
+ };
58
+
59
+ /** An argument without its quotes: `"RT-1-a"` names RT-1-a. */
60
+ const unquote = (arg) => arg.replace(/^(['"])(.*)\1$/, '$2');
61
+
62
+ /** The tail of a command up to its end: `;`, a pipe, `&&` or a lone `&`, not the `&` of `2>&1`. */
63
+ const TAIL = String.raw`((?:[^;&|\n]|>&|&>)*)`;
64
+
65
+ /**
66
+ * The branches the session pushed: { head: the time of the last push }. The time is the result of
67
+ * the call: a push runs the push set for minutes, and the hosting shows the run only after it.
68
+ */
69
+ export function pushedHeads(events) {
70
+ const heads = new Map();
71
+ const put = (head, at) => {
72
+ if (!head || head.includes('$')) return;
73
+ heads.set(head, Math.max(heads.get(head) ?? -Infinity, Number.isFinite(at) ? at : -Infinity));
74
+ };
75
+ // A push sent to the background ends with the notice of its task, not with the result of its call.
76
+ const ended = new Map(events.filter((e) => e.kind === 'backgroundEnd' && e.id).map((e) => [e.id, e.at]));
77
+ for (const event of events) {
78
+ if (event.kind !== 'call' || event.blocked || event.failed || event.name !== 'Bash') continue;
79
+ const command = flat(event.input?.command ?? '');
80
+ const at = event.input?.run_in_background ? ended.get(event.id) : Number.isFinite(event.doneAt) ? event.doneAt : event.at;
81
+ // `git checkout -b X && git push origin HEAD` pushes X, not the branch the call started on.
82
+ const switched = (index) => [...command.slice(0, index).matchAll(/\bgit\s+(?:checkout\s+-[bB]|switch\s+-[cC])\s+(\S+)/g)].pop()?.[1] ?? event.branch;
83
+ const own = (ref, index) => (!ref || ref === 'HEAD' ? switched(index) : ref);
84
+ for (const match of command.matchAll(new RegExp(String.raw`\bgit\s+(?:-[Cc]\s+\S+\s+)*push\b${TAIL}`, 'g'))) {
85
+ const refspecs = argsOf(match[1]).map(unquote).slice(1);
86
+ if (refspecs.length === 0) put(switched(match.index), at);
87
+ for (const refspec of refspecs) put(own(refspec.replace(/^\+/, '').split(':').pop().replace(/^refs\/heads\//, ''), match.index), at);
88
+ }
89
+ for (const match of command.matchAll(new RegExp(String.raw`\bgh\s+pr\s+(?:create|new)\b${TAIL}`, 'g'))) {
90
+ // `--head owner:branch` names the branch of a fork: the PR list names it without the owner.
91
+ put(own(/(?:--head|-H)[=\s]+['"]?([^\s'"]+)/.exec(match[1])?.[1]?.replace(/^[^:]+:/, ''), match.index), at);
92
+ }
93
+ }
94
+ return heads;
95
+ }
96
+
97
+ /** The background tasks of the session that started and have not ended: [{ command, output }]. */
98
+ function openTasks(events) {
99
+ const open = new Map();
100
+ for (const event of events) {
101
+ if (event.kind === 'background') open.set(event.id, event);
102
+ else if (event.kind === 'backgroundEnd') {
103
+ if (event.id) open.delete(event.id);
104
+ else for (const [id, task] of open) if (event.task && task.task === event.task) open.delete(id);
105
+ }
106
+ }
107
+ return [...open.values()];
108
+ }
109
+
110
+ /**
111
+ * A background task watches the run: its command calls the hosting client and names the run, the PR
112
+ * or the head. A log file named after the PR is no watch.
113
+ */
114
+ const watches = (task, run, pr) =>
115
+ typeof task.command === 'string' &&
116
+ /\bgh\b[\s\S]*\bwatch\b/.test(task.command) &&
117
+ (names(task.command, run?.id) ||
118
+ names(task.command, pr.number) ||
119
+ names(task.command, pr.head) ||
120
+ (pr.headRefOid && task.command.includes(pr.headRefOid.slice(0, 7))));
121
+
122
+ /**
123
+ * A command after the end of the run that a hook did not refuse and that did not fail names it, or a
124
+ * read of the output of a watch of it. An edit of a text that names the run reads nothing.
125
+ */
126
+ function wasRead(events, run, pr) {
127
+ const outputs = new Set(events.filter((e) => e.kind === 'background' && e.output && watches(e, run, pr)).map((e) => e.output));
128
+ return events.some(
129
+ (event) =>
130
+ event.kind === 'call' &&
131
+ !event.blocked &&
132
+ !event.failed &&
133
+ Number.isFinite(event.at) &&
134
+ event.at > run.endedAt &&
135
+ ((event.name === 'Bash' && /\bgh\b/.test(callText(event)) && names(callText(event), run.id)) ||
136
+ (event.name === 'Bash' && [...outputs].some((output) => callText(event).includes(output))) ||
137
+ (event.name === 'Read' && outputs.has(event.input?.file_path))),
138
+ );
139
+ }
140
+
141
+ /** A base the pipeline wakes for: a name of the list, or a mask with `*`. */
142
+ const wakes = (bases, base) =>
143
+ bases === null || bases.some((name) => (name.includes('*') ? new RegExp(`^${name.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*+/g, '.*')}$`).test(base) : name === base));
144
+
145
+ /**
146
+ * The hold: { kind: 'running' | 'red' | 'fresh', pr, run, file }, or false. `pr` — { number, head,
147
+ * headRefOid, base }; `run` — { id, attempt, conclusion, endedAt }, null for a fresh head; `file` —
148
+ * the pipeline file.
149
+ */
150
+ export function hold({ git, host, tree, session, owner }) {
151
+ return (data) => {
152
+ if (owner && interrupted({ owner })(data)) return false;
153
+ const events = session.events();
154
+ const pushes = pushedHeads(events);
155
+ const heads = new Set(pushes.keys());
156
+ const branch = git.branch();
157
+ if (branch) heads.add(branch);
158
+ let epic = null;
159
+ try {
160
+ epic = epicOfWork({ git, host, tree })?.branch ?? null;
161
+ } catch (error) {
162
+ if (error?.name !== 'HostSilent') throw error;
163
+ }
164
+ if (epic) heads.add(epic);
165
+ const { bases, file } = host.pipeline();
166
+ if (Array.isArray(bases) && bases.length === 0) return false;
167
+ const pulls = host.openPulls().filter((p) => heads.has(p.head) && wakes(bases, p.base));
168
+ if (pulls.length === 0) return false;
169
+ const now = typeof session.now === 'function' ? session.now() : Date.now();
170
+ const tasks = openTasks(events);
171
+ for (const pr of pulls) {
172
+ const runs = host.runs(pr.headRefOid);
173
+ const red = runs.find((run) => run.status === 'completed' && !NOT_RED.has(run.conclusion) && !wasRead(events, run, pr));
174
+ if (red) return { kind: 'red', pr, run: red, file };
175
+ const running = runs.find((run) => run.status !== 'completed');
176
+ if (running && !tasks.some((task) => watches(task, running, pr))) return { kind: 'running', pr, run: running, file };
177
+ if (runs.length === 0) {
178
+ const since = Math.max(pushes.get(pr.head) ?? -Infinity, Number.isFinite(pr.createdAt) ? pr.createdAt : -Infinity);
179
+ if (now - since < FRESH_MINUTES * 60_000 && !tasks.some((task) => watches(task, null, pr))) return { kind: 'fresh', pr, run: null, file };
180
+ }
181
+ }
182
+ return false;
183
+ };
184
+ }
@@ -1,12 +1,19 @@
1
1
  /**
2
- * The measurer «measure.owner» — what the owner's last word says about the turn: a stop, or a push
3
- * to go on.
2
+ * The measurer «measure.owner» — what the owner's last word says about the turn: an interrupt, or a
3
+ * push to go on. No typed word stops the work: the owner stops it by Esc.
4
4
  */
5
- /** The owner's last word begins with a stop word of `words.stop`, and nothing after it holds the turn. */
6
- export function saidStop({ owner }) {
7
- return ({ words, rules }) => {
5
+
6
+ /** The mark the host writes into the record when the owner presses Esc. */
7
+ const INTERRUPT = /^\[Request interrupted by user/;
8
+
9
+ /**
10
+ * The owner's last word is the interrupt mark of Esc: a turn a background notice wakes after it is
11
+ * released until the owner writes again.
12
+ */
13
+ export function interrupted({ owner }) {
14
+ return () => {
8
15
  const last = owner.last();
9
- return last !== null && rules.saysStop(last, words);
16
+ return last !== null && INTERRUPT.test(last.trim());
10
17
  };
11
18
  }
12
19
 
@@ -47,22 +47,32 @@ export function menuLost({ session }) {
47
47
  };
48
48
  }
49
49
 
50
+ /** The hook of the engine itself, the one that holds a turn by the scenario. */
51
+ const ENGINE_HOOK = 'turn-exit-guard';
52
+
50
53
  /**
51
54
  * Another check forbids the step: the last two refusals of calls come from the same guard for the
52
55
  * same reason, and no call wrote to the tree after the first of them. Answers the name of the guard,
53
56
  * or false — the exit check then names the owner's menu about that guard.
54
57
  */
55
58
  /**
56
- * The last of the refusals of a stop, the calls and the menus is a refusal of a stop: the move it
57
- * named was not taken. While a background task of the session runs the stop is a wait, not an idle
58
- * one: the executor has a move, and it is to wait.
59
+ * The refusals of a stop stand after the last call and menu: the move they named was not taken. The
60
+ * stop is idle when one of them is the engine's own, or names no hook: true. When every one of them
61
+ * is another hook's, the stop is no idle one: { foreign: [<their hooks, each once>] }. While a
62
+ * background task of the session runs the stop is a wait, not an idle one: the executor has a move,
63
+ * and it is to wait.
59
64
  */
60
- export function idle({ session }) {
65
+ export function idle({ session, tree }) {
61
66
  return () => {
62
67
  const events = session.events();
63
- let last = null;
64
- for (const event of events) if (event.kind === 'refusal' || event.kind === 'call' || event.kind === 'menu') last = event;
65
- return last?.kind === 'refusal' && running(events, timeOf(session)).tasks.length === 0 && unreadOf(events) === null;
68
+ let refusals = [];
69
+ for (const event of events) {
70
+ if (event.kind === 'call' || event.kind === 'menu') refusals = [];
71
+ else if (event.kind === 'refusal') refusals.push(event);
72
+ }
73
+ if (refusals.length === 0 || running(events, timeOf(session), scriptsOf(tree)).tasks.length > 0 || unreadOf(events) !== null) return false;
74
+ if (refusals.some((refusal) => !refusal.by || refusal.by === ENGINE_HOOK)) return true;
75
+ return { foreign: [...new Set(refusals.map((refusal) => refusal.by))] };
66
76
  };
67
77
  }
68
78
 
@@ -99,16 +109,65 @@ export function unread({ session }) {
99
109
  return () => unreadOf(session.events()) ?? false;
100
110
  }
101
111
 
102
- /** A background task older than this releases nothing and counts as no task, in minutes. */
103
- export const BACKGROUND_BOUND = 20;
112
+ /**
113
+ * The command of a server started in the background: a stand, a showcase, a dev server. It never
114
+ * ends by itself and sends no notice, so it is no wait. A package script `serve`, `serve:*`,
115
+ * `storybook` or `storybook:*`; `storybook dev`; the serve target of nx or ng; a stand's `up.mjs`.
116
+ * A build, a lint or a search that only names the showcase is no server.
117
+ */
118
+ const SERVER =
119
+ /\b(?:pnpm|npm|yarn)\s+(?:run\s+)?(?:serve|storybook)(?::[\w-]+)?(?![\w:-])|\bstorybook\s+dev\b|\b(?:nx|ng)\s+serve\b|\bnx\s+run\s+[\w@./-]+:serve\b|\bnx\s+run-many\b[^|;&]*?(?:-t|--targets?)[=\s]+serve\b|\bstand\/up\.mjs\b/;
120
+
121
+ /** A server at the start of a part of a command: a search that only names one is no server. */
122
+ const SERVER_AT_START = new RegExp(`^(?:(?:npx|pnpm\\s+exec|pnpm\\s+dlx)\\s+|node\\s+\\S*?)?(?:${SERVER.source})`);
123
+
124
+ /** The package script a server command runs: `serve:db` of `pnpm run serve:db`. */
125
+ const SCRIPT = /\b(?:pnpm|npm|yarn)\s+(?:run\s+)?((?:serve|storybook)(?::[\w-]+)?)(?![\w:-])/;
126
+
127
+ /** A script body that starts containers detached and ends by itself: `docker compose up -d`. */
128
+ const DETACHED = /\bup\b[^|;&]*?\s(?:-d|--detach)\b/;
129
+
130
+ /** A command of nothing but pauses and prints: `sleep 120; echo done`. It waits for nothing. */
131
+ const PAUSE = /^(?:sleep\s+[\d.]+[smhd]?|echo\b[^;&|]*|true|:)$/;
132
+
133
+ /**
134
+ * A background command that is no wait: a server, which never ends by itself, or a bare pause. A
135
+ * package script whose body in `scripts` starts its containers detached ends by itself and is a
136
+ * wait like any other command.
137
+ */
138
+ function noWait(command, scripts) {
139
+ const parts = command.split(/;|&&|\|\||(?<!&)&(?!&)/).map((part) => part.trim()).filter(Boolean);
140
+ if (parts.length > 0 && parts.every((part) => PAUSE.test(part))) return true;
141
+ // The command runs as long as its last part: a stand raised before a test run ends with the run.
142
+ const last = (parts.at(-1) ?? '').split('|')[0].trim().replace(/^(?:[A-Z_][A-Z0-9_]*=\S*\s+)+/, '');
143
+ if (!SERVER_AT_START.test(last)) return false;
144
+ const body = scripts?.[SCRIPT.exec(last)?.[1]];
145
+ return !(typeof body === 'string' && DETACHED.test(body));
146
+ }
147
+
148
+ /** The `scripts` of the package file at the tree root, or null. */
149
+ function scriptsOf(tree) {
150
+ try {
151
+ return JSON.parse(tree?.read?.('package.json') ?? 'null')?.scripts ?? null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+
157
+ /**
158
+ * A background task older than this releases nothing: it is hung, in minutes. The longest command of
159
+ * the records of 14–22.11 ran 58 minutes; 3 of 810 tasks, all agents, ran longer than 90.
160
+ */
161
+ export const BACKGROUND_BOUND = 90;
104
162
 
105
163
  const timeOf = (session) => (typeof session.now === 'function' ? session.now() : Date.now());
106
164
 
107
165
  /**
108
166
  * The background tasks of the session that have a start, no end, and are younger than the bound at
109
- * `now`, and how many of the open tasks have released their stop: { tasks, spent }.
167
+ * `now`, the ones older than it, and how many of the open tasks have released their stop:
168
+ * { tasks, hung, spent }. A watch of a CI run counts like any other task.
110
169
  */
111
- function running(events, now) {
170
+ function running(events, now, scripts = null) {
112
171
  const open = new Map();
113
172
  // The calls whose end stands in the record before their start: a command that finished at once.
114
173
  const over = new Set();
@@ -121,6 +180,8 @@ function running(events, now) {
121
180
  return true;
122
181
  };
123
182
  for (const event of events) {
183
+ // A server never ends by itself, and a pause waits for nothing: no wait, and no hung task.
184
+ if (event.kind === 'background' && noWait(event.command ?? '', scripts)) continue;
124
185
  if (event.kind === 'background') {
125
186
  if (!over.has(event.id)) open.set(event.id, event);
126
187
  } else if (event.kind === 'backgroundEnd') {
@@ -134,8 +195,24 @@ function running(events, now) {
134
195
  }
135
196
  // A start stamped ahead of the clock by more than a minute is no start to wait for.
136
197
  const age = (task) => now - task.at;
137
- const tasks = [...open.values()].filter((task) => Number.isFinite(task.at) && age(task) < BACKGROUND_BOUND * 60_000 && age(task) > -60_000);
138
- return { tasks, spent };
198
+ const timed = [...open.values()].filter((task) => Number.isFinite(task.at) && age(task) > -60_000);
199
+ const tasks = timed.filter((task) => age(task) < BACKGROUND_BOUND * 60_000);
200
+ // An agent that handed its report back while its own background work ran ends with no notice
201
+ // the record reads: past the bound it counts as no task, never as a hung one.
202
+ const hung = timed.filter((task) => !task.agent && age(task) >= BACKGROUND_BOUND * 60_000).map((task) => ({ task: task.task ?? task.id, minutes: Math.floor(age(task) / 60_000), output: task.output ?? null }));
203
+ return { tasks, hung, spent };
204
+ }
205
+
206
+ /**
207
+ * The measurer «measure.session.hung»: the oldest background task of the session that runs past the
208
+ * bound with no notice, { task, minutes, output }, or false. The hold names it, and the move is to
209
+ * read its output and stop or restart it, not to wait.
210
+ */
211
+ export function hung({ session, tree }) {
212
+ return () => {
213
+ const { hung: over } = running(session.events(), timeOf(session), scriptsOf(tree));
214
+ return over.sort((a, b) => b.minutes - a.minutes)[0] ?? false;
215
+ };
139
216
  }
140
217
 
141
218
  /**
@@ -143,9 +220,9 @@ function running(events, now) {
143
220
  * no call since. One task releases one stop — a chain of waits does not keep a turn released, and
144
221
  * two tasks release two stops: the notice of the first wakes the session while the second runs.
145
222
  */
146
- export function waiting({ session }) {
223
+ export function waiting({ session, tree }) {
147
224
  return () => {
148
- const { tasks, spent } = running(session.events(), timeOf(session));
225
+ const { tasks, spent } = running(session.events(), timeOf(session), scriptsOf(tree));
149
226
  return tasks.length > spent;
150
227
  };
151
228
  }