@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
@@ -17,9 +17,9 @@
17
17
  * says what the last measurement said.
18
18
  */
19
19
  import { spawn, spawnSync } from 'node:child_process';
20
- import { availableParallelism } from 'node:os';
20
+ import { availableParallelism, tmpdir } from 'node:os';
21
21
  import { createHash } from 'node:crypto';
22
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
22
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
23
23
 
24
24
  import { dirname, join } from 'node:path';
25
25
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -28,8 +28,9 @@ import { compareExpected, isWriteCommand } from './flow-data.mjs';
28
28
 
29
29
  // The sources of the description lie next to the engine where it is laid out, one level up in the package.
30
30
  const HERE = dirname(fileURLToPath(import.meta.url));
31
- const RECORDS = [join(HERE, 'task-flow/source/records.mjs'), join(HERE, '../task-flow/source/records.mjs')].find((path) => existsSync(path));
32
- const records = await import(pathToFileURL(RECORDS).href);
31
+ const source = (name) => [join(HERE, `task-flow/source/${name}`), join(HERE, `../task-flow/source/${name}`)].find((path) => existsSync(path));
32
+ const records = await import(pathToFileURL(source('records.mjs')).href);
33
+ const { liveRun, putBack, release, rewritePutBack } = await import(pathToFileURL(source('git.mjs')).href);
33
34
 
34
35
  /** The record directories of this repository and the test of an approval mark, shared by the checks. */
35
36
  export const openRecords = (root = process.cwd()) => records.openAt(root);
@@ -38,9 +39,41 @@ export const approvalFault = records.approvalFault;
38
39
  /** The limit of one check, in milliseconds: past it the step does not match. */
39
40
  export const STEP_LIMIT_MS = 540_000;
40
41
 
42
+ /** The budget of the rerun before a PR, in milliseconds: a second run of a group starts only within it. */
43
+ export const RERUN_BUDGET_MS = 1_500_000;
44
+
41
45
  /** The progress changes every turn and is the one file of the folder not judged against the plan. */
42
46
  const PROGRESS = 'progress.md';
43
47
 
48
+ /** A taken-apart folder put back for one run, or null; a live, broken or stray folder on disk refuses the step. */
49
+ export function restoreFolder(git, folder) {
50
+ const restored = putBack(git, folder);
51
+ if (restored?.busy) throw new StepRefused(`the task folder is put back by the live run ${restored.busy}: measure after it ends`);
52
+ if (restored?.left) throw new StepRefused(`${folder} is left by a broken step run and was edited after it: read it, remove it, then measure`);
53
+ if (restored?.stray) throw new StepRefused(`the task folder is taken apart by ${restored.removedBy.slice(0, 9)}, and ${folder} still holds ${restored.stray.join(', ')}: remove them, then measure`);
54
+ return restored;
55
+ }
56
+
57
+ /** The versions of a file in its history up to the head, or up to `removedFrom` when the head lacks it, oldest first. */
58
+ const versionsOf = (source, path) =>
59
+ (spawnSync('git', ['log', '--reverse', '--format=%H', (!source.existsAtHead(path) && source.removedFrom?.(path)) || 'HEAD', '--', path], { encoding: 'utf8' }).stdout ?? '').split('\n').filter(Boolean).map((sha) => source.versionAt(path, sha));
60
+
61
+ const doneLine = (number) => new RegExp(`^\\s*-\\s+\\[x\\]\\s+${number.replace('.', '\\.')}\\s`, 'm');
62
+
63
+ /**
64
+ * The progress as step `number` saw it: the version before the first one marking it done, with the
65
+ * replacements of `latest` (the last version has every step done). With no such version, `latest`.
66
+ */
67
+ export function progressOfStep(versions, latest, number) {
68
+ const first = versions.findIndex((text) => text !== null && doneLine(number).test(text));
69
+ const chosen = (first > 0 && versions[first - 1]) || latest;
70
+ return chosen === latest ? chosen : withReplacements(chosen, latest);
71
+ }
72
+
73
+ /** The move of a step on a taken-apart folder whose fix lies in the folder: the revert of its taking-apart. */
74
+ export const revertMove = (removedBy) =>
75
+ `fix what the step measures and measure it again; a fix that lies in the folder — a check replaced in the progress, a folder file edited after the plan — needs the folder back: \`git revert --no-edit ${removedBy}\` takes back the whole commit, the archive record too; then take the folder apart again`;
76
+
44
77
  /** A replacement of a step check in the progress. */
45
78
  const REPLACEMENT = /^-\s+\*\*(?:Проверка шага|Check of step)\s+(\d+\.\d+)\s+(?:заменена|replaced):\*\*\s+`(.+)`\s+→\s+(.+?)(?:\s+·\s+(?:слово владельца|the owner's word):\s+«.+»)?\s*$/u;
46
79
 
@@ -52,12 +85,15 @@ export class StepRefused extends Error {
52
85
  }
53
86
  }
54
87
 
55
- const lastLine = (output) =>
56
- output
88
+ /** The last `count` lines of a text that are not empty. */
89
+ const tail = (text, count) =>
90
+ (text ?? '')
57
91
  .split('\n')
58
92
  .map((line) => line.trimEnd())
59
93
  .filter((line) => line !== '')
60
- .pop() ?? '';
94
+ .slice(-count);
95
+
96
+ const lastLine = (output) => tail(output, 1)[0] ?? '';
61
97
 
62
98
  const readFile = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null);
63
99
 
@@ -191,36 +227,87 @@ export function markedProgress(text, number) {
191
227
  return lines.join('\n');
192
228
  }
193
229
 
194
- /** The verdict of a run: the mark is written and the step marked done, or the mark is dropped; the result is returned. */
195
- function settleStep({ git, marks }, model, { plan, step }, run, limitMs) {
230
+ /**
231
+ * The verdict of a run: the mark is written and the step marked done, or the mark is dropped; the
232
+ * result is returned with the command, its output and errors. `keepMark` leaves the mark of a step
233
+ * that did not match, for a run that is repeated; `restored` leaves a folder put back unmarked.
234
+ */
235
+ function settleStep({ git, marks }, model, { plan, step }, run, limitMs, { keepMark = false, restored = false } = {}) {
196
236
  const verdict = run.timedOut ? { form: null, matched: false } : compareExpected(model.expect, step.expected, run.code, run.output);
197
237
  if (verdict.matched) {
198
238
  marks.writeStep(plan.branch, step.number, { branch: plan.branch, step: step.number, plan: plan.fingerprint, head: git.head(), line: lastLine(run.output), replaced: step.replaced, matched: true });
199
239
  // Only the engine marks a step done: the guard refuses a hand mark.
200
240
  const progress = `${plan.folder}/${PROGRESS}`;
201
- const text = readFile(progress);
241
+ const text = restored ? null : readFile(progress);
202
242
  if (text !== null) {
203
243
  const marked = markedProgress(text, step.number);
204
244
  if (marked !== text) writeFileSync(progress, marked);
205
245
  }
206
- } else marks.dropStep(plan.branch, step.number);
207
- return { number: step.number, expected: step.expected, got: gotOf(run, verdict.form, limitMs, verdict.matched), matched: verdict.matched };
246
+ } else if (!keepMark) marks.dropStep(plan.branch, step.number);
247
+ const got = gotOf(run, verdict.form, limitMs, verdict.matched);
248
+ return { number: step.number, expected: step.expected, got, matched: verdict.matched, timedOut: run.timedOut, command: step.command, output: run.output, errors: run.errors ?? '', tap: run.tap ?? '' };
249
+ }
250
+
251
+ /**
252
+ * The command with `tee <file>` before its last pipe, so the output a closing `grep` only counts is
253
+ * kept for the line of an unmatched step. Null unless the pipe is certain: a `|` of `case`, `((`,
254
+ * `[[` or `>|`, a backslash in a quote and `PIPESTATUS` change their meaning under a `tee`.
255
+ */
256
+ export function tapped(command, file) {
257
+ if (/\bcase\b|\(\(|\[\[|>\||PIPESTATUS|\\/.test(command)) return null;
258
+ let quote = null;
259
+ let at = -1;
260
+ for (let i = 0; i < command.length; i++) {
261
+ const c = command[i];
262
+ if (quote) quote = c === quote ? null : quote;
263
+ else if (c === "'" || c === '"') quote = c;
264
+ else if (c === '|' && command[i + 1] !== '|' && command[i - 1] !== '|' && command[i + 1] !== '&') at = i;
265
+ }
266
+ return at < 0 || !/^\|\s*grep\b/.test(command.slice(at)) ? null : `${command.slice(0, at)}| tee '${file}' ${command.slice(at)}`;
208
267
  }
209
268
 
210
269
  /**
211
- * Measures one step of the plan: `{ number, expected, got, matched }`, and writes or drops its mark.
212
- * `sources` holds `git`, `steps`, `marks` and `owner`; `model` gives the words and the forms of `expect`.
270
+ * Measures one step of the plan: `{ number, expected, got, matched, removedBy }`, and writes or drops
271
+ * its mark. A taken-apart folder comes back for the run with the progress of the step's measurement; a
272
+ * step the last progress of the history does not mark done is refused with the move of the revert.
213
273
  */
214
274
  export function measureStep(sources, model, number, limitMs = STEP_LIMIT_MS, read = readFile) {
215
- const ready = prepareStep(sources, model, number, read);
216
- return settleStep(sources, model, ready, runCheck(ready.step.command, limitMs), limitMs);
275
+ const plan = planOfBranch(sources.git, model.words);
276
+ if (!sources.steps.ofPlan(plan.text).some((s) => s.number === number)) throw new StepRefused(`the plan names no step ${number}`);
277
+ const restored = restoreFolder(sources.git, plan.folder);
278
+ try {
279
+ if (restored) {
280
+ const progressPath = `${plan.folder}/${PROGRESS}`;
281
+ const latest = readFile(progressPath);
282
+ if (latest === null || !doneLine(number).test(latest)) {
283
+ const back = `\`git revert --no-edit ${restored.removedBy}\``;
284
+ throw new StepRefused(`${number} is not marked done in the history, and the task folder is taken apart by ${restored.removedBy.slice(0, 9)}: bring the folder back — ${back} — then do the step, measure it and take the folder apart again`);
285
+ }
286
+ rewritePutBack(progressPath, progressOfStep(versionsOf(sources.git, progressPath), latest, number));
287
+ }
288
+ const ready = preparedOn(sources, model, number, read, restored?.removedBy);
289
+ const result = settleStep(sources, model, ready, runCheck(ready.step.command, limitMs), limitMs, { restored: restored !== null });
290
+ return { ...result, removedBy: restored?.removedBy ?? null };
291
+ } finally {
292
+ release(restored);
293
+ }
294
+ }
295
+
296
+ /** `prepareStep` on a folder put back: a folder file edited after the plan gets the move of the revert. */
297
+ function preparedOn(sources, model, number, read, removedBy) {
298
+ try {
299
+ return prepareStep(sources, model, number, read);
300
+ } catch (error) {
301
+ if (!removedBy || !(error instanceof StepRefused) || !error.message.startsWith('the task folder differs')) throw error;
302
+ throw new StepRefused(`${error.message}, and the folder is taken apart by ${removedBy.slice(0, 9)}: ${revertMove(removedBy)}`);
303
+ }
217
304
  }
218
305
 
219
306
  /**
220
- * Measures the given steps side by side, at most `width` checks at once: the results in the order of
221
- * `numbers`, a refused step as `{ number, refused }`. The limit holds for each check, as in `measureStep`.
307
+ * Measures the steps side by side, at most `width` at once, each within the limit: results in the order
308
+ * of `numbers`, a refused one as `{ number, refused }`; `settle` goes to each verdict, `settle.tap` to `tapped`.
222
309
  */
223
- export async function measureSteps(sources, model, numbers, limitMs = STEP_LIMIT_MS, width = availableParallelism(), read = readFile) {
310
+ export async function measureSteps(sources, model, numbers, limitMs = STEP_LIMIT_MS, width = availableParallelism(), read = readFile, settle = {}) {
224
311
  const results = new Array(numbers.length);
225
312
  let next = 0;
226
313
  const worker = async () => {
@@ -228,9 +315,14 @@ export async function measureSteps(sources, model, numbers, limitMs = STEP_LIMIT
228
315
  const index = next++;
229
316
  const number = numbers[index];
230
317
  try {
231
- const ready = prepareStep(sources, model, number, read);
232
- const run = await runCheckAsync(ready.step.command, limitMs);
233
- results[index] = settleStep(sources, model, ready, run, limitMs);
318
+ const ready = preparedOn(sources, model, number, read, settle.removedBy);
319
+ const file = join(tmpdir(), `rt-step-${process.pid}-${number}.out`);
320
+ const command = (settle.tap && tapped(ready.step.command, file)) || ready.step.command;
321
+ const started = Date.now();
322
+ const run = await runCheckAsync(command, limitMs);
323
+ if (command !== ready.step.command) run.tap = readFile(file) ?? '';
324
+ rmSync(file, { force: true });
325
+ results[index] = { ...settleStep(sources, model, ready, run, limitMs, settle), ms: Date.now() - started };
234
326
  } catch (error) {
235
327
  if (!(error instanceof StepRefused)) throw error;
236
328
  results[index] = { number, refused: error.message };
@@ -264,6 +356,7 @@ export async function runStepCommand(sources, model, target, mode = '') {
264
356
  try {
265
357
  const result = measureStep(sources, model, target);
266
358
  console.log(stepLine(result));
359
+ if (!result.matched && result.removedBy) console.log([...detailLines(result), `step: ${revertMove(result.removedBy)}`].join('\n'));
267
360
  return result.matched ? 0 : 1;
268
361
  } catch (error) {
269
362
  if (!(error instanceof StepRefused)) throw error;
@@ -273,6 +366,9 @@ export async function runStepCommand(sources, model, target, mode = '') {
273
366
  }
274
367
  let numbers;
275
368
  try {
369
+ // A taken-apart folder: the done steps are measured the way the rerun before a PR measures them.
370
+ const folder = planOfBranch(sources.git, model.words).folder;
371
+ if (!existsSync(folder) || liveRun(folder)) return runBeforePull(sources, model);
276
372
  numbers = doneSteps(sources, model);
277
373
  } catch (error) {
278
374
  if (!(error instanceof StepRefused)) throw error;
@@ -290,11 +386,28 @@ export async function runStepCommand(sources, model, target, mode = '') {
290
386
  const trackedChanges = () =>
291
387
  (spawnSync('git', ['status', '--porcelain', '--untracked-files=no'], { encoding: 'utf8' }).stdout ?? '').split('\n').filter(Boolean).sort();
292
388
 
389
+ /** A line of a suite that names a failure. */
390
+ const FAILURE = /\bFAIL\b|\bnot ok\b|\b[Ee]rror\b|провал/;
391
+
392
+ /**
393
+ * The lines under an unmatched step: its command, the last lines of its output and of its errors, and
394
+ * of what a pipe fed its last command — the lines naming a failure, or the last ones; each cut at 300.
395
+ */
396
+ export const detailLines = (result) => {
397
+ const fed = (result.tap ?? '').split('\n').filter((line) => FAILURE.test(line) && !/\b0 провалов/.test(line));
398
+ const lines = (name, list) => list.map((line) => ` ${name}: ${line.slice(0, 300)}`);
399
+ return [
400
+ ...lines('command', [result.command]),
401
+ ...lines('output', tail(result.output, 3)),
402
+ ...lines('errors', tail(result.errors, 3)),
403
+ ...lines('before the last pipe', fed.length > 0 ? tail(fed.join('\n'), 3) : tail(result.tap, 3)),
404
+ ];
405
+ };
406
+
293
407
  /**
294
- * The rerun before a PR opens: every step the progress marks done is measured once more, whatever
295
- * mark lies on disk. A taken-apart task folder is put back from the history for the run and removed
296
- * after it; a check that leaves a tracked file changed does not match. A branch with no plan, or a
297
- * plan with no checks, has nothing to measure. Returns 0 when every done step matched.
408
+ * The rerun before a PR: every step the progress marks done is measured once more on the folder put
409
+ * back, whatever mark lies on disk; a check that changes a tracked file does not match. A mismatch
410
+ * runs again in its group within the budget and loses its mark only then. 0 when every step matched.
298
411
  */
299
412
  export async function runBeforePull(sources, model) {
300
413
  let plan;
@@ -309,48 +422,66 @@ export async function runBeforePull(sources, model) {
309
422
  console.log('step: the plan names no checks — nothing to measure before the PR');
310
423
  return 0;
311
424
  }
312
- // A taken-apart folder: its last version comes back for the run and leaves after it.
313
- const restored = [];
314
- if (!existsSync(plan.folder)) {
315
- const last = (spawnSync('git', ['log', '-1', '--format=%H', '--diff-filter=D', 'HEAD', '--', plan.folder], { encoding: 'utf8' }).stdout ?? '').trim();
316
- const at = last ? `${last}^` : null;
317
- for (const path of at ? sources.git.filesAt(plan.folder, at) : []) {
318
- const text = sources.git.versionAt(path, at);
319
- if (text === null) continue;
320
- mkdirSync(dirname(path), { recursive: true });
321
- writeFileSync(path, text);
322
- restored.push(path);
323
- }
324
- }
425
+ const started = Date.now();
325
426
  const before = trackedChanges();
427
+ let restored = null;
326
428
  try {
429
+ // A taken-apart folder: its last version comes back for the run and leaves after it.
430
+ restored = restoreFolder(sources.git, plan.folder);
327
431
  const numbers = doneSteps(sources, model);
328
- // The suites shorten the limit; the work always runs with the step limit.
432
+ // The suites shorten the limit and the budget; the work always runs with its own.
329
433
  const limit = Number(process.env.RT_FLOW_STEP_LIMIT_MS) || STEP_LIMIT_MS;
330
- // A restored folder brings the progress back as it stood when each step was measured — the
331
- // version before the first commit that marks the step done: a check that reads the progress
332
- // saw it so, while the last version has every step done.
434
+ const budget = Number(process.env.RT_FLOW_RERUN_BUDGET_MS) || RERUN_BUDGET_MS;
435
+ // A restored folder brings the progress back as it stood when each step was measured.
333
436
  const progressPath = `${plan.folder}/${PROGRESS}`;
334
- const latest = restored.includes(progressPath) ? readFileSync(progressPath, 'utf8') : null;
335
- const log = latest === null ? '' : (spawnSync('git', ['log', '--reverse', '--format=%H', 'HEAD', '--', progressPath], { encoding: 'utf8' }).stdout ?? '');
336
- const versions = log.split('\n').filter(Boolean).map((sha) => sources.git.versionAt(progressPath, sha));
437
+ const latest = restored ? readFile(progressPath) : null;
438
+ const versions = latest === null ? [] : versionsOf(sources.git, progressPath);
337
439
  const groups = new Map();
338
440
  for (const number of numbers) {
339
- const done = new RegExp(`^\\s*-\\s+\\[x\\]\\s+${number.replace('.', '\\.')}\\s`, 'm');
340
- const first = versions.findIndex((text) => text !== null && done.test(text));
341
- const chosen = (first > 0 && versions[first - 1]) || latest;
342
- const text = latest === null || chosen === latest ? chosen : withReplacements(chosen, latest);
441
+ const text = latest === null ? null : progressOfStep(versions, latest, number);
343
442
  groups.set(text, [...(groups.get(text) ?? []), number]);
344
443
  }
345
- const results = [];
346
- for (const [text, group] of groups) {
347
- if (text !== null) writeFileSync(progressPath, text);
348
- results.push(...(await measureSteps(sources, model, group, limit)));
349
- }
444
+ const settle = { keepMark: true, restored: restored !== null, removedBy: restored?.removedBy, tap: true };
445
+ // A second run of a group starts only when its longest first run still fits the budget, and
446
+ // runs no longer than the budget left.
447
+ const spent = new Map();
448
+ const runGroups = async (wanted, settled, again) => {
449
+ const out = [];
450
+ for (const [text, group] of groups) {
451
+ const todo = group.filter((number) => wanted.includes(number));
452
+ const left = budget - (Date.now() - started);
453
+ if (todo.length === 0 || (again && (spent.get(text) ?? 0) > left)) continue;
454
+ if (text !== null) rewritePutBack(progressPath, text);
455
+ const done = await measureSteps(sources, model, todo, again ? Math.min(limit, left) : limit, undefined, readFile, settled);
456
+ spent.set(text, Math.max(0, ...done.map((r) => r.ms ?? 0)));
457
+ out.push(...done);
458
+ }
459
+ return out;
460
+ };
461
+ const first = await runGroups(numbers, settle, false);
462
+ const again = first.filter((r) => !r.refused && !r.matched && !r.timedOut).map((r) => r.number);
463
+ const second = await runGroups(again, { ...settle, keepMark: false }, true);
464
+ // A second run refused keeps the first mismatch: the step did not match, and its lines stay.
465
+ const results = first.map((r) => {
466
+ const s = second.find((x) => x.number === r.number);
467
+ return s && !s.refused ? s : { ...r, refusedAgain: s?.refused };
468
+ });
350
469
  results.sort((a, b) => numbers.indexOf(a.number) - numbers.indexOf(b.number));
470
+ // A step that did not match and did not run again loses its mark here.
471
+ for (const r of results) if (!r.refused && !r.matched) sources.marks.dropStep(plan.branch, r.number);
351
472
  const changed = trackedChanges().filter((line) => !before.includes(line));
352
- for (const result of results) console.log(`${result.number} ${result.refused ? `step: ${result.refused}` : stepLine(result)}`);
473
+ for (const result of results) {
474
+ console.log(`${result.number} ${result.refused ? `step: ${result.refused}` : stepLine(result)}`);
475
+ const runs = second.some((s) => s.number === result.number && !s.refused) ? 'twice' : 'once';
476
+ const again = result.refusedAgain ? [` second run: step: ${result.refusedAgain}`] : [];
477
+ if (!result.refused && !result.matched) console.log([` runs: ${runs}`, ...again, ...detailLines(result)].join('\n'));
478
+ else if (result.matched && runs === 'twice') console.log(' matched on the second run');
479
+ }
353
480
  if (changed.length > 0) console.log(`step: the checks changed tracked files — ${changed.join(', ')}: a check measures, it does not edit`);
481
+ const failed = results.filter((r) => !r.refused && !r.matched).map((r) => r.number);
482
+ if (restored && failed.length > 0) {
483
+ console.log(`step: ${failed.join(', ')} did not match, and the task folder is taken apart by ${restored.removedBy.slice(0, 9)}: ${revertMove(restored.removedBy)}`);
484
+ }
354
485
  const matched = changed.length > 0 ? 0 : results.filter((result) => result.matched).length;
355
486
  console.log(`steps re-measured ${results.length}, matched ${matched}`);
356
487
  return matched === results.length && changed.length === 0 ? 0 : 1;
@@ -359,7 +490,6 @@ export async function runBeforePull(sources, model) {
359
490
  console.log(`step: ${error.message}`);
360
491
  return 1;
361
492
  } finally {
362
- for (const path of restored) rmSync(path, { force: true });
363
- if (restored.length > 0) rmSync(plan.folder, { recursive: true, force: true });
493
+ release(restored);
364
494
  }
365
495
  }
@@ -7,21 +7,76 @@
7
7
  * the command that measures it.
8
8
  *
9
9
  * When another check refused the same step twice for the same reason, or the executor stopped again
10
- * with no call after the previous refusal,
10
+ * with no call after a refusal of the engine itself,
11
11
  * the one move is the owner's menu: the options of `words.menu`, with the number of the task put in.
12
+ * A stop again after refusals of other stop hooks only names those hooks and the move instead.
12
13
  *
13
14
  * The case of the silent hosting counts only when the measurement itself stopped on the silence: a
14
15
  * read that failed for a state passed over says nothing when a later local exit is unmet. Any other
15
16
  * case the hosting could not answer is not met.
16
17
  */
17
18
  import { evaluateCondition } from './flow-condition.mjs';
18
- import { stepsOfProgress } from './work-steps-lib.mjs';
19
+ import { stepsOfPlan, stepsOfProgress } from './work-steps-lib.mjs';
19
20
 
20
21
  /** The measurer whose answer depends on where the measurement stopped. */
21
22
  const SILENCE = 'measure.host.silent';
22
23
 
23
24
  /** The measurers that name why the next move is the owner's menu. */
24
- const MENU_CAUSES = { unread: 'measure.session.unread', forbidden: 'measure.session.forbidden', idle: 'measure.session.idle' };
25
+ const MENU_CAUSES = { unread: 'measure.session.unread', hung: 'measure.session.hung', forbidden: 'measure.session.forbidden', idle: 'measure.session.idle' };
26
+
27
+ /** The measurer of the CI hold, read before the release cases and before the cause of the menu. */
28
+ const CI_HOLD = 'measure.ci.hold';
29
+
30
+ /**
31
+ * The CI hold: { kind, pr, run } of `measure.ci.hold`, or null. A description without the measurer
32
+ * holds nothing; a hosting that did not answer holds nothing either — the release cases decide then.
33
+ */
34
+ export function ciHold(model, read) {
35
+ if (!(model.measures ?? []).some((m) => m.entry === 'ci' && m.caps?.hold)) return null;
36
+ try {
37
+ return read(CI_HOLD) || null;
38
+ } catch (error) {
39
+ if (error?.name === 'HostSilent') return null;
40
+ throw error;
41
+ }
42
+ }
43
+
44
+ /** The refusal of a CI hold: the run, the PR, and the one move with its ready command. */
45
+ export function ciHoldReason(hold) {
46
+ const { pr, run } = hold;
47
+ const where = `PR #${pr.number} (\`${pr.head}\` into \`${pr.base}\`)`;
48
+ if (hold.kind === 'running') {
49
+ return [
50
+ `The CI run ${run.id} of ${where} is running, and no background task of this session watches it.`,
51
+ `The one move is to watch it in the background: \`command gh run watch ${run.id} --exit-status --interval 30\` with run_in_background — its notice wakes the session when the run ends. The watch lifts this hold; the scenario decides the rest of the turn.`,
52
+ ].join('\n');
53
+ }
54
+ if (hold.kind === 'fresh') {
55
+ const sha = String(pr.headRefOid ?? '');
56
+ const workflow = String(hold.file ?? '').split('/').pop();
57
+ const list = `command gh run list --commit ${sha}${workflow ? ` --workflow ${workflow}` : ''} --json databaseId --jq '.[0].databaseId'`;
58
+ return [
59
+ `The head ${sha.slice(0, 7)} of ${where} was pushed less than two minutes ago, and the hosting shows no CI run on it yet.`,
60
+ `The one move is a background watch of that head: \`for i in $(seq 30); do id=$(${list}); [ -n "$id" ] && break; sleep 10; done; [ -n "$id" ] && command gh run watch "$id" --exit-status --interval 30\` with run_in_background.`,
61
+ ].join('\n');
62
+ }
63
+ return [
64
+ `The CI run ${run.id} of ${where} ended «${run.conclusion}», and no call after its end has read it.`,
65
+ `The one move is to read it: \`command gh run view ${run.id} --log-failed | tail -n 200\` — then fix what fell when it is this session's work, or name the run in the reply when another session already fixes it. No owner's menu is offered while the run is unread.`,
66
+ ].join('\n');
67
+ }
68
+
69
+ /**
70
+ * The verdict on a measured branch: { block } of a CI hold first — the end of the scenario does not
71
+ * pass it — then { release } of the first release case, or null when the turn is held by the
72
+ * scenario.
73
+ */
74
+ export function decide(model, read, result) {
75
+ const hold = ciHold(model, read);
76
+ if (hold) return { block: ciHoldReason(hold) };
77
+ const released = releaseCase(model, read, result);
78
+ return released ? { release: released.log ?? released.key } : null;
79
+ }
25
80
 
26
81
  /** The first release case met, or null. `read` answers a measurer by its reference. */
27
82
  export function releaseCase(model, read, result) {
@@ -43,7 +98,8 @@ export function releaseCase(model, read, result) {
43
98
  * Why the next move is the owner's menu: { by: '<guard>' }, { idle: true }, or null. A measurer the
44
99
  * description does not declare, or the hosting could not answer, names no cause. An unread
45
100
  * background task comes first, { unread: { task, output, agent } }: while it is unread the move is to
46
- * read it, and no menu is offered.
101
+ * read it, and no menu is offered. A stop refused only by other hooks gives { foreign: ['<hook>', …] }:
102
+ * the hold names those hooks and the move of the state, not the menu.
47
103
  */
48
104
  export function menuCause(read) {
49
105
  const answer = (name) => {
@@ -57,7 +113,15 @@ export function menuCause(read) {
57
113
  if (unread) return { unread };
58
114
  const by = answer(MENU_CAUSES.forbidden);
59
115
  if (by) return { by: String(by) };
60
- return answer(MENU_CAUSES.idle) ? { idle: true } : null;
116
+ // A task past the bound of the wait is hung: the move is to deal with it, not the owner's menu.
117
+ // A step another check refused twice still goes to the owner's menu above.
118
+ const hung = answer(MENU_CAUSES.hung);
119
+ if (hung && typeof hung === 'object') return { hung };
120
+ const idle = answer(MENU_CAUSES.idle);
121
+ // A stop refused only by other hooks is no idle one: no menu, the refusal is named in one line.
122
+ const foreign = idle && typeof idle === 'object' ? [idle.foreign ?? []].flat().filter(Boolean).map(String) : [];
123
+ if (foreign.length > 0) return { foreign };
124
+ return idle ? { idle: true } : null;
61
125
  }
62
126
 
63
127
  /** The options of the owner's menu: `words.menu`, the number of the task put in place of N. */
@@ -72,6 +136,50 @@ export function currentStep(progress) {
72
136
  return step ? { number: step.number, name: step.name, left: steps.filter((s) => s.mark !== 'x').length } : null;
73
137
  }
74
138
 
139
+ /**
140
+ * The step the stages wait for: the current one of the progress, else the first step of the plan that
141
+ * the progress does not mark done or that has no matched mark. `{ number, name, left, done }`, or null;
142
+ * `matched(number)` answers the mark of a step.
143
+ */
144
+ export function pendingStep(progress, matched, plan = '') {
145
+ const marked = stepsOfProgress(progress ?? '').steps;
146
+ const planned = plan ? stepsOfPlan(plan).map((s) => ({ ...s, mark: marked.find((m) => m.number === s.number)?.mark ?? ' ' })) : marked;
147
+ const open = planned.filter((s) => s.mark !== 'x' || !matched(s.number));
148
+ const step = marked.find((s) => s.mark === '>') ?? open[0];
149
+ return step ? { number: step.number, name: step.name, left: open.length, done: step.mark === 'x' } : null;
150
+ }
151
+
152
+ /**
153
+ * The step of a running stage with no current step: from `text`, the progress on disk, or with no
154
+ * folder from the last progress of the history, with the commit that took the folder apart. Null when
155
+ * no progress is found.
156
+ */
157
+ export function stageStep(git, marks, folder, branch, text = null) {
158
+ const progress = text ?? git.lastVersion(`${folder}/progress.md`);
159
+ const plan = git.lastVersion(`${folder}/plan.md`) ?? '';
160
+ const pending = progress === null ? null : pendingStep(progress, (number) => marks.step(branch, number)?.matched === true, plan);
161
+ return pending ? { ...pending, removedBy: text === null ? git.removedAt(folder) : null } : null;
162
+ }
163
+
164
+ /** The lines of the step the stages wait for; `removedBy` names the commit that took the folder apart. */
165
+ function stepLines(step) {
166
+ const measure = `\`node tools/task-flow-script.mjs step ${step.number}\``;
167
+ const back = step.removedBy ? `\`git revert --no-edit ${step.removedBy}\`` : null;
168
+ if (!back) {
169
+ // A step read with the marks: its count is not the one of `check-work-steps`, which reads the progress alone.
170
+ const count = step.done === undefined ? 'are not done, counted by `node tools/check-work-steps.mjs`' : 'are not done or have no matched mark';
171
+ return [`${step.left} steps of the plan ${count}.`, `The next move is step ${step.number} «${step.name}»: do it, then measure it — ${measure}.`];
172
+ }
173
+ const lines = [`${step.left} steps of the plan are not done or have no matched mark, read from the last progress of the history: the task folder is taken apart by ${step.removedBy.slice(0, 9)}.`];
174
+ if (!step.done) {
175
+ lines.push(`The next move is step ${step.number} «${step.name}»: the history does not mark it done, so bring the folder back — ${back} — then do the step and measure it — ${measure}.`);
176
+ } else {
177
+ lines.push(`The next move is step ${step.number} «${step.name}»: measure it — ${measure}; the command puts the folder back for the run.`);
178
+ lines.push(`A step that does not match again is fixed where its check reads; a fix that lies in the folder — a check replaced in the progress — needs the folder back — ${back} — then take it apart again.`);
179
+ }
180
+ return lines;
181
+ }
182
+
75
183
  /**
76
184
  * The reason of a held turn: the measured state, its action, and the step when the stages go on. With a
77
185
  * cause of the menu the one move is the owner's menu instead.
@@ -90,6 +198,14 @@ export function holdReason(model, result, step, menu = null) {
90
198
  lines.push(`The background task \`${task}\` ended after the last call, and its notice has not been read${where}.`);
91
199
  lines.push('The first move is to read that output and act on it: a red result is fixed now. No owner\'s menu is offered while the task is unread.');
92
200
  }
201
+ } else if (menu?.cause?.hung) {
202
+ const { task, minutes, output } = menu.cause.hung;
203
+ const where = output ? ` — its output is \`${output}\`` : '';
204
+ lines.push(`The background task \`${task}\` runs ${minutes} minutes with no notice, past the bound of the wait: it is hung${where}.`);
205
+ lines.push('The first move is to read its output, then stop it or start it again, and go on with the step. No owner\'s menu is offered while it hangs.');
206
+ } else if (menu?.cause?.foreign) {
207
+ const hooks = menu.cause.foreign.map((hook) => `\`${hook}\``).join(', ');
208
+ lines.push(`The previous refusal came from ${hooks}, not from this check, and no owner's menu is offered for it. Do what it named; when it is not yours, say so in one line and make the move below in the same turn: a stop with no call after this refusal gives the menu.`);
93
209
  } else if (menu?.cause) {
94
210
  lines.push(
95
211
  menu.cause.idle
@@ -97,13 +213,12 @@ export function holdReason(model, result, step, menu = null) {
97
213
  : `The check \`${menu.cause.by}\` refused the same step twice for the same reason.`,
98
214
  );
99
215
  const options = menuOptions(model.words, menu.task);
100
- lines.push(`The one move is the owner's menu: ask through the question tool with exactly these options — ${options.map((o) => `«${o}»`).join(', ')}.`);
101
- lines.push('Then do what the owner chose: a deferral marks the task «отложено» in the plan of the epic and takes the next unblocked task; «стоп» ends the turn.');
216
+ lines.push(`The one move is the owner's menu: ask through the question tool with exactly these options — ${options.map((o) => `«${o}»`).join(', ')} — and say in the question that the way goes into its free field.`);
217
+ lines.push('Then do what the owner chose: a deferral marks the task «отложено» in the plan of the epic and takes the next unblocked task; a way written by the owner is taken in the same step. A bare «подскажу путь» with no text is followed by one question with a free field only.');
102
218
  return lines.join('\n');
103
219
  }
104
220
  if (step && state?.key === 'stage') {
105
- lines.push(`${step.left} steps of the plan are not done, counted by \`node tools/check-work-steps.mjs\`.`);
106
- lines.push(`The next move is step ${step.number} «${step.name}»: do it, then measure it — \`node tools/task-flow-script.mjs step ${step.number}\`.`);
221
+ lines.push(...stepLines(step));
107
222
  } else {
108
223
  lines.push(`The next move is the action of this state: ${state?.action ?? ''} (pattern \`${state?.pattern ?? ''}\`).`);
109
224
  }
@@ -94,12 +94,39 @@ const STOP_FEEDBACK = /^Stop hook feedback:/;
94
94
  * names itself is taken by its name; the rest are named here.
95
95
  */
96
96
  const CHECK_TABLE = [
97
+ // A model check speaks in the frame of the harness, and each event holds one model check: the
98
+ // frame names it, its failure to find or read its own file included. A verdict that quotes the
99
+ // refusal of another guard or a shell error is still its own.
100
+ [/^\s*Stop hook feedback:\s*Agent hook condition was not met: /, () => 'turn-judge'],
101
+ [/^\s*PreToolUse:AskUserQuestion hook error: Agent hook condition was not met: /, () => 'ask-judge'],
97
102
  // A neighbouring guard that names the load of a rule is the same round as the gate refusal,
98
103
  // only under another hook name, so it is counted as the gate before its own name is read.
99
104
  [/The named move is held by the rules gate/, () => 'skill-gate'],
100
105
  [/BLOCKED by ([a-z0-9][a-z0-9-]*):/, (m) => m[1]],
106
+ // The dispatcher of the command hooks failed as a shell script — a conflict marker or a syntax
107
+ // error in it: no guard ran, and the text is the error of the shell. A guard that named itself
108
+ // above keeps its name even when a line of the dispatcher stands in its text.
109
+ [/\/hooks\/dispatch\.sh: line \d+: /, () => 'dispatch-broken'],
101
110
  [/Refused by the rules gate/, () => 'skill-gate'],
102
111
  [/Refused: the epic is over/, () => 'epic-over'],
112
+ // The guards below name no check in their texts; each is told by the opening of its own text.
113
+ [
114
+ /BLOCKED: the work is not ready for delivery|while a conflicting request of your own stands|is merged, and the branch has no open PR|Rewrite the signature before the push|BLOCKED: a request from the branch «|BLOCKED: the task folder /,
115
+ () => 'git-guard-delivery',
116
+ ],
117
+ [
118
+ /BLOCKED: (?:the heavy steps of this tree run ahead|a push without a green local run|several pushes by one command|the command names a push, and the guard cannot read|switching the branch and pushing by one command|the call goes from a second working copy)/,
119
+ () => 'git-guard-push-tests',
120
+ ],
121
+ [/Refused: a commit straight into «/, () => 'git-guard-main'],
122
+ [/Refused: this call takes work, and /, () => 'tree-assignment-guard'],
123
+ [/BLOCKED: the commit edits code but not the document that describes it/, () => 'docs-guard'],
124
+ [/BLOCKED: this is already written\. File: /, () => 'reuse-first-guard'],
125
+ [/No browser is selected in this session\.|The last browser selection was \d+ s ago/, () => 'browser-guard-require-select'],
126
+ [/The profile «[^»]*» is not the one pinned to the project/, () => 'browser-guard-device-id'],
127
+ [/Do not list and do not switch browsers/, () => 'browser-guard-no-listing'],
128
+ [/Do not ask which browser to use/, () => 'browser-guard-no-asking'],
129
+ [/Drive the browser by the pinned extension/, () => 'browser-guard-no-other-drivers'],
103
130
  ];
104
131
 
105
132
  /** The check a refusal text names, or `unnamed`. */