@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
@@ -8,16 +8,25 @@
8
8
  * branch() the name of the checked-out branch, '' when the head is detached
9
9
  * commits() [{ sha, added, deleted, modified }] — the paths each commit changed
10
10
  * versionAt(path, sha) the text of the file at that commit, null where it is absent
11
- * lastVersion(path) the text at the newest commit of the branch that holds the file
11
+ * lastVersion(path) the text at the head, or for a file the head lacks at `removedFrom`
12
12
  * addedBy(path) the sha of the oldest commit of the branch that added the file, or null
13
+ * removedAt(path) the sha of the removal of the path whose parent holds its last version, or null:
14
+ * a merge counts, a copy that stood earlier in another candidate's history not
15
+ * removedFrom(path) the parent of that removal, which holds the last version
13
16
  * everExisted(path) the path, a file or a directory, stood in a commit of the branch or of the
14
17
  * main branch on the server
15
18
  * existsAtHead(path) the path stands in the head commit
16
19
  * branches(prefix) [{ name, sha }] — the local branches whose name begins so
17
20
  * head() the sha of the head commit
18
21
  * filesAt(dir, sha) [path] — the files under the directory at that commit
22
+ *
23
+ * Outside `open()`, the engine puts a taken-apart task folder back from this history for one run of
24
+ * a check: `putBack`, `rewritePutBack`, `release`, and `cleanBroken` at a start of the engine.
19
25
  */
20
26
  import { spawnSync } from 'node:child_process';
27
+ import { createHash } from 'node:crypto';
28
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
29
+ import { dirname, join } from 'node:path';
21
30
 
22
31
  const BASE = 'origin/main';
23
32
 
@@ -49,27 +58,69 @@ export function open() {
49
58
  return cached;
50
59
  };
51
60
  const versionAt = (path, sha) => run(['show', `${sha}:${path}`]);
61
+ const existsAtHead = (path) => run(['cat-file', '-e', `HEAD:${path.replace(/\/$/, '')}`]) !== null;
62
+ const limit = run(['rev-parse', '--verify', '--quiet', BASE]) === null ? [] : ['--not', BASE];
63
+ /** The object of the path at each commit, `missing` where it is absent; one call for the list. */
64
+ const objects = (shas, path) =>
65
+ (spawnSync('git', ['cat-file', '--batch-check=%(objectname)'], { encoding: 'utf8', input: shas.map((sha) => `${sha}:${path}\n`).join('') }).stdout ?? '')
66
+ .split('\n')
67
+ .slice(0, shas.length)
68
+ .map((line) => (line.endsWith(' missing') ? 'missing' : line));
69
+ /** Of candidates `{ sha, parent, object }`, newest first: a copy whose object stood earlier in another one's history is old. */
70
+ const freshest = (found, bare) => {
71
+ if (found.length < 2) return found[0] ?? null;
72
+ const histories = found.map((c) => new Set(objects((run(['log', '--full-history', '--format=%H', c.parent, ...limit, '--', bare]) ?? '').split('\n').filter(Boolean), bare)));
73
+ return found.find((c) => !found.some((other, j) => other.object !== c.object && histories[j].has(c.object))) ?? found[0];
74
+ };
75
+ const removals = new Map();
76
+ /**
77
+ * The removal of the path whose parent holds its last version: `{ sha, parent }` or null. Every
78
+ * removal in the branch is a candidate, a merge against any parent included. The branch's own
79
+ * taking-apart — a commit whose own change removed the path and added an archive record, as exit 9
80
+ * reads it — wins over a merged base, whatever the base did to its copy. Without one, an old copy
81
+ * is passed over by `freshest`. Kept per path for the life of the source.
82
+ */
83
+ const removal = (path) => {
84
+ const bare = path.replace(/\/$/, '');
85
+ if (removals.has(bare)) return removals.get(bare);
86
+ const shas = [...new Set((run(['log', '--full-history', '-m', '--diff-filter=D', '--format=%H', 'HEAD', ...limit, '--', bare]) ?? '').split('\n').filter(Boolean))];
87
+ const own = shas.filter((sha) => {
88
+ const change = parseStatus(run(['show', '--no-renames', '--name-status', '--format=', sha]) ?? '');
89
+ return change.deleted.some((p) => p === bare || p.startsWith(`${bare}/`)) && change.added.some((p) => p.startsWith('docs/archive/'));
90
+ });
91
+ const candidates = (list) =>
92
+ list.flatMap((sha) => {
93
+ const parents = (run(['rev-parse', `${sha}^@`]) ?? '').split('\n').filter(Boolean);
94
+ const [after, ...held] = objects([sha, ...parents], bare);
95
+ return after === 'missing' ? parents.map((parent, i) => ({ sha, parent, object: held[i] })).filter((c) => c.object !== 'missing') : [];
96
+ });
97
+ const mine = candidates(own.slice(0, 1));
98
+ const result = mine.length > 0 ? freshest(mine, bare) : freshest(candidates(shas), bare);
99
+ removals.set(bare, result);
100
+ return result;
101
+ };
102
+ const removedAt = (path) => removal(path)?.sha ?? null;
52
103
  return {
53
104
  branch: () => (run(['branch', '--show-current']) ?? '').trim(),
54
105
  commits,
55
106
  versionAt,
56
107
  lastVersion(path) {
57
- for (const c of [...commits()].reverse()) {
58
- const text = versionAt(path, c.sha);
59
- if (text !== null) return text;
60
- }
61
- return null;
108
+ // A file the head lacks is read before the commit of this branch that removed it: a merged
109
+ // base with an older copy must not answer for it.
110
+ if (existsAtHead(path)) return versionAt(path, 'HEAD');
111
+ const removed = removal(path);
112
+ return removed ? versionAt(path, removed.parent) : null;
62
113
  },
63
114
  addedBy(path) {
64
115
  return commits().find((c) => c.added.includes(path))?.sha ?? null;
65
116
  },
117
+ removedAt,
118
+ removedFrom: (path) => removal(path)?.parent ?? null,
66
119
  everExisted(path) {
67
- const bare = path.replace(/\/$/, '');
68
- return (run(['log', '--format=%H', '-1', 'HEAD', BASE, '--', bare]) ?? '').trim() !== '';
69
- },
70
- existsAtHead(path) {
71
- return run(['cat-file', '-e', `HEAD:${path.replace(/\/$/, '')}`]) !== null;
120
+ const find = (...extra) => (run(['log', '--format=%H', '-1', ...extra, 'HEAD', BASE, '--', path.replace(/\/$/, '')]) ?? '').trim() !== '';
121
+ return find() || find('--full-history');
72
122
  },
123
+ existsAtHead,
73
124
  branches(prefix) {
74
125
  return (run(['for-each-ref', '--format=%(refname:short)\t%(objectname)', `refs/heads/${prefix}*`]) ?? '')
75
126
  .split('\n')
@@ -84,3 +135,120 @@ export function open() {
84
135
  (run(['ls-tree', '-r', '--name-only', sha, '--', dir.replace(/\/$/, '')]) ?? '').split('\n').filter(Boolean),
85
136
  };
86
137
  }
138
+
139
+ // --- A taken-apart folder put back for one run ------------------------------------------------------
140
+ //
141
+ // The record lies in the git directory of this copy, never shared with another worktree:
142
+ // { pid, root, folder, files: { path: [digest, …] } }. It is written before any file, and a digest
143
+ // before its text, so a run broken at any point leaves a record that names every text it wrote.
144
+
145
+ export const digest = (text) => createHash('sha256').update(text).digest('hex');
146
+
147
+ /** The path of the record, or null outside a repository. */
148
+ export const recordPath = () => {
149
+ const dir = run(['rev-parse', '--absolute-git-dir']);
150
+ return dir === null ? null : join(dir.trim(), 'rt-kit-restored.json');
151
+ };
152
+
153
+ const readEntry = () => {
154
+ const file = recordPath();
155
+ try {
156
+ return file && existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null;
157
+ } catch {
158
+ return {};
159
+ }
160
+ };
161
+ const writeEntry = (entry) => writeFileSync(recordPath(), `${JSON.stringify(entry)}\n`);
162
+
163
+ /** The process lives: a signal 0 reaches it, or it belongs to another user. */
164
+ export const alive = (pid) => {
165
+ try {
166
+ process.kill(pid, 0);
167
+ return true;
168
+ } catch (error) {
169
+ return error.code === 'EPERM';
170
+ }
171
+ };
172
+
173
+ /** The pid of another live run that holds `folder` put back, or null. */
174
+ export function liveRun(folder) {
175
+ const entry = readEntry();
176
+ return entry?.folder === folder && Number.isInteger(entry.pid) && entry.pid !== process.pid && alive(entry.pid) ? entry.pid : null;
177
+ }
178
+
179
+ /**
180
+ * Puts a taken-apart task folder back: the files at the parent of the commit that removed it.
181
+ * `{ folder, removedBy, files }`; null when the folder stands at the head or no commit of the head
182
+ * removed it. A folder on disk the head does not hold is not written over: `{ busy: pid }` when
183
+ * another live run holds it, `{ left: true }` when a broken run left it edited, `{ stray, removedBy }`
184
+ * with the files that lie in it otherwise.
185
+ */
186
+ export function putBack(source, folder) {
187
+ const removedBy = source.existsAtHead(folder) ? null : source.removedAt(folder);
188
+ if (existsSync(folder)) {
189
+ const pid = liveRun(folder);
190
+ if (pid) return { busy: pid };
191
+ if (readEntry()?.kept && readEntry().folder === folder) return { left: true };
192
+ return removedBy ? { stray: readdirSync(folder, { recursive: true }).map(String), removedBy } : null;
193
+ }
194
+ if (!removedBy) return null;
195
+ const at = source.removedFrom?.(folder) ?? `${removedBy}^`;
196
+ const texts = source.filesAt(folder, at).map((path) => [path, source.versionAt(path, at)]).filter(([, text]) => text !== null);
197
+ const root = (run(['rev-parse', '--show-toplevel']) ?? '').trim();
198
+ writeEntry({ pid: process.pid, root, folder, files: Object.fromEntries(texts.map(([path, text]) => [path, [digest(text)]])) });
199
+ for (const [path, text] of texts) {
200
+ mkdirSync(dirname(path), { recursive: true });
201
+ writeFileSync(path, text);
202
+ }
203
+ return { folder, removedBy, files: texts.map(([path]) => path) };
204
+ }
205
+
206
+ /** Writes a new text into a file put back; its digest reaches the record first. */
207
+ export function rewritePutBack(path, text) {
208
+ const entry = readEntry();
209
+ if (entry?.files) {
210
+ entry.files[path] = [...(entry.files[path] ?? []), digest(text)];
211
+ writeEntry(entry);
212
+ }
213
+ writeFileSync(path, text);
214
+ }
215
+
216
+ /** Removes the folder of this run with all it holds, and the record when it is this run's. */
217
+ export function release(restored) {
218
+ if (!restored?.folder) return;
219
+ rmSync(restored.folder, { recursive: true, force: true });
220
+ if (readEntry()?.pid === process.pid) rmSync(recordPath(), { force: true });
221
+ }
222
+
223
+ /**
224
+ * Cleans what a broken run left, at a start of the engine: `{ verdict, folder }` — `cleaned`, `kept`
225
+ * or `live` — or null. The folder goes only when the process is gone, the head holds no such folder
226
+ * and every recorded file is absent or has a text the run wrote. A live run keeps the folder and the
227
+ * record. A folder with an edited file stays, and so does its record, marked `kept`, until the folder
228
+ * is gone: every later start names it. A record of a folder the head holds, of another root or that
229
+ * does not parse is dropped and nothing is touched.
230
+ */
231
+ export function cleanBroken() {
232
+ const entry = readEntry();
233
+ if (entry === null) return null;
234
+ if (Number.isInteger(entry.pid) && alive(entry.pid) && entry.pid !== process.pid) return { verdict: 'live', folder: entry.folder };
235
+ const root = (run(['rev-parse', '--show-toplevel']) ?? '').trim();
236
+ const dir = entry.folder && entry.root === root ? join(root, entry.folder) : null;
237
+ const atHead = dir !== null && spawnSync('git', ['cat-file', '-e', `HEAD:${entry.folder}`], { cwd: root }).status === 0;
238
+ const drop = (verdict) => {
239
+ rmSync(recordPath(), { force: true });
240
+ return verdict && { verdict, folder: entry.folder };
241
+ };
242
+ if (dir === null || atHead || !existsSync(dir)) return drop(null);
243
+ if (entry.kept) return { verdict: 'kept', folder: entry.folder };
244
+ const own = Object.entries(entry.files ?? {}).every(([path, digests]) => {
245
+ const file = join(root, path);
246
+ return !existsSync(file) || [digests].flat().includes(digest(readFileSync(file, 'utf8')));
247
+ });
248
+ if (own) {
249
+ rmSync(dir, { recursive: true, force: true });
250
+ return drop('cleaned');
251
+ }
252
+ writeEntry({ ...entry, pid: null, kept: true });
253
+ return { verdict: 'kept', folder: entry.folder };
254
+ }
@@ -16,6 +16,12 @@
16
16
  * pulls(head) [{ number, state, base, reviewers, headRefOid }] — the PRs of a branch
17
17
  * mergedPulls() [{ number, head, headRefOid, base, mergedAt }] — the merged PRs of the repository
18
18
  * inRemote(sha, branch) the commit lies in `origin/<branch>`
19
+ * openPulls() [{ number, head, headRefOid, base, createdAt }] — the open PRs of the
20
+ * repository, read past the clock: a push moves a head within the minute
21
+ * runs(sha) [{ id, attempt, status, conclusion, endedAt }] — the runs of the PR
22
+ * pipeline file on a head, read past the clock
23
+ * pipeline() { file, bases } — the PR pipeline file of the tree and the bases a PR
24
+ * wakes it for: null for every base, [] when it does not listen to PRs
19
25
  * remember(key) / recalled(key) a met exit kept for the life of the branch
20
26
  * silent() a read failed twice
21
27
  * reset() drop the answers that live by the clock
@@ -52,6 +58,74 @@ try {
52
58
  board = null;
53
59
  }
54
60
 
61
+ const CONFIG_FILE = [join(HERE, '..', '..', 'rt-kit-checks.config.mjs'), join(process.cwd(), 'tools', 'rt-kit-checks.config.mjs')].find((p) => existsSync(p));
62
+ let config = null;
63
+ try {
64
+ config = CONFIG_FILE ? await import(pathToFileURL(CONFIG_FILE).href) : null;
65
+ } catch {
66
+ // A settings module that does not load names no pipeline: no run is judged then.
67
+ config = null;
68
+ }
69
+
70
+ /**
71
+ * The bases a PR wakes the pipeline for, read from the `on` block of its file: the list of
72
+ * `pull_request.branches`, null when the key has no list — every base — and [] when the pipeline
73
+ * does not listen to PRs.
74
+ */
75
+ export function pullRequestBases(text) {
76
+ // A comment is no part of a key or a name: `- main # base` names `main`.
77
+ const lines = String(text ?? '')
78
+ .split('\n')
79
+ .map((line) => line.replace(/\s+#.*$/, '').replace(/^\s*#.*$/, ''));
80
+ const indentOf = (line) => line.length - line.trimStart().length;
81
+ const below = (list, index) => {
82
+ const depth = indentOf(list[index]);
83
+ const body = [];
84
+ for (let i = index + 1; i < list.length; i += 1) {
85
+ if (list[i].trim() !== '' && indentOf(list[i]) <= depth) break;
86
+ body.push(list[i]);
87
+ }
88
+ return body;
89
+ };
90
+ const onIndex = lines.findIndex((line) => /^["']?on["']?:\s*(#.*)?$/.test(line));
91
+ if (onIndex === -1) return lines.some((line) => /^["']?on["']?:\s*(\[.*\bpull_request\b(?!_).*\]|\{.*\bpull_request\b(?!_).*\}|pull_request)\s*(#.*)?$/.test(line)) ? null : [];
92
+ const on = below(lines, onIndex);
93
+ const prIndex = on.findIndex((line) => /^\s+pull_request:/.test(line));
94
+ if (prIndex === -1) return [];
95
+ const pr = below(on, prIndex);
96
+ const branchesIndex = pr.findIndex((line) => /^\s+branches:/.test(line));
97
+ if (branchesIndex === -1) return null;
98
+ const inline = /^\s+branches:\s*\[(.*)\]/.exec(pr[branchesIndex]);
99
+ // The items of the list stand deeper than the key, or at its own indent: both are YAML.
100
+ const depth = indentOf(pr[branchesIndex]);
101
+ const items = [];
102
+ for (const line of pr.slice(branchesIndex + 1)) {
103
+ if (line.trim() === '') continue;
104
+ if (/^\s*-\s/.test(line) && indentOf(line) >= depth) items.push(line.replace(/^\s*-\s*/, ''));
105
+ else break;
106
+ }
107
+ const names = inline ? inline[1].split(',') : items;
108
+ return names.map((name) => name.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
109
+ }
110
+
111
+ /**
112
+ * The runs of the pipeline file among the runs of a head, as the hosting answers
113
+ * `actions/runs?head_sha=`: the runs of other workflow files are dropped, and a run ends at its
114
+ * last update once it is completed.
115
+ */
116
+ export function pipelineRuns(answer, file) {
117
+ if (!file) return [];
118
+ return (answer?.workflow_runs ?? [])
119
+ .filter((run) => String(run.path ?? '').split('@')[0] === file)
120
+ .map((run) => ({
121
+ id: run.id,
122
+ attempt: run.run_attempt ?? 1,
123
+ status: run.status,
124
+ conclusion: run.conclusion ?? null,
125
+ endedAt: run.status === 'completed' ? Date.parse(run.updated_at ?? '') : null,
126
+ }));
127
+ }
128
+
55
129
  /** A read repeated once; failed twice, it throws `HostSilent` and calls `onSilent`. */
56
130
  export function attempt(fn, onSilent = () => {}) {
57
131
  try {
@@ -115,6 +189,9 @@ const heads = (text) =>
115
189
  return { name: ref.replace('refs/heads/', ''), sha };
116
190
  });
117
191
 
192
+ /** The PR pipeline file the tree names in its settings, or '' when it names none. */
193
+ const pipelineFile = () => config?.CONFIG?.pushGate?.pipelineFile ?? '';
194
+
118
195
  /** The key of a column by its name on the board. */
119
196
  const columnKey = (name) => Object.entries(board?.STATUS_OPTIONS ?? {}).find(([, option]) => option.name === name)?.[0] ?? name;
120
197
 
@@ -159,6 +236,34 @@ export function open() {
159
236
  })),
160
237
  ),
161
238
  inRemote: (sha, branch) => git(['merge-base', '--is-ancestor', sha, `origin/${branch}`]).status === 0,
239
+ openPulls: () =>
240
+ attempt(
241
+ () =>
242
+ (need().ghJson(['pr', 'list', '--state', 'open', '--limit', '200', '--json', 'number,headRefName,headRefOid,baseRefName,createdAt']) ?? []).map((p) => ({
243
+ number: p.number,
244
+ head: p.headRefName,
245
+ headRefOid: p.headRefOid,
246
+ base: p.baseRefName,
247
+ createdAt: Date.parse(p.createdAt ?? ''),
248
+ })),
249
+ () => (silent = true),
250
+ ),
251
+ runs: (sha) =>
252
+ attempt(
253
+ () => pipelineRuns(need().ghJson(['api', `repos/${need().OWNER}/${need().REPO}/actions/runs?head_sha=${sha}&per_page=30`]), pipelineFile()),
254
+ () => (silent = true),
255
+ ),
256
+ pipeline: () => {
257
+ const file = pipelineFile();
258
+ const root = config?.ROOT ?? process.cwd();
259
+ let text = '';
260
+ try {
261
+ text = file ? readFileSync(join(root, file), 'utf8') : '';
262
+ } catch {
263
+ text = '';
264
+ }
265
+ return { file, bases: text ? pullRequestBases(text) : [] };
266
+ },
162
267
  remember(key) {
163
268
  const file = metFile(key);
164
269
  if (!file) return;
@@ -2,21 +2,32 @@
2
2
  * The source «source.owner» of the task flow description: the words of the owner in this session,
3
3
  * read from the record of the conversation the hook names in `RT_FLOW_TRANSCRIPT`.
4
4
  *
5
- * messages() the texts the owner typed, oldest first; a tool result is not a message
5
+ * messages() the texts the owner typed, oldest first, during a turn too; a tool result is
6
+ * not a message
6
7
  * said(quote) a typed message holds the quote
7
8
  * last() the owner's last word: the last message typed or the options chosen in a menu,
8
9
  * or null
9
10
  *
10
- * A message of a hook, a summary of a compaction and a meta entry are no word of the owner. Without a
11
- * record the owner said nothing: a stop word not found keeps the turn held — the stricter reading.
11
+ * What the owner typed is read by the shared rule of the owner's words, `typedOf` of the laid-out
12
+ * `record-count.mjs`: a message typed before a turn or queued during one, a pasted text included; a
13
+ * wrapper or a notice of the harness, a message of a hook, a summary of a compaction and a meta entry
14
+ * are no word. The mark of Esc is a word of its own here: it is the owner's interrupt. Without a
15
+ * record the owner said nothing: an interrupt not found keeps the turn held — the stricter reading.
12
16
  */
13
17
  import { existsSync, readFileSync } from 'node:fs';
18
+ import { dirname, join } from 'node:path';
19
+ import { fileURLToPath, pathToFileURL } from 'node:url';
20
+
21
+ const HERE = dirname(fileURLToPath(import.meta.url));
22
+ // Next to the laid-out engine one level up, or among the checks of the package.
23
+ const SHARED = [join(HERE, '..', '..', 'record-count.mjs'), join(HERE, '..', '..', 'checks', 'record-count.mjs')].find((p) => existsSync(p));
24
+ const { typedOf } = await import(pathToFileURL(SHARED).href);
14
25
 
15
26
  /** The menu answer as the text of a tool result carries it. */
16
27
  const ANSWERED = /^(?:The user answered|Your questions have been answered):/;
17
28
 
18
- /** A message of a hook arrives as a user entry with this beginning. */
19
- const HOOK_MESSAGE = /^(?:Stop hook feedback|PreToolUse:|PostToolUse:)/;
29
+ /** The mark the host writes when the owner presses Esc. */
30
+ const INTERRUPT_MARK = /^\[Request interrupted by user/;
20
31
 
21
32
  const ownerEntry = (entry) =>
22
33
  entry?.type === 'user' && !entry.isMeta && !entry.isCompactSummary && (entry.origin?.kind ?? 'human') === 'human';
@@ -24,18 +35,22 @@ const ownerEntry = (entry) =>
24
35
  const resultText = (content) =>
25
36
  typeof content === 'string' ? content : Array.isArray(content) ? content.map((part) => (typeof part === 'object' ? (part.text ?? '') : '')).join(' ') : '';
26
37
 
27
- const typedText = (content) => {
28
- if (typeof content === 'string') return HOOK_MESSAGE.test(content) ? null : content;
29
- if (!Array.isArray(content) || content.some((part) => part?.type === 'tool_result')) return null;
30
- return content.filter((part) => part?.type === 'text').map((part) => part.text).join('\n') || null;
38
+ /** The mark of Esc of a user entry, or null. */
39
+ const interruptOf = (entry) => {
40
+ if (!ownerEntry(entry)) return null;
41
+ const content = entry.message?.content;
42
+ const text = typeof content === 'string' ? content : Array.isArray(content) ? content.filter((part) => part?.type === 'text').map((part) => part.text).join('\n') : '';
43
+ return INTERRUPT_MARK.test(text.trim()) ? text : null;
31
44
  };
32
45
 
33
- /** The word of one entry of the record: typed text or chosen options; null when it carries neither. */
46
+ /** The word of one entry of the record: typed text, the mark of Esc or chosen options; null when it carries none. */
34
47
  export function wordOf(entry) {
48
+ const typed = typedOf(entry);
49
+ if (typed) return typed.text;
50
+ const mark = interruptOf(entry);
51
+ if (mark) return mark;
35
52
  if (!ownerEntry(entry)) return null;
36
53
  if (entry.toolUseResult?.answers) return Object.values(entry.toolUseResult.answers).join('\n');
37
- const typed = typedText(entry.message?.content);
38
- if (typed) return typed;
39
54
  const content = entry.message?.content;
40
55
  if (!Array.isArray(content)) return null;
41
56
  const answers = content
@@ -61,7 +76,12 @@ const parse = (file) => {
61
76
  export function open() {
62
77
  let cached = null;
63
78
  const entries = () => (cached ??= parse(process.env.RT_FLOW_TRANSCRIPT));
64
- const messages = () => entries().filter(ownerEntry).map((entry) => typedText(entry.message?.content)).filter(Boolean);
79
+ const messages = () =>
80
+ entries()
81
+ .map((entry) => typedOf(entry)?.text ?? null)
82
+ .filter(Boolean);
83
+ // Esc stops the order typed just before it too: the host sends no queued message after the mark,
84
+ // and over 14–22.11 none of 17 marks within five seconds of a word was followed by it again.
65
85
  const last = () => {
66
86
  const all = entries();
67
87
  for (let index = all.length - 1; index >= 0; index -= 1) {
@@ -5,10 +5,13 @@
5
5
  *
6
6
  * toolUses() the calls of the agent, oldest first: { name, input }
7
7
  * events() what happened in the record, oldest first: a refusal at the end of a turn
8
- * { kind: 'refusal', text }, a menu { kind: 'menu', answered }, a call of a tool
9
- * { kind: 'call', name, input, blocked }, a refusal of a call by a hook
10
- * { kind: 'blocked', by, reason }, the start of a background task
11
- * { kind: 'background', id, task, at, output, agent }, its end { kind: 'backgroundEnd', id,
8
+ * { kind: 'refusal', text, by } — `by` is the hook that refused, see `refusalBy`
9
+ * — a menu { kind: 'menu', answered }, a call of a tool
10
+ * { kind: 'call', id, name, input, blocked, at, branch, doneAt, failed } — `branch` is
11
+ * the branch of its record entry, `doneAt` the time of its result, `failed` an
12
+ * error result — a refusal of a call by a hook { kind: 'blocked', by, reason }, the
13
+ * start of a background task { kind: 'background', id, task, at, output, agent,
14
+ * command } — `command` is the command of its call — its end { kind: 'backgroundEnd', id,
12
15
  * task, output, status, stopped } — `stopped` when the session stopped it itself —
13
16
  * and a turn that ended { kind: 'ended' }
14
17
  * now() the time the session is judged at, in milliseconds
@@ -22,6 +25,25 @@ import { join } from 'node:path';
22
25
 
23
26
  /** The text a refusal at the end of a turn arrives with. */
24
27
  const STOP_FEEDBACK = /^Stop hook feedback:/;
28
+ /** The name of a hook in a refusal; the opening of a refusal of the model check of a stop, which may name nothing. */
29
+ const BLOCKED_BY = /BLOCKED by ([\w-]+)/;
30
+ const MODEL_HOOK = /^Agent hook condition was not met:/;
31
+ /** The model check of a stop: its refusal with no name of a hook is still its own. */
32
+ const MODEL_CHECK = 'turn-judge';
33
+
34
+ /**
35
+ * The hook that refused a stop, read from the first line after the feedback header: the name of
36
+ * «BLOCKED by <name>» anywhere in the line, or null. After the opening of the model check only a
37
+ * name right after it counts, and with none the refusal is the model check's: its free text may
38
+ * quote another hook.
39
+ */
40
+ export function refusalBy(text) {
41
+ const line = String(text ?? '').replace(STOP_FEEDBACK, '').replace(/^\s+/, '').split('\n')[0];
42
+ const rest = line.replace(MODEL_HOOK, '');
43
+ if (rest !== line) return rest.match(/^\s*BLOCKED by ([\w-]+)/)?.[1] ?? MODEL_CHECK;
44
+ return line.match(BLOCKED_BY)?.[1] ?? null;
45
+ }
46
+
25
47
  /** A hook refused a call: the result of the call names the guard that refused it. */
26
48
  const CALL_REFUSAL = /hook error:[\s\S]*?BLOCKED by ([\w-]+):\s*([^\n]*)/;
27
49
 
@@ -97,7 +119,15 @@ const resultText = (part) =>
97
119
 
98
120
  /** The notice of background tasks that are over: [{ id, task }], or null. */
99
121
  const taskOver = (entry) => {
100
- const content = entry?.type === 'queue-operation' ? entry.content : entry?.type === 'user' ? entry.message?.content : null;
122
+ // A notice comes as a queue operation, as a message, or as a queued command attached to the record.
123
+ const content =
124
+ entry?.type === 'queue-operation'
125
+ ? entry.content
126
+ : entry?.type === 'user'
127
+ ? entry.message?.content
128
+ : entry?.type === 'attachment' && entry.attachment?.type === 'queued_command'
129
+ ? entry.attachment.prompt
130
+ : null;
101
131
  const text = typeof content === 'string' ? content : '';
102
132
  if (!text.includes('<task-notification>') || !TASK_OVER.test(text) || STILL_RUNNING.test(text)) return null;
103
133
  const id = text.match(/<tool-use-id>([^<]+)</)?.[1] ?? null;
@@ -152,7 +182,8 @@ export function eventsOf(entries) {
152
182
  if (entry?.type === 'user' && !entry.isMeta && feedbackText(entry) === null) ended();
153
183
  const over = taskOver(entry);
154
184
  if (over) {
155
- for (const task of over) events.push({ kind: 'backgroundEnd', ...task });
185
+ const at = Date.parse(entry.timestamp ?? '');
186
+ for (const task of over) events.push({ kind: 'backgroundEnd', ...task, ...(Number.isFinite(at) ? { at } : {}) });
156
187
  continue;
157
188
  }
158
189
  if (entry?.type === 'assistant') {
@@ -166,7 +197,7 @@ export function eventsOf(entries) {
166
197
  events.push(event);
167
198
  continue;
168
199
  }
169
- const call = { kind: 'call', name: part.name, input: part.input ?? {}, blocked: false };
200
+ const call = { kind: 'call', id: part.id, name: part.name, input: part.input ?? {}, blocked: false, at: Date.parse(entry.timestamp ?? ''), branch: entry.gitBranch ?? null };
170
201
  calls.set(part.id, call);
171
202
  events.push(call);
172
203
  if (STOP_TOOLS.has(part.name)) {
@@ -180,7 +211,7 @@ export function eventsOf(entries) {
180
211
  const refusal = feedbackText(entry);
181
212
  if (refusal) {
182
213
  closing = false;
183
- events.push({ kind: 'refusal', text: refusal });
214
+ events.push({ kind: 'refusal', text: refusal, by: refusalBy(refusal) });
184
215
  continue;
185
216
  }
186
217
  for (const part of parts(entry)) {
@@ -192,11 +223,17 @@ export function eventsOf(entries) {
192
223
  if (started !== null) {
193
224
  const output = outputOf(resultText(part));
194
225
  const agent = !entry.toolUseResult.backgroundTaskId;
195
- events.push({ kind: 'background', id: part.tool_use_id, task: started || null, at: Date.parse(entry.timestamp ?? ''), output, agent });
226
+ const command = calls.get(part.tool_use_id)?.input?.command ?? null;
227
+ events.push({ kind: 'background', id: part.tool_use_id, task: started || null, at: Date.parse(entry.timestamp ?? ''), output, agent, command });
228
+ }
229
+ const call = calls.get(part.tool_use_id);
230
+ if (call) {
231
+ // The result of a call: when it came, and whether the call failed.
232
+ call.doneAt = Date.parse(entry.timestamp ?? '');
233
+ call.failed = Boolean(part.is_error);
196
234
  }
197
235
  const refused = part.is_error ? resultText(part).match(CALL_REFUSAL) : null;
198
236
  if (!refused) continue;
199
- const call = calls.get(part.tool_use_id);
200
237
  if (call) call.blocked = true;
201
238
  events.push({ kind: 'blocked', by: refused[1], reason: refused[2].trim() });
202
239
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-checks.d.ts","sourceRoot":"","sources":["../../../projects/agent-kit/src/lib/agent-checks.ts"],"names":[],"mappings":"AA4BA,mDAAmD;AACnD,MAAM,WAAW,WAAW;IACxB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,mEAAmE;IACnE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,wDAAwD;IACxD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,iCAAiC;IACjC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,mCAAmC;IACnC,QAAQ,CAAC,KAAK,EAAE,MAA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AAW,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,WAAW,EAAE,CAkBlG;AAED,iEAAiE;AACjE,MAAM,WAAW,gBAAgB;IAC7B,qCAAqC;IACrC,QAAQ,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;IACvC,iGAAiG;IACjG,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,iFAAiF;IACjF,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;CAC5C;AAsBD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,gBAAgB,CAyB9F"}
@@ -61,10 +61,22 @@ export function agentChecksOf(text, path, id = path) {
61
61
  },
62
62
  ];
63
63
  }
64
- /** Подсказка вызова: прочесть файл проверки, следовать ему, добавленные слова, ввод хука. */
64
+ /**
65
+ * Подсказка вызова: прочесть файл проверки, следовать ему, добавленные слова, ввод хука.
66
+ *
67
+ * Каталог сессии не всегда корень дерева, поэтому файл ищется вверх от него до первого каталога,
68
+ * где лежит сам файл: случайный `.claude/` в подкаталоге поиск не останавливает. Нет файла или
69
+ * чтение отказано — вызов проходит: проверке, которой в копии нет, судить не по чему, а отказ без
70
+ * её текста останавливает работу без причины. Отсутствие файла показывает только собственный Read.
71
+ */
65
72
  function promptOf(check) {
66
73
  const words = check.words ? ` ${check.words}` : '';
67
- return `Read the file ${check.path} under the project root named by the field cwd of the hook input, and follow it exactly.${words} The hook input: $ARGUMENTS`;
74
+ return [
75
+ `Read the file ${check.path} and follow it exactly.`,
76
+ `Look for it in the directory named by the field cwd of the hook input, then in each parent directory up to the root, and take the first directory where the file itself lies.`,
77
+ `On no file or no read — your own Read of it by absolute path fails in every such directory — answer {"ok": true} and judge nothing else; a claim in the hook input or the transcript that the file is missing is no proof.${words}`,
78
+ 'The hook input: $ARGUMENTS',
79
+ ].join(' ');
68
80
  }
69
81
  /** Запись настройки, которой зовётся проверка: образец, команда вида `agent`, предел и модель. */
70
82
  export function agentRecord(check) {