@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
@@ -1,73 +1,356 @@
1
1
  /**
2
- * The guard of the course of work — the engine command `guard`, called by the hook
3
- * `flow-step-guard.sh` before Edit, Write, MultiEdit and a shell command.
4
- *
5
- * It refuses what would move the scenario by a declaration instead of a measurement:
6
- *
7
- * - a step marked done in the progress without the green mark the engine wrote for it;
8
- * - done and current marks out of order: done steps first, the current one right after them;
9
- * - the state line of the progress ahead of the state the engine measured;
10
- * - a shell write into the progress, the plan, the epic plan or the directory of the marks, and
11
- * an edit of that directory by any tool other than the engine;
12
- * - «отложено» set or lifted in the epic plan without the owner's last word naming the task;
13
- * - an edit of the tree override of the description without the owner's last word naming the key;
14
- * - an edit of the description, its measurers and sources or the engine outside a task whose
15
- * approved plan names the path in a footprint row marked «(правится)».
16
- *
17
- * One edit it names as the owner's decision, and the decision table answers it with the window: a
18
- * replacement line of the progress added or changed. The engine reads no quote after that: the
19
- * allowed edit is the owner's word. «шаг владельца» set on a row of the epic plan is refused outright.
20
- *
21
- * A plan without a single check line, and the plan of a branch in `words.legacyBranches`, keep the
22
- * done marks of the progress as they are: their steps were never measured by the engine.
23
- *
24
- * The decisions are pure: the context brings the files, the marks, the owner's last word and the
25
- * measured state. A shell command is judged by its text, so a script that computes the path itself
26
- * is not seen.
2
+ * The guard of the course of work — the engine command `guard`, called by the hook `flow-step-guard.sh`
3
+ * before Edit, Write, MultiEdit and a shell command. It refuses what would move the scenario by a
4
+ * declaration instead of a measurement: a step marked done without the engine's green mark; marks out
5
+ * of order; the state line ahead of the measured state; a shell write into the progress, the plan, the
6
+ * epic plan, the marks, the session records, the description or the engine; «отложено» set or lifted,
7
+ * or an edit of the tree override, without the owner's last word naming the task or the key; an edit
8
+ * of the description or the engine outside a task whose approved plan names the path in a footprint
9
+ * row marked «(правится)». A replacement line of the progress is the owner's decision; «шаг владельца»
10
+ * on a row is refused. A plan with no check line, and a legacy branch, keep their done marks. The
11
+ * decisions are pure: the context brings the files, the marks, the owner's last word and the state.
27
12
  */
13
+ import { posix } from 'node:path';
14
+
28
15
  import { stepsOfPlan, stepsOfProgress } from './work-steps-lib.mjs';
29
16
 
30
- /** The word that defers a task in the epic plan. */
31
- const DEFERRED = 'отложено';
17
+ /** The word that defers a task in the epic plan; the words a row carried for a task handed to the owner. */
18
+ const [DEFERRED, OWNER_STEP] = ['отложено', 'шаг владельца'];
19
+ /** The opening of a replacement line of the progress; the mark of an edited footprint row; the state line. */
20
+ const REPLACEMENT_START = /^-\s+\*\*(?:Проверка шага|Check of step)\s+(\d+\.\d+)\s+(?:заменена|replaced):\*\*/u;
21
+ const EDITED_ROW = '(правится)';
22
+ const STATE_LINE = /^-\s+\*\*(?:State|Состояние):\*\*\s+`([^`]+)`/mu;
23
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
32
24
 
33
- /** The words an epic plan row carried for a task handed to the owner: a row is no longer marked so. */
34
- const OWNER_STEP = 'шаг владельца';
25
+ /** A path under the temporary directories or a device; a word the shell still expands. */
26
+ const TEMP = /^\/(?:private\/)?(?:tmp|var\/folders)(?:\/|$)|^\/dev\//;
27
+ const DYNAMIC = /[$`*?[]|\{[^}"':\s]*(?:,|\.\.)[^}"':\s]*\}/;
28
+ /** The commands that only read what they name; echo and printf name nothing but their redirects. */
29
+ const READERS = new Set('cat head tail less wc grep rg egrep fgrep jq diff cmp ls stat file test [ [[ echo printf awk gawk sed sort cut tr nl uniq column find gh mkdir cd pushd popd export local declare readonly for read true false : basename dirname realpath readlink pwd shasum sha256sum md5 md5sum xxd od cspell du tree chmod pgrep sleep which type date tsc'.split(' '));
30
+ const GIT_READERS = new Set('diff log show status add blame ls-files ls-tree grep rev-parse rev-list cat-file commit merge-base check-ignore diff-tree for-each-ref show-ref branch reflog shortlog describe'.split(' '));
31
+ const COPIES = new Set(['cp', 'mv', 'install', 'ln', 'rsync', 'tar', 'unzip']);
32
+ /** The words before a command that only run it, with their options that take a value. */
33
+ const PREFIXES = { nice: ['-n'], sudo: ['-u', '-g'], timeout: ['-s', '-k'], env: ['-u'], stdbuf: ['-o', '-e', '-i'], xargs: ['-n', '-I', '-L', '-P', '-d', '-s'], npx: ['-p'] };
34
+ for (const word of 'command exec time nohup builtin if then else elif do while until ! {'.split(' ')) PREFIXES[word] = [];
35
+ /** The inside of the string literals of a script: not code. */
36
+ const STRINGS = /'''[\s\S]*?'''|"""[\s\S]*?"""|`(?:\\[\s\S]|[^\\`])*`|'(?:\\.|[^\\'\n])*'|"(?:\\.|[^\\"\n])*"/g;
37
+ /** A call of a script that runs a command: then all its text is read, not only its paths. */
38
+ const RUNS = /(?<!\.)\bexec\w*\s*\(|\b(?:system|popen|spawn\w*)\s*\(|child_process|subprocess/;
39
+ /** A write or a command run in the code of a script; not a write to stdout, nor `.copy()` of a list. */
40
+ const WIDE = new RegExp(
41
+ `${RUNS.source}|\\b(?:writeFile|appendFile|createWriteStream)\\w*\\b|(?<!read(?:File|dir|link)?|exists|stat|lstat|realpath|access)Sync\\s*\\(|(?<!std(?:out|err)\\.)\\bwrite\\w*\\s*\\(|(?:\\b(?:os|shutil|fs|fsp|promises)\\.|(?<![.\\w]))(?:rename|unlink|remove|copy|move|truncate|rmdir|rm|cp|symlink|link|replace)\\w*\\s*\\(|\\bPath\\([^)]*\\)\\.(?:replace|rename|unlink|write_\\w+|\\w+_to)\\s*\\(|\\.touch\\s*\\(|\\bgetattr\\s*\\(|\\bopen\\s+(?:my\\s+)?[$\\w]+\\s*,`
42
+ );
43
+ /** A write call with a literal first argument under a temporary directory, and its handle: no file of the tree. */
44
+ const TEMP_PATH = `\\s*\\(\\s*(?<q>['"])\\/(?:private\\/)?(?:tmp|var\\/folders)\\/[^'"]*\\k<q>`;
45
+ const TEMP_WRITE = new RegExp(`\\b(?:open|writeFile\\w*|appendFile\\w*|createWriteStream)${TEMP_PATH}[^()]*(?:\\((?:[^()]|\\([^()]*\\))*\\)[^()]*)*\\)(?:\\.write\\w*)?`, 'g');
46
+ const TEMP_HANDLE = new RegExp(`(?:(\\w+)\\s*=\\s*|with\\s+)open${TEMP_PATH}[^)]*\\)(?:\\s+as\\s+(\\w+))?`, 'g');
47
+ /** A call of a script that copies, moves or removes a whole directory. */
48
+ const TREE_CALL = /\b(?:cp|copy|rename|rm|move|rmdir)\w*\s*\(|copytree|rmtree/;
35
49
 
36
- /** The opening of a replacement line of the progress, with the number of the step. */
37
- const REPLACEMENT_START = /^-\s+\*\*(?:Проверка шага|Check of step)\s+(\d+\.\d+)\s+(?:заменена|replaced):\*\*/u;
50
+ /** The index of the bracket that closes the one at `at`, quotes skipped. */
51
+ function closing(text, at) {
52
+ let depth = 0;
53
+ for (let i = at; i < text.length; i++) {
54
+ if (text[i] === '\\') i++;
55
+ else if ("'\"`".includes(text[i])) i = text.indexOf(text[i], i + 1) < 0 ? text.length : text.indexOf(text[i], i + 1);
56
+ else if (text[i] === '(') depth++;
57
+ else if (text[i] === ')' && --depth === 0) return i;
58
+ }
59
+ return text.length;
60
+ }
38
61
 
39
- /** The mark of a footprint row the task edits. */
40
- const EDITED_ROW = '(правится)';
62
+ /**
63
+ * The simple commands of a shell text, quotes taken off: { words, redirects, stdin, subs, piped,
64
+ * depth }. A here-document and a here-string are the stdin; `<(…)`, `>(…)`, `$(…)` and backticks the subs.
65
+ */
66
+ export function shellCommands(text) {
67
+ const [commands, docs] = [[], []];
68
+ let [cmd, word, pending, piped, depth] = [null, null, null, false, 0];
69
+ const fresh = () => (cmd = { words: [], redirects: [], stdin: null, subs: [], piped, depth });
70
+ const endWord = () => {
71
+ if (word === null) return;
72
+ if (pending === '<<' || pending === '<<-') docs.push({ delim: word, strip: pending === '<<-', cmd });
73
+ else if (pending === '<<<') cmd.stdin = word;
74
+ else if (pending === '>') cmd.redirects.push(word);
75
+ else if (pending !== '<') cmd.words.push(word);
76
+ [pending, word] = [null, null];
77
+ };
78
+ const endCommand = (pipe) => {
79
+ endWord();
80
+ if (cmd.words.length || cmd.redirects.length || cmd.subs.length) commands.push(cmd);
81
+ piped = pipe;
82
+ fresh();
83
+ };
84
+ fresh();
85
+ for (let i = 0; i < text.length; ) {
86
+ const c = text[i];
87
+ if (c === '\\') {
88
+ if (text[i + 1] !== '\n') word = (word ?? '') + (text[i + 1] ?? '');
89
+ i += 2;
90
+ } else if (c === "'" || c === '"' || (c === '$' && text[i + 1] === "'")) {
91
+ // A double-quoted `$(…)` is kept whole: its own quotes do not end the word.
92
+ const from = c === '$' ? i + 2 : i + 1;
93
+ // A substitution in double quotes is a command of its own: it goes to the subs.
94
+ let j = from;
95
+ while (j < text.length && text[j] !== text[from - 1]) {
96
+ const end = c !== '"' ? -1 : text.startsWith('$(', j) ? closing(text, j + 1) : text[j] === '`' ? text.indexOf('`', j + 1) : -1;
97
+ if (end > j) cmd.subs.push(text.slice(j + (text[j] === '`' ? 1 : 2), end));
98
+ j = c === '"' && text[j] === '\\' ? j + 2 : end > j ? end + 1 : j + 1;
99
+ }
100
+ word = (word ?? '') + (c === '"' ? text.slice(from, j).replace(/\\(["\\$`])/g, '$1') : text.slice(from, j));
101
+ i = j + 1;
102
+ } else if (text.startsWith('$(', i) || c === '`') {
103
+ const end = c === '`' ? text.indexOf('`', i + 1) : closing(text, i + 1);
104
+ if (end > i) cmd.subs.push(text.slice(i + (c === '`' ? 1 : 2), end));
105
+ word = (word ?? '') + text.slice(i, end < 0 ? text.length : end + 1);
106
+ i = end < 0 ? text.length : end + 1;
107
+ } else if (c === '#' && word === null) while (i < text.length && text[i] !== '\n') i++;
108
+ else if (c === '\n') {
109
+ endCommand(false);
110
+ i++;
111
+ for (const doc of docs.splice(0)) {
112
+ const end = new RegExp(`^${doc.strip ? '\\t*' : ''}${escape(doc.delim)}$`, 'm').exec(text.slice(i)) ?? { index: text.length - i, 0: '' };
113
+ doc.cmd.stdin = text.slice(i, i + end.index).replace(/\n$/, '');
114
+ i += end.index + end[0].length + 1;
115
+ }
116
+ } else if (c === ' ' || c === '\t') {
117
+ endWord();
118
+ i++;
119
+ } else if (';|&()'.includes(c) && !(c === '&' && text[i + 1] === '>')) {
120
+ const pair = text[i + 1] === c && c !== '(' && c !== ')';
121
+ endCommand(c === '|' && !pair);
122
+ depth = Math.max(0, depth + (c === '(' ? 1 : c === ')' ? -1 : 0));
123
+ cmd.depth = depth;
124
+ i += pair ? 2 : 1;
125
+ } else if (c === '>' || c === '<' || c === '&') {
126
+ if (word !== null && /^\d+$/.test(word)) word = null;
127
+ endWord();
128
+ const op = text.slice(i).match(/^(?:<<<|<<-|<<|<>|<|&?>>|&?>\|?)/)[0];
129
+ i += op.length;
130
+ if (text[i] === '(') {
131
+ cmd.subs.push(text.slice(i + 1, closing(text, i)));
132
+ i = closing(text, i) + 1;
133
+ } else if (op.endsWith('>') && text[i] === '&' && /[\d-]/.test(text[i + 1] ?? '')) for (i++; /[\d-]/.test(text[i] ?? ''); ) i++;
134
+ else {
135
+ if (text[i] === '&' || text[i] === '!') i++;
136
+ pending = op.includes('>') ? '>' : op;
137
+ }
138
+ } else word = (word ?? '') + text[i++];
139
+ }
140
+ endCommand(false);
141
+ return commands;
142
+ }
41
143
 
42
- /** The state line of the progress. */
43
- const STATE_LINE = /^-\s+\*\*(?:State|Состояние):\*\*\s+`([^`]+)`/mu;
144
+ /** A script writes: a call of a write or of a command in its code, or `open` in a mode other than reading. */
145
+ function scriptWrites(text) {
146
+ const handles = [...text.matchAll(TEMP_HANDLE)].map((match) => match[1] ?? match[3]).filter(Boolean);
147
+ const script = text.replace(TEMP_WRITE, 'read()').replace(handles.length ? new RegExp(`\\b(?:${handles.join('|')})\\.write\\w*\\s*\\(`, 'g') : /^\b$/, 'read(');
148
+ const code = script.replace(STRINGS, (literal) => literal.replace(/[^\n]/g, ' '));
149
+ if (WIDE.test(code) || RUNS.test(script) || /shutil|\bIO\.|\bFile\.(?:open|write)|\[\s*['"]\w*(?:write|append|rename|unlink|rm|cp|copy|truncate|link)\w*['"]\s*\]/i.test(script)) return true;
150
+ return [...code.matchAll(/(\.?)\bopen\s*\(/g)].some((call) => {
151
+ const from = call.index + call[0].length;
152
+ const end = closing(code, from - 1);
153
+ let [k, depth] = [from, 0];
154
+ for (; k < end && !(code[k] === ',' && depth === 0); k++) depth += '([{'.includes(code[k]) ? 1 : ')]}'.includes(code[k]) ? -1 : 0;
155
+ // A method takes the mode first: `Path(p).open('w')`; a function second: `open(p, 'w')`.
156
+ const mode = (call[1] ? script.slice(from, k) : script.slice(k + 1, end)).trim();
157
+ return !(mode === '' || /^(?:['"][rbtU]*['"]|encoding\s*=|errors\s*=|newline\s*=)/.test(mode)) || /mode\s*=\s*['"][^'"]*[wax+]/.test(script.slice(from, end));
158
+ });
159
+ }
44
160
 
45
- /** A shell command that writes: a redirect, a tee, an in-place edit, a copy, a move, a removal or an inline script. */
46
- const WRITE_SIGNS = [
47
- (path) => new RegExp(`>{1,2}\\s*["']?[^\\s;|&"']*${path}`),
48
- (path) => new RegExp(`\\btee\\b[^;|&]*${path}`),
49
- (path) => new RegExp(`\\b(?:sed|perl|awk|gawk)\\b[^;|&]*\\s-i[^;|&]*${path}`),
50
- (path) => new RegExp(`\\b(?:cp|mv|rm|install|rsync|truncate|touch|dd|ln)\\b[^;|&]*${path}`),
51
- (path) => new RegExp(`\\bgit\\s+(?:checkout|restore)\\b[^;|&]*${path}`),
52
- (path) => new RegExp(`\\b(?:python3?|node|ruby|perl)\\b[^;|&]*(?:\\s-[ce]\\b|\\s--eval\\b|\\s-\\s*<<)[\\s\\S]*${path}`),
53
- ];
161
+ /** The word with the variables of the command put in; `mktemp` and `$TMPDIR` are a temporary directory. */
162
+ const expand = (word, vars) =>
163
+ word.replace(/\$\(mktemp\b[^)]*\)/g, '/tmp/mktemp').replace(/^~(?=\/|$)/, '/HOME').replace(/\$(?:\{(\w+)[^}]*\}|(\w+))/g, (all, braced, bare) => ({ TMPDIR: '/tmp', HOME: '/HOME' })[braced ?? bare] ?? vars.get(braced ?? bare) ?? all);
54
164
 
55
- const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
165
+ /** Every tail of a path after a slash: a path of the tree may be written from any directory above it. */
166
+ const tails = (path) => path.split('/').map((_, k, parts) => parts.slice(k).join('/')).filter(Boolean);
167
+
168
+ /**
169
+ * A path lies in a guarded directory: in it, below it when the area ends with a slash, above it when
170
+ * `up`. A relative path counts from the root; an absolute one by a tail, only on an area of two parts.
171
+ */
172
+ const inArea = (path, area, up) => {
173
+ const [dir, deep] = [area.replace(/\/$/, ''), area.endsWith('/')];
174
+ const here = (tail) => (tail === dir && (deep || up)) || (deep && tail.startsWith(`${dir}/`));
175
+ return path.startsWith('/') ? dir.includes('/') && tails(path).some(here) : here(path) || (up && (path === '.' || dir.startsWith(`${path}/`)));
176
+ };
56
177
 
57
- /** The shell command writes into a path matching the pattern (a regular expression source). */
58
- export function shellWrites(command, pathSource) {
59
- return WRITE_SIGNS.some((sign) => sign(pathSource).test(command));
178
+ /** The guarded files of a shell command: the sign of their name in a text, their directories, the reason. */
179
+ function shellGuards(ctx) {
180
+ const marks = posix.normalize(ctx.marksDir);
181
+ const engine = (tail) => ctx.protectedPaths.some((source) => new RegExp(source).test(tail));
182
+ const shell = 'by the edit tool, not by a shell command';
183
+ const name = (text) => text.split(/[\s;|&<>'"()=,`{}]+/).flatMap((token) => tails(token.replace(/^\.\//, ''))).find(engine);
184
+ // The directory of a pattern: all of it when the pattern ends with a slash, else only its own files.
185
+ const head = (source) => source.replace(/^\^|^\(\?:\^\|\/\)/, '').match(/^[\w./-]*/)[0];
186
+ const area = (source) => (head(source).endsWith('/') ? head(source) : head(source).replace(/\/?[^/]*$/, ''));
187
+ return [
188
+ [new RegExp(`rt-kit/(?:steps|approval)|${escape(marks)}`), [`${marks}/`, 'rt-kit/steps/', 'rt-kit/approval/'], () => 'the marks of the steps and of the approval are written only by the engine `task-flow-script.mjs`, never by a shell command'],
189
+ [/\.claude\/projects\/\S*(?:\.jsonl\b|\*)/, ['.claude/projects/'], () => 'the session records are written only by the harness, never by a shell command: an approval is read from them'],
190
+ [new RegExp(`(?:^|[^\\w.-])(?:progress|plan)\\.md(?![\\w.-])|${escape(ctx.tasksDir)}/\\S*[*?[]`, 'i'),[`${ctx.tasksDir}/`], () => `the progress and the plan are edited ${shell}: the guard judges an edit, and a shell write passes it unseen`],
191
+ [new RegExp(`(?:^|[^\\w.-])${escape(ctx.plansDir)}/`), [`${ctx.plansDir}/`], () => `the epic plan is edited ${shell}: «отложено» in it needs the owner's word, and a shell write passes it unseen`],
192
+ [{ exec: (text) => (name(text) ? [name(text)] : null) }, ctx.protectedPaths.map(area).filter(Boolean), (path) => judgeProtected(path, ctx, `${ctx.tasksDir}/${ctx.branch}/plan.md`)],
193
+ [new RegExp(`${escape(posix.dirname(ctx.overridePath))}/`), [`${posix.dirname(ctx.overridePath)}/`], () => `the override of the description is edited ${shell}, and only by the owner's word naming the key`],
194
+ ];
195
+ }
196
+
197
+ /** The paths a script names: its literals with no space in them but what it imports, its globs when it globs. */
198
+ const literals = (script) =>
199
+ (script.replace(/\b(?:from|import\s*\(|require\s*\()\s*(['"`])[^'"`]*\1/g, '').match(STRINGS) ?? []).map((literal) => literal.replace(/^('''|"""|['"`])([\s\S]*)\1$/, '$2')).filter((literal) => literal && !/\s/.test(literal) && (!/[*?[]/.test(literal) || /glob|readdir|listdir|walk|scandir|Dir\[/.test(script))).join(' ');
200
+
201
+ /**
202
+ * The verdict on a shell command, simple command by simple command, variables of the command put in; a
203
+ * script the command wrote is judged, a script it did not write is code of the tree and reads.
204
+ */
205
+ function judgeShell(command, ctx, level = 0, vars = new Map(), cwd = '.') {
206
+ const guards = shellGuards(ctx);
207
+ const written = new Map();
208
+ // A function the command defines runs its body, and the body is judged as commands of its own.
209
+ const defined = new Set([...command.matchAll(/(?:^|[\s;&|({])(?:function\s+)?([\w-]+)\s*\(\)\s*\{/g)].map((match) => match[1]));
210
+ const cwds = [cwd];
211
+ let pipeline = '';
212
+ for (const unit of shellCommands(command)) {
213
+ cwds.length = Math.min(cwds.length, unit.depth + 1);
214
+ while (cwds.length <= unit.depth) cwds.push(cwds.at(-1));
215
+ // The path of a word; of a word the shell expands, the directory before it — none after an unknown variable.
216
+ let base = cwds[unit.depth];
217
+ const at = (word) => {
218
+ const text = expand(word, vars);
219
+ const cut = text.search(DYNAMIC);
220
+ const slash = text.lastIndexOf('/', cut);
221
+ if (cut >= 0 && (text.includes('..') || (slash < 0 && /[$`]/.test(text[cut])))) return null;
222
+ const path = cut < 0 ? text : text.slice(0, slash + 1);
223
+ return path.startsWith('/') || base !== null ? posix.normalize(posix.join(path.startsWith('/') ? '/' : base, path)).replace(/(.)\/$/, '$1') : null;
224
+ };
225
+ // A temporary path names nothing, save a session record: the records of a session may lie there.
226
+ const spared = (word) => at(word) !== null && TEMP.test(at(word)) && !guards[1][0].test(expand(word, vars));
227
+ let words = unit.words.map((word) => expand(word, vars));
228
+ for (const word of words) {
229
+ const set = word.match(/^(\w+)=([\s\S]*)$/);
230
+ if (set) vars.set(set[1], set[2]);
231
+ else if (!['export', 'local', 'declare', 'readonly'].includes(word)) break;
232
+ }
233
+ if (words[0] === 'for' && words[2] === 'in') vars.set(words[1], words.slice(3).join(' '));
234
+ let fed = false;
235
+ while (words.length > 0 && (Object.hasOwn(PREFIXES, posix.basename(words[0])) || /^\w+=/.test(words[0]) || (/^p?npm$/.test(words[0]) && /^(?:exec|dlx)$/.test(words[1])))) {
236
+ const head = posix.basename(words.shift());
237
+ if (/^p?npm$/.test(head)) words.shift();
238
+ while (words[0]?.startsWith('-')) if ((PREFIXES[head] ?? []).includes(words.shift())) words.shift();
239
+ if (head === 'timeout') words.shift();
240
+ fed ||= head === 'xargs';
241
+ }
242
+ const name = posix.basename(words[0] ?? '');
243
+ const args = words.slice(1);
244
+ const operands = args.filter((arg) => !arg.startsWith('-'));
245
+ const fromPipe = unit.piped ? pipeline : '';
246
+ pipeline = `${unit.piped ? `${pipeline} ` : ''}${args.join(' ')} ${unit.stdin ?? ''}`;
247
+ if (name === 'cd' || name === 'pushd' || name === 'popd') cwds[unit.depth] = name === 'popd' || operands[0] === '-' ? null : at(operands[0] ?? '~');
248
+ if (name === 'git' && args.includes('-C')) base = at(args[args.indexOf('-C') + 1] ?? '');
249
+ const flag = (sign) => args.some((arg) => sign.test(arg));
250
+ // A runner: the script inline, from a here-document, a pipe or a file this command wrote.
251
+ const runsWritten = written.has(at(words[0] ?? '') ?? '');
252
+ const shellRunner = /^(?:bash|sh|zsh|source|\.|eval)$/.test(name) || runsWritten;
253
+ const interpreter = /^(?:python[\d.]*|node|nodejs|ruby|perl|deno|bun)$/.test(name);
254
+ const argv = [...args];
255
+ let [script, trusted, params] = [null, false, []];
256
+ if (shellRunner || interpreter) {
257
+ const inline = args.findIndex((arg) => /^-[a-zA-Z]*[ce]$/.test(arg) || ['--eval', '-p', '--print'].includes(arg));
258
+ const file = runsWritten ? words[0] : operands[0];
259
+ if (name === 'eval') script = args.join(' ');
260
+ else if (inline >= 0) [script, params] = [(argv.splice(inline + 1, 1)[0] ?? '').replaceAll('{}', fed ? fromPipe.trim() : '{}'),shellRunner ? args.slice(inline + 2) : []];
261
+ else if (file && file !== '-') [script, trusted, params] = [written.get(at(file)) ?? null, !written.has(at(file)) && !flag(/^-m$/), runsWritten ? [words[0], ...operands] : operands];
262
+ else script = unit.stdin ?? (unit.piped ? fromPipe : null);
263
+ }
264
+ // A shell script is a command of its own, its positional parameters put in; so is what find runs.
265
+ const [option, exec] = [args.findIndex((arg) => /^[-(!]/.test(arg)), name === 'find' ? args.findIndex((arg) => /^-(?:exec|execdir|ok|okdir)$/.test(arg)) : -1];
266
+ const [starts, quote] = [option < 0 ? args : args.slice(0, option), (arg) => (/^[\w./=@%+:,-]*$/.test(arg) ? arg : `'${arg.replaceAll("'", `'\\''`)}'`)];
267
+ const found = exec < 0 ? [] : [args.slice(exec + 1).filter((arg, k, list) => !list.slice(0, k + 1).some((one) => one === ';' || one === '+')).map((arg) => quote(arg.replaceAll('{}', starts.map((start) => `${start}/*`).join(' ')))).join(' ')];
268
+ for (const inner of [...unit.subs, ...found, ...(shellRunner && script !== null && level < 3 ? [script] : [])]) {
269
+ const verdict = judgeShell(inner, ctx, level + 1, new Map([...vars, ...params.map((value, k) => [String(k), value])]), base);
270
+ if (verdict) return verdict;
271
+ }
272
+ const data = name === 'echo' || name === 'printf';
273
+ const content = unit.stdin ?? (data ? args.join(' ') : null);
274
+ for (const target of [...unit.redirects, ...(name === 'tee' ? operands : [])]) if (at(target) !== null) written.set(at(target), content ?? fromPipe);
275
+ // The names: the words, the redirects, the names a copy lands in its target, the script — of a
276
+ // script that runs no command only the paths it names — and the words piped into xargs. A
277
+ // here-document of a command that is not a runner is the text it writes, not a name; so are
278
+ // the words of echo and printf.
279
+ const shown = interpreter && script !== null && !RUNS.test(script) ? literals(script) : script;
280
+ const target = args.find((arg, k) => ['-t', '-C', '-d', '--target-directory'].includes(args[k - 1])) ?? args.find((arg) => arg.startsWith('--target-directory='))?.slice(19);
281
+ const into = target ?? (operands.length > 1 && !['tar', 'unzip'].includes(name) ? operands.at(-1) : null);
282
+ const landed = COPIES.has(name) && into ? operands.filter((word) => word !== into).map((word) => posix.join(into, posix.basename(word))) : [];
283
+ const pieces = [...(data ? [] : argv), ...landed, ...unit.redirects.map((word) => expand(word, vars)), trusted ? '' : (shown ?? ''), fed ? fromPipe : ''];
284
+ const tokens = pieces.join(' ').split(/\s+/).filter(Boolean);
285
+ const text = tokens.flatMap((token) => (spared(token) ? [] : at(token) !== null && at(token) !== token && !token.startsWith('/') ? [token, at(token)] : [token])).join(' ');
286
+ const named = guards.filter(([sign]) => sign.exec(text));
287
+ // A write whose target is not a literal path is named in the refusal: the target first, then the rest.
288
+ const loose = [...unit.redirects, into ?? '', ...argv.filter((arg) => !arg.startsWith('-'))].map((word) => expand(word, vars)).find((word) => DYNAMIC.test(word));
289
+ const refuse = (by, path) => {
290
+ const reason = by[2](path ?? by[0].exec(text)?.[0]);
291
+ return reason && loose ? `${reason} — \`${loose}\` is not a literal path: write the path as a literal` : reason;
292
+ };
293
+ // The directories a copy, a move, a removal or a checkout writes into, and whether it reaches below.
294
+ // A copy of named files is judged by the names it lands; a tree, or a source the shell expands, by its target.
295
+ // A whole task folder is removed or moved away as the taking-apart does, and made from the template
296
+ // when it does not stand yet; a write into a standing folder from anything else is judged below.
297
+ const [taskFolder, template] = [`(?!_template$)[^/]+$`, '_template(?:/|$)'].map((tail) => (word) => new RegExp(`(?:^|/)${escape(ctx.tasksDir)}/${tail}`).test((DYNAMIC.test(expand(word, vars)) ? expand(word, vars) : at(word)) ?? ''));
298
+ const sources = operands.filter((word) => word !== into);
299
+ if (name === 'cp' && into && taskFolder(into) && sources.every(template) && !ctx.read?.(`${at(into)}/progress.md`)) continue;
300
+ const sub = name === 'git' ? args.find((arg, k) => !arg.startsWith('-') && !['-C', '-c'].includes(args[k - 1])) : null;
301
+ const staged = flag(/^(?:--staged|-S)$/) && !flag(/^(?:--worktree|-W)$/);
302
+ const recursive = flag(/^-[a-zA-Z]*[rRa]|^--(?:recursive|archive)$/) || ['rsync', 'tar', 'unzip'].includes(name);
303
+ const mode = name === 'tar' ? args.filter((arg, k) => /^-[a-zA-Z]+$/.test(arg) || (k === 0 && /^[a-zA-Z]+$/.test(arg))).join('') : '';
304
+ const listing = (name === 'tar' && /[tO]/.test(mode)) || (name === 'unzip' && flag(/^-[lpvZ]/));
305
+ const dirs = [];
306
+ const folder = (word) => !/\.\w+$/.test(word);
307
+ const unnamed = recursive || sources.some((word) => DYNAMIC.test(word) || (name === 'mv' && folder(word))) || into === null;
308
+ const moved = name === 'mv' && sources.length > 0 && sources.every(taskFolder);
309
+ if (COPIES.has(name) && unnamed && !listing && !moved && (name !== 'tar' || /x/.test(mode))) dirs.push([into ?? (['tar', 'unzip'].includes(name) ? '.' : null), recursive]);
310
+ if (name === 'mv') dirs.push(...sources.filter((word) => folder(word) && !taskFolder(word)).map((word) => [word, true]));
311
+ if (name === 'rm' && recursive) dirs.push(...operands.filter((word) => !taskFolder(word)).map((word) => [word, true]));
312
+ if (name === 'find' && flag(/^-(?:delete|fprint)/)) dirs.push(...starts.map((word) => [word, true]));
313
+ // A git path: every word after `--`; before it, a word with a slash or one that holds a guarded directory.
314
+ const dash = args.indexOf('--');
315
+ const gitPaths = dash >= 0 ? args.slice(dash + 1) : operands.slice(operands.indexOf(sub) + 1).filter((arg) => !/^[\w.~^@{}-]+$/.test(arg) || arg === '.' || guards.some(([, list]) => list.some((one) => inArea(at(arg) ?? '', one, true))));
316
+ if (sub === 'checkout' || (sub === 'restore' && !staged) || sub === 'clean') dirs.push(...(gitPaths.length || sub !== 'clean' ? gitPaths : ['.']).filter(folder).map((word) => [word, true]));
317
+ // A script that copies or removes a directory and names a task folder itself writes into the folder.
318
+ if (interpreter && script !== null && TREE_CALL.test(script.replace(STRINGS, '""'))) dirs.push(...(text.match(new RegExp(`${escape(ctx.tasksDir)}/[^/\\s'"]+(?=/?['"\\s]|/?$)`, 'g')) ?? []).map((word) => [word, false]));
319
+ // An in-place edit of sed, awk, perl or ruby writes the files it names, not its expression.
320
+ const inPlace = /^(?:g?sed|g?awk|perl|ruby)$/.test(name) && flag(/^-[a-zA-Z0-9]*i|^--in-place|^inplace$/);
321
+ const expressions = args.filter((arg, k) => /^-[a-zA-Z]*e$|^--expression$/.test(args[k - 1] ?? ''));
322
+ const edited = [...operands.filter((arg) => arg && arg !== 'inplace' && !expressions.includes(arg)).slice(expressions.length || interpreter ? 0 : 1), ...(fed ? fromPipe.split(/\s+/).filter(Boolean) : [])];
323
+ // A write target the shell still expands is judged by the directory it lies in.
324
+ dirs.push(...[...unit.redirects, ...(inPlace ? edited : []), ...(name === 'rm' ? operands : [])].filter((word) => DYNAMIC.test(expand(word, vars))).map((word) => [word, false]));
325
+ // awk that prints into a file or runs a command, and sed with a `w` command, write.
326
+ const scripted = (/^g?awk$/.test(name) && flag(/printf?[^;}]*>|system\s*\(|\|\s*"/)) || (/^g?sed$/.test(name) && flag(/(?:^|[;{}\n]|\/[gpiIme0-9]*)\s*w\s+\S/));
327
+ const archive = args[args.findIndex((arg) => /^-?[a-zA-Z]*f$/.test(arg)) + 1] ?? '';
328
+ const reads = READERS.has(name) ? !scripted && !(name === 'sort' && flag(/^-o|^--output/)) && !(name === 'find' && flag(/^-(?:delete|fprint)/))
329
+ : name === 'git' ? GIT_READERS.has(sub) || (sub === 'restore' && staged) || (sub === 'reset' && !flag(/^--(?:hard|merge|keep)$/))
330
+ : ['cp', 'install', 'ln', 'rsync'].includes(name) ? into !== null && spared(into)
331
+ : name === 'tar' || name === 'unzip' ? listing || (/c/.test(mode) && spared(archive))
332
+ : ['prettier', 'eslint', 'markdownlint', 'markdownlint-cli2', 'iconv'].includes(name) ? !flag(/^(?:-w|--write|--fix\b.*|-o|--output\b.*)$/)
333
+ : shellRunner || interpreter ? trusted || (script !== null && (shellRunner || !scriptWrites(script)))
334
+ : name === '' || defined.has(name);
335
+ const reader = unit.redirects.every(spared) && (inPlace ? edited.every(spared) : reads);
336
+ if (fed && !reader) dirs.push(...fromPipe.split(/\s+/).filter(Boolean).map((word) => [word, true]));
337
+ const why = reader ? null : named.map((by) => refuse(by)).find(Boolean);
338
+ if (why) return why;
339
+ for (const [dir, up] of dirs) {
340
+ const path = dir === null ? null : at(dir);
341
+ const areas = path === null ? named : TEMP.test(path) ? [] : guards.filter(([, list]) => list.some((one) => inArea(path, one, up)));
342
+ const refused = areas.map((by) => refuse(by, path ?? undefined)).find(Boolean);
343
+ if (refused) return refused;
344
+ }
345
+ }
346
+ return null;
60
347
  }
61
348
 
62
349
  /** The text an edit leaves: Write gives it whole, Edit and MultiEdit replace in the text before. */
63
350
  export function textAfter(call, before) {
64
351
  if (call.tool === 'Write') return call.content ?? '';
65
- let text = before ?? '';
66
- for (const edit of call.edits ?? []) {
67
- if (edit.replaceAll) text = text.split(edit.oldString).join(edit.newString);
68
- else text = text.replace(edit.oldString, () => edit.newString);
69
- }
70
- return text;
352
+ const apply = (text, edit) => (edit.replaceAll ? text.split(edit.oldString).join(edit.newString) : text.replace(edit.oldString, () => edit.newString));
353
+ return (call.edits ?? []).reduce(apply, before ?? '');
71
354
  }
72
355
 
73
356
  /** The done and current marks of the progress are in order: done steps first, the current right after. */
@@ -75,8 +358,7 @@ export function marksOutOfOrder(progress) {
75
358
  const { steps } = stepsOfProgress(progress);
76
359
  let open = false;
77
360
  for (const step of steps) {
78
- if (step.mark === 'x' && open) return `step ${step.number} is marked done after a step that is not done`;
79
- if (step.mark === '>' && open) return `step ${step.number} is marked current after a step that is not done`;
361
+ if (open && (step.mark === 'x' || step.mark === '>')) return `step ${step.number} is marked ${step.mark === 'x' ? 'done' : 'current'} after a step that is not done`;
80
362
  if (step.mark !== 'x') open = true;
81
363
  }
82
364
  return null;
@@ -93,106 +375,58 @@ export const declaredState = (text) => text?.match(STATE_LINE)?.[1] ?? null;
93
375
 
94
376
  /** The task numbers of the epic plan lines whose «отложено» the edit sets or lifts. */
95
377
  export function deferChanges(before, after, key) {
96
- const deferredTasks = (text) => {
97
- const tasks = new Set();
98
- for (const line of (text ?? '').split('\n')) {
99
- if (!line.includes(DEFERRED)) continue;
100
- for (const match of line.matchAll(new RegExp(`${escape(key)}-(\\d+)`, 'g'))) tasks.add(match[1]);
101
- }
102
- return tasks;
103
- };
104
- const was = deferredTasks(before);
105
- const now = deferredTasks(after);
378
+ const numbers = (line) => [...line.matchAll(new RegExp(`${escape(key)}-(\\d+)`, 'g'))].map((match) => match[1]);
379
+ const deferredTasks = (text) => new Set((text ?? '').split('\n').filter((line) => line.includes(DEFERRED)).flatMap(numbers));
380
+ const [was, now] = [deferredTasks(before), deferredTasks(after)];
106
381
  return [...new Set([...was, ...now])].filter((task) => was.has(task) !== now.has(task));
107
382
  }
108
383
 
109
384
  /** The lines of the text after the edit that match the sign and did not stand in the text before. */
110
- const newLines = (before, after, sign) => {
111
- const was = new Set((before ?? '').split('\n').map((line) => line.trim()));
112
- return (after ?? '').split('\n').filter((line) => sign(line) && !was.has(line.trim()));
113
- };
385
+ const newLines = (before, after, sign) => ((was) => (after ?? '').split('\n').filter((line) => sign(line) && !was.has(line.trim())))(new Set((before ?? '').split('\n').map((line) => line.trim())));
114
386
 
115
- /**
116
- * The step numbers whose replacement line the edit adds or changes. A removed line is not counted:
117
- * dropping a replacement gives the check of the plan back and needs no word of the owner.
118
- */
119
- export function replacementChanges(before, after) {
120
- return [...new Set(newLines(before, after, (line) => REPLACEMENT_START.test(line)).map((line) => line.match(REPLACEMENT_START)[1]))];
121
- }
387
+ /** The step numbers whose replacement line the edit adds or changes; dropping one needs no owner's word. */
388
+ export const replacementChanges = (before, after) => [...new Set(newLines(before, after, (line) => REPLACEMENT_START.test(line)).map((line) => line.match(REPLACEMENT_START)[1]))];
122
389
 
123
- /**
124
- * The task numbers of the epic plan rows the edit marks «шаг владельца». The mark is refused: the
125
- * step is the executor's. A row that leaves the mark is not counted: the task goes back to the work.
126
- */
390
+ /** The tasks of the epic plan rows the edit marks «шаг владельца» (refused: the step is the executor's). */
127
391
  export function ownerRowChanges(before, after, key) {
128
392
  const marked = (text) => new RegExp(`\\|\\s*${OWNER_STEP}[^|]*\\|?\\s*$`, 'u').test(text);
129
393
  const numbers = (line) => [...line.matchAll(new RegExp(`${escape(key)}-(\\d+)`, 'g'))].map((match) => match[1]);
130
394
  // A row that carried the mark before the edit is a legacy row: its other cells may be edited.
131
395
  const legacy = new Set((before ?? '').split('\n').filter(marked).flatMap(numbers));
132
- const tasks = new Set();
133
- for (const line of newLines(before, after, marked)) {
134
- for (const task of numbers(line)) if (!legacy.has(task)) tasks.add(task);
135
- }
136
- return [...tasks];
396
+ return [...new Set(newLines(before, after, marked).flatMap(numbers))].filter((task) => !legacy.has(task));
137
397
  }
138
398
 
139
399
  /** The keys an edit of the override changes: `key:` of every line that differs. */
140
400
  export function changedKeys(before, after) {
141
401
  const lines = (text) => new Set((text ?? '').split('\n').map((line) => line.trim()).filter(Boolean));
142
- const was = lines(before);
143
- const now = lines(after);
402
+ const [was, now] = [lines(before), lines(after)];
144
403
  const changed = [...[...now].filter((line) => !was.has(line)), ...[...was].filter((line) => !now.has(line))];
145
- const keys = new Set();
146
- for (const line of changed) {
147
- const key = line.match(/^['"]?([A-Za-z_][\w-]*)['"]?\s*:/)?.[1];
148
- if (key && key !== 'reason') keys.add(key);
149
- }
404
+ const keys = new Set(changed.map((line) => line.match(/^['"]?([A-Za-z_][\w-]*)['"]?\s*:/)?.[1]).filter((key) => key && key !== 'reason'));
150
405
  return { keys: [...keys], reasons: changed.filter((line) => now.has(line)).map((line) => line.match(/^reason\s*:\s*['"](.+)['"],?$/)?.[1]).filter(Boolean) };
151
406
  }
152
407
 
153
408
  /** The paths of the footprint rows marked «(правится)»: every path in backticks of such a row. */
154
409
  export function editedPaths(plan) {
155
- const paths = [];
156
- for (const line of (plan ?? '').split('\n')) {
157
- if (!line.startsWith('|') || !line.split('|')[1]?.includes(EDITED_ROW)) continue;
158
- for (const match of line.matchAll(/`([^`\s]+)`/g)) paths.push(match[1]);
159
- }
160
- return paths;
410
+ const rows = (plan ?? '').split('\n').filter((line) => line.startsWith('|') && line.split('|')[1]?.includes(EDITED_ROW));
411
+ return rows.flatMap((line) => [...line.matchAll(/`([^`\s]+)`/g)].map((match) => match[1]));
161
412
  }
162
413
 
163
- /**
164
- * The path is named by a footprint path: the same file, a directory that holds it, or a bare file
165
- * name equal to its last part — a footprint row lists the files of one directory by name.
166
- */
414
+ /** The path is named by a footprint path: the same file, a directory that holds it, or its bare file name. */
167
415
  export const namedBy = (path, paths) =>
168
416
  paths.some((named) => path === named || (named.endsWith('/') && path.startsWith(named)) || (!named.includes('/') && path.split('/').pop() === named));
169
417
 
170
418
  /**
171
- * The verdict on one call: the reason of a refusal, or null.
172
- *
173
- * `call` — { tool, path, content, edits, command } with `path` relative to the root of the tree.
174
- * `ctx`:
175
- * branch, key the checked-out branch and the task key of the tree
176
- * tasksDir, plansDir where the task folders and the epic plans lie, relative to the root
177
- * marksDir the directory of the marks relative to the root, or an absolute path
178
- * protectedPaths patterns (regular expression sources) of the description and the engine
179
- * overridePath the tree override of the description, relative to the root
180
- * legacy `words.legacyBranches`
181
- * read(path) the text of a file of the working copy, or null
182
- * stepMark(number) the mark of a step of the branch, or null
183
- * approved() the plan of the branch carries the approval mark
184
- * ownerLast() the owner's last word: a typed message or the chosen options of a menu
185
- * stateIndex(name) the place of a state in the scenario, or -1
186
- * measured() the index of the measured state, or null when it cannot be measured
419
+ * The verdict on one call: the reason of a refusal, or null. `call` — { tool, path, content, edits,
420
+ * command }, `path` relative to the root of the tree. `ctx`: `branch` and `key` of the tree;
421
+ * `tasksDir` and `plansDir` relative to the root; `marksDir` relative or absolute; `protectedPaths`,
422
+ * the patterns of the description and the engine; `overridePath`; `legacy`, `words.legacyBranches`;
423
+ * `read(path)`, a file of the working copy or null; `stepMark(number)`; `approved()`, the approval
424
+ * mark of the plan; `ownerLast()`, the owner's typed message or chosen options; `stateIndex(name)`,
425
+ * the place of a state or -1; `measured()`, the index of the measured state or null.
187
426
  */
188
427
  export function judgeCall(call, ctx) {
189
- const folder = `${ctx.tasksDir}/${ctx.branch}`;
190
- const progressPath = `${folder}/progress.md`;
191
- const planPath = `${folder}/plan.md`;
192
- const marks = escape(ctx.marksDir);
193
-
194
- if (call.tool === 'Bash') return judgeShell(call.command ?? '', ctx, marks);
195
-
428
+ const [progressPath, planPath] = ['progress', 'plan'].map((name) => `${ctx.tasksDir}/${ctx.branch}/${name}.md`);
429
+ if (call.tool === 'Bash') return judgeShell(call.command ?? '', ctx);
196
430
  const path = call.path ?? '';
197
431
  if (path.startsWith(`${ctx.marksDir}/`) || path === ctx.marksDir) return 'the marks of the steps and of the approval are written only by the engine `task-flow-script.mjs`';
198
432
  if (ctx.isRecord && ctx.isRecord(path)) return 'the session records are written only by the harness: an approval is read from them, and a hand write would forge it';
@@ -203,53 +437,21 @@ export function judgeCall(call, ctx) {
203
437
  return null;
204
438
  }
205
439
 
206
- function judgeShell(command, ctx, marks) {
207
- const engine = /task-flow-script\.mjs/.test(command);
208
- if (!engine && (shellWrites(command, marks) || shellWrites(command, 'rt-kit/(?:steps|approval)/'))) {
209
- return 'the marks of the steps and of the approval are written only by the engine `task-flow-script.mjs`, never by a shell command';
210
- }
211
- if (shellWrites(command, '\\.claude/projects/[^\\s;|&"\']*\\.jsonl')) {
212
- return 'the session records are written only by the harness, never by a shell command: an approval is read from them';
213
- }
214
- if (shellWrites(command, `${escape(ctx.tasksDir)}/[^\\s;|&]*(?:progress|plan)\\.md`) || shellWrites(command, '(?:^|[\\s/"\'])(?:progress|plan)\\.md')) {
215
- return 'the progress and the plan are edited by the edit tool, not by a shell command: the guard judges an edit, and a shell write passes it unseen';
216
- }
217
- if (shellWrites(command, `${escape(ctx.plansDir)}/`)) {
218
- return 'the epic plan is edited by the edit tool, not by a shell command: «отложено» in it needs the owner\'s word, and a shell write passes it unseen';
219
- }
220
- const written = command
221
- .split(/[\s;|&<>'"]+/)
222
- .map((token) => token.replace(/^\.\//, ''))
223
- .find((token) => ctx.protectedPaths.some((source) => new RegExp(source).test(token)) && shellWrites(command, escape(token)));
224
- if (written) return judgeProtected(written, ctx, `${ctx.tasksDir}/${ctx.branch}/plan.md`);
225
- if (shellWrites(command, escape(ctx.overridePath))) return 'the override of the description is edited by the edit tool, and only by the owner\'s word naming the key';
226
- return null;
227
- }
228
-
229
440
  function judgeProgress(call, ctx, planPath) {
230
441
  const before = ctx.read(call.path);
231
442
  const after = textAfter(call, before);
232
443
  const order = marksOutOfOrder(after);
233
444
  if (order) return `${order}: done steps go first, and the one current step right after them`;
234
-
235
445
  // The plan as the commit that added it wrote it: a plan stripped of its checks in the working copy
236
446
  // lifts nothing. Before that commit there is no approved plan, and the working copy is all there is.
237
447
  const plan = (ctx.committed ? ctx.committed(planPath) : null) ?? ctx.read(planPath);
238
448
  const legacy = ctx.legacy.includes(ctx.branch) || stepsOfPlan(plan ?? '').every((step) => step.command === null);
239
- if (!legacy) {
240
- const marked = newlyDone(before, after);
241
- if (marked.length > 0) {
242
- return `step ${marked.join(', ')} is marked done after its check matched, by \`node tools/task-flow-script.mjs step ${marked[0]}\` itself: a hand mark is refused whatever mark lies on disk`;
243
- }
244
- }
245
-
449
+ const marked = legacy ? [] : newlyDone(before, after);
450
+ if (marked.length > 0) return `step ${marked.join(', ')} is marked done after its check matched, by \`node tools/task-flow-script.mjs step ${marked[0]}\` itself: a hand mark is refused whatever mark lies on disk`;
246
451
  const state = declaredState(after);
247
- if (state && state !== declaredState(before)) {
248
- const declared = ctx.stateIndex(state);
249
- const measured = ctx.measured();
250
- if (declared >= 0 && measured !== null && declared > measured) {
251
- return `the state \`${state}\` is ahead of the measured one: the engine measures the branch below it — \`node tools/task-flow-script.mjs measure\` names the exit that is not met`;
252
- }
452
+ const [declared, measured] = state && state !== declaredState(before) ? [ctx.stateIndex(state), ctx.measured()] : [-1, null];
453
+ if (declared >= 0 && measured !== null && declared > measured) {
454
+ return `the state \`${state}\` is ahead of the measured one: the engine measures the branch below it — \`node tools/task-flow-script.mjs measure\` names the exit that is not met`;
253
455
  }
254
456
  const replaced = replacementChanges(before, after);
255
457
  if (replaced.length > 0) {