@rt-tools/agent-kit 0.29.4 → 0.30.1

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 (81) hide show
  1. package/assets/checks/board-epics.github.mjs +17 -2
  2. package/assets/checks/board-folders.mjs +40 -1
  3. package/assets/checks/board-runs.github.mjs +7 -2
  4. package/assets/checks/board.github.mjs +23 -3
  5. package/assets/checks/check-board.github.mjs +2 -1
  6. package/assets/checks/check-prose-style.mjs +6 -2
  7. package/assets/checks/spec-anchors.mjs +5 -1
  8. package/assets/checks/task-new-queue.github.mjs +51 -0
  9. package/assets/checks/task-new.github.mjs +4 -41
  10. package/assets/defaults/gate-map.sh +4 -1
  11. package/assets/defaults/shell.sh +6 -2
  12. package/assets/hooks/claim-guard.sh +42 -13
  13. package/assets/hooks/epic-stop-guard.sh +31 -1
  14. package/assets/hooks/git-guard-delivery-epic.sh +11 -1
  15. package/assets/hooks/git-guard-delivery-tree.sh +29 -0
  16. package/assets/hooks/git-guard-delivery.sh +6 -6
  17. package/assets/hooks/git-guard-push-tests.sh +10 -1
  18. package/assets/hooks/grill-gate-bypass.sh +61 -0
  19. package/assets/hooks/grill-gate.sh +144 -4
  20. package/assets/hooks/proposal-guard.sh +3 -0
  21. package/assets/hooks/turn-exit-guard.sh +3 -3
  22. package/assets/hooks/turn-exit-verdict.sh +18 -1
  23. package/assets/hooks/write-targets.sh +69 -3
  24. package/assets/patterns/admin-nav-item.md +2 -1
  25. package/assets/patterns/browser-verification-stand.md +3 -0
  26. package/assets/patterns/doc-style-human.md +21 -0
  27. package/assets/patterns/git-workflow-commit.azure.md +4 -0
  28. package/assets/patterns/git-workflow-commit.github.md +15 -0
  29. package/assets/patterns/git-workflow-commit.gitlab.md +4 -0
  30. package/assets/patterns/git-workflow-docker.md +4 -2
  31. package/assets/patterns/git-workflow-merge.md +6 -0
  32. package/assets/patterns/git-workflow-pr-body.github.md +4 -0
  33. package/assets/patterns/queue-audit-read.github.md +47 -0
  34. package/assets/patterns/spec-driven-domain.md +12 -0
  35. package/assets/patterns/spec-driven-rule.md +8 -2
  36. package/assets/patterns/task-flow-close.md +11 -9
  37. package/assets/patterns/task-flow-start.md +21 -22
  38. package/assets/patterns/testing-e2e.md +16 -2
  39. package/assets/patterns/testing-unit.md +4 -0
  40. package/assets/pitfalls/doc-style.md +8 -0
  41. package/assets/pitfalls/styling-bem.md +11 -0
  42. package/assets/pitfalls/turn-conduct.md +14 -0
  43. package/assets/rules/browser-verification.md +7 -5
  44. package/assets/rules/component-structure.md +8 -0
  45. package/assets/rules/deploy-flow.github.md +28 -2
  46. package/assets/rules/doc-style.md +20 -3
  47. package/assets/rules/git-workflow.azure.md +4 -0
  48. package/assets/rules/git-workflow.github.md +8 -25
  49. package/assets/rules/git-workflow.gitlab.md +4 -0
  50. package/assets/rules/lib-layers.md +2 -2
  51. package/assets/rules/queue-audit.github.md +77 -0
  52. package/assets/rules/reuse-first.md +7 -0
  53. package/assets/rules/shared-code.md +3 -0
  54. package/assets/rules/spec-driven.md +3 -1
  55. package/assets/rules/status-report.md +6 -0
  56. package/assets/rules/task-flow.md +18 -21
  57. package/assets/rules/testing.md +7 -1
  58. package/assets/rules/turn-conduct.md +27 -26
  59. package/lib/commands.d.ts.map +1 -1
  60. package/lib/commands.js +12 -2
  61. package/lib/commands.js.map +1 -1
  62. package/lib/hooks-map.d.ts +14 -0
  63. package/lib/hooks-map.d.ts.map +1 -1
  64. package/lib/hooks-map.js +55 -8
  65. package/lib/hooks-map.js.map +1 -1
  66. package/lib/proposals.d.ts.map +1 -1
  67. package/lib/proposals.js +9 -1
  68. package/lib/proposals.js.map +1 -1
  69. package/lib/ship.d.ts +9 -0
  70. package/lib/ship.d.ts.map +1 -1
  71. package/lib/ship.js +16 -0
  72. package/lib/ship.js.map +1 -1
  73. package/lib/shipment.d.ts.map +1 -1
  74. package/lib/shipment.js +30 -29
  75. package/lib/shipment.js.map +1 -1
  76. package/lib/sync.d.ts +9 -0
  77. package/lib/sync.d.ts.map +1 -1
  78. package/lib/sync.js +6 -1
  79. package/lib/sync.js.map +1 -1
  80. package/package.json +1 -1
  81. package/rt-tools-agent-kit-0.29.4.tgz +0 -0
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { declaredEpicOf } from './board-epic-link.mjs';
6
6
  import { planPathOf, planRows, planTaskCells } from './board-epic-plan.mjs';
7
- import { ghJson, numberFromTitle, OfflineError, OWNER, REPO, TASK_KEY } from './board.mjs';
7
+ import { ghJson, numberFromBranch, numberFromTitle, OfflineError, OWNER, REPO, TASK_KEY } from './board.mjs';
8
8
  import { CONFIG } from './rt-kit-checks.config.mjs';
9
9
 
10
10
  /**
@@ -66,7 +66,16 @@ export function checkEpicLinks(open, report) {
66
66
 
67
67
  const planPath = found.path;
68
68
  const mentions = planTaskCells(found.text).join('\n').matchAll(new RegExp(`(?:#|${TASK_KEY}-)(\\d+)`, 'g'));
69
- const numbers = new Set([...mentions].map((match) => Number(match[1])));
69
+ const listed = [...mentions].map((match) => Number(match[1]));
70
+ const numbers = new Set(listed);
71
+ // A merge that took both sides of a conflict doubles rows of the makeup, and the set above
72
+ // does not see it.
73
+ for (const number of numbers) {
74
+ const times = listed.filter((one) => one === number).length;
75
+ if (times > 1) {
76
+ report(`#${epic.number}: the plan names the task #${number} in ${times} rows of the makeup — a merge took both sides; one row stays`);
77
+ }
78
+ }
70
79
  for (const number of numbers) {
71
80
  if (number === epic.number || !byNumber.has(number)) {
72
81
  continue;
@@ -236,6 +245,12 @@ export function checkEpicPullBase(open, pulls, report) {
236
245
  if (base.startsWith(`${TASK_KEY}-${epic}-`)) {
237
246
  continue;
238
247
  }
248
+ // A chain base: the branch of a task below in the same epic. The rule puts a chain PR on
249
+ // the previous branch, and that branch carries the epic branch.
250
+ const baseTask = numberFromBranch(base);
251
+ if (baseTask !== null && epicOf.get(baseTask) === epic) {
252
+ continue;
253
+ }
239
254
  report(
240
255
  `PR #${pull.number}: the task #${number} belongs to the epic #${epic}, and the base of the request is «${base}». A request past the epic takes the task out of it: the epic is handed in without it`
241
256
  );
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { execFileSync } from 'node:child_process';
11
11
 
12
- import { TASK_KEY } from './board.mjs';
12
+ import { TASK_KEY, numberFromTaskDir, taskDirs } from './board.mjs';
13
13
  import { CONFIG, ROOT } from './rt-kit-checks.config.mjs';
14
14
 
15
15
  /**
@@ -109,3 +109,42 @@ export function checkBranchFolders(report, mainBranch) {
109
109
  );
110
110
  }
111
111
  }
112
+
113
+ /**
114
+ * Task folders with a number that hold not one file from the index.
115
+ *
116
+ * Only a draft without a number may live outside history. The task creating command lays a numbered
117
+ * folder at once, and a task created "for later" leaves it on disk for good: the folder passes edits
118
+ * without a refusal and follows its owner across every switch of branches. Ten such folders were
119
+ * found by the owner in `git status`, not by a check.
120
+ *
121
+ * The index is asked, not the history: a folder added and not committed yet travels with the next
122
+ * commit, and a line about it would ask for what is already done.
123
+ */
124
+ export function checkUntrackedFolders(report) {
125
+ let tracked;
126
+ try {
127
+ tracked = execFileSync('git', ['ls-files', '-z', '--', CONFIG.tasksDir], {
128
+ cwd: ROOT,
129
+ encoding: 'utf8',
130
+ stdio: ['ignore', 'pipe', 'ignore'],
131
+ }).split('\0');
132
+ } catch {
133
+ // Not a repository: there is no index to compare with.
134
+ return;
135
+ }
136
+
137
+ for (const name of taskDirs()) {
138
+ if (numberFromTaskDir(name.split('/').pop()) === null) {
139
+ continue;
140
+ }
141
+ const prefix = `${CONFIG.tasksDir}/${name}/`;
142
+ if (tracked.some((file) => file.startsWith(prefix))) {
143
+ continue;
144
+ }
145
+ report(
146
+ `${prefix}: the task folder lies outside the index — take the branch of the task and commit the folder, ` +
147
+ `or delete it, if the task is not taken now`
148
+ );
149
+ }
150
+ }
@@ -39,6 +39,11 @@ export function runsOnHead(sha, options) {
39
39
  * nothing about it: production was 476 commits behind while the check stayed silent. Only a rollout
40
40
  * finished with success is judged — one still going may end with anything.
41
41
  *
42
+ * The status filter of the hosting is not used: it counts by a separate index that lags, and the same
43
+ * request returned a month-old run and yesterday's one within a minute. The twenty latest runs come
44
+ * without it, and the first successful among them is taken; twenty failed in a row are named by the
45
+ * neighbouring check of the last rollout.
46
+ *
42
47
  * Returns `null` if there were no rollouts at all: that is not a discrepancy but nothing to compare.
43
48
  */
44
49
  export function deployLag(workflow, mainBranch, options) {
@@ -46,9 +51,9 @@ export function deployLag(workflow, mainBranch, options) {
46
51
  [
47
52
  'api',
48
53
  `repos/${OWNER}/${REPO}/actions/workflows/${encodeURIComponent(workflow)}/runs` +
49
- '?status=success&per_page=1',
54
+ '?per_page=20',
50
55
  '--jq',
51
- '[.workflow_runs[] | {sha: .head_sha, at: .created_at}] | first // empty',
56
+ '[.workflow_runs[] | select(.conclusion == "success") | {sha: .head_sha, at: .created_at}] | first // empty',
52
57
  ],
53
58
  options
54
59
  );
@@ -101,6 +101,23 @@ export function fetchBoard(options) {
101
101
  }
102
102
  }
103
103
 
104
+ /**
105
+ * The card of one task on this board, read by a direct request to the task itself — its
106
+ * `projectItems` field — and not out of the list of the whole board. The list took three seconds on
107
+ * two hundred cards, a direct request answered in under one, and it names the column in the same
108
+ * answer. `undefined` — the task stands on no card of this board (yet).
109
+ */
110
+ export function fetchCard(number, options) {
111
+ const issue = graphql(
112
+ `{ repository(owner: "${OWNER}", name: "${REPO}") { issue(number: ${Number(number)}) { projectItems(first: 20) {
113
+ nodes { id project { id }
114
+ status: fieldValueByName(name: "Status") { ... on ProjectV2ItemFieldSingleSelectValue { name optionId } } } } } } }`,
115
+ options
116
+ ).data?.repository?.issue;
117
+ const card = issue?.projectItems?.nodes?.find((node) => node.project?.id === PROJECT_ID);
118
+ return card ? { itemId: card.id, status: card.status?.name ?? null } : undefined;
119
+ }
120
+
104
121
  /**
105
122
  * Moving a task to another column. The task's state on the board is the only thing the progress
106
123
  * is visible by: the board does not read the branch or the open PR itself.
@@ -284,7 +301,7 @@ export function taskState(number, options) {
284
301
  if (!issue) {
285
302
  return { exists: false, viewer: viewerOf(options) };
286
303
  }
287
- const item = fetchBoard(options).items.get(issue.number);
304
+ const item = fetchCard(issue.number, options);
288
305
  return {
289
306
  exists: true,
290
307
  viewer: viewerOf(options),
@@ -310,7 +327,7 @@ export function taskState(number, options) {
310
327
  *
311
328
  * `state` — what `taskState` returned, or `{ offline: <reason> }` if asking failed.
312
329
  */
313
- export function describeTaskState(number, state) {
330
+ export function describeTaskState(number, state, waitedSeconds) {
314
331
  if (state?.offline) {
315
332
  return {
316
333
  ok: false,
@@ -326,7 +343,10 @@ export function describeTaskState(number, state) {
326
343
  if (!state.onBoard) {
327
344
  return {
328
345
  ok: false,
329
- lines: [`in the work queue: NO`, 'a task that is not in the queue is backed by no work — nobody will come for it'],
346
+ lines: [
347
+ `in the work queue: NO${waitedSeconds === undefined ? '' : ` — not seen in ${waitedSeconds} s of waiting`}`,
348
+ 'a task that is not in the queue is backed by no work — nobody will come for it',
349
+ ],
330
350
  };
331
351
  }
332
352
 
@@ -48,7 +48,7 @@ import {
48
48
  numberFromTitle,
49
49
  taskDirs,
50
50
  } from './board.mjs';
51
- import { checkBranchFolders } from './board-folders.mjs';
51
+ import { checkBranchFolders, checkUntrackedFolders } from './board-folders.mjs';
52
52
  import { checkConflicting, checkHeadRun } from './board-pull-state.mjs';
53
53
  import { checkLongWork } from './board-long-work.mjs';
54
54
  import { HAS_PIPELINE, deployLag, lastDeploy, lastMainRun, pipelineText, pipelineWakesOnPush } from './board-runs.mjs';
@@ -167,6 +167,7 @@ let checked = { issues: 0, pulls: 0, cargo: 0, offBase: 0 };
167
167
  // Drafts are judged by the disk and so are checked always: no connection is needed for that.
168
168
  checkDrafts();
169
169
  checkBranchFolders(report, MAIN_BRANCH);
170
+ checkUntrackedFolders(report);
170
171
 
171
172
  let offline = false;
172
173
  try {
@@ -204,10 +204,14 @@ function findingsIn(line) {
204
204
  return found;
205
205
  }
206
206
 
207
- /** A sentence that is too long: the reader loses the beginning before the author reaches the end. */
207
+ /**
208
+ * A sentence that is too long: the reader loses the beginning before the author reaches the end.
209
+ * A full stop closed by emphasis — `.**` at the end of an article title — ends a sentence too:
210
+ * otherwise the title and the first sentence after it are counted as one.
211
+ */
208
212
  function longSentences(line) {
209
213
  return line
210
- .split(/(?<=[.!?])\s+/)
214
+ .split(/(?<=[.!?][*_]*)\s+/)
211
215
  .filter((sentence) => sentence.trim().split(/\s+/).length > WORDS_LIMIT)
212
216
  .map((sentence) => [`${sentence.trim().split(/\s+/).length} words in a sentence`, `split it: the limit is ${WORDS_LIMIT}`]);
213
217
  }
@@ -272,8 +272,12 @@ function publishedFiles() {
272
272
  const file = queue.pop();
273
273
  const dir = file.slice(0, file.lastIndexOf('/'));
274
274
  for (const [, relative] of read(file).matchAll(/(?:export|import)[^'"]*from\s+['"](\.[^'"]*)['"]/g)) {
275
+ // An ES module package writes the import with the `.js` ending of the built file; the
276
+ // source behind it is the `.ts` of the same name. Read literally, the published file
277
+ // stayed unseen, and every function the package hands out read as called by tests alone.
278
+ const source = relative.replace(/^\.\//, '').replace(/\.js$/, '');
275
279
  for (const suffix of ['.ts', '/index.ts', '']) {
276
- const path = `${dir}/${relative.replace(/^\.\//, '')}${suffix}`.replace(/\/\.\//g, '/');
280
+ const path = `${dir}/${source}${suffix}`.replace(/\/\.\//g, '/');
277
281
  if (exists(path) && !published.has(path)) {
278
282
  published.add(path);
279
283
  if (path.endsWith('/index.ts')) {
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The fifth step of creating a task: creation is confirmed by the answer of the work queue, not by
3
+ * the output of the command.
4
+ *
5
+ * All four steps before it answer for their own calls and stay silent about whether the task is
6
+ * visible to whoever comes for it. Sixteen creations in a row printed the number with a link that
7
+ * way, and not one of them landed in the queue: the account was limited by the hosting, and the
8
+ * calls gave no refusal at that.
9
+ */
10
+ import { OfflineError, describeTaskState, taskState } from './board.mjs';
11
+
12
+ /**
13
+ * The window of waiting: the pauses between readings, in milliseconds, growing, about thirty seconds
14
+ * in all. The queue hands a new card back after seconds, and the delay sometimes outlasts a window
15
+ * of twelve seconds: one creation in six printed «NO» for a card that stood on the board with its
16
+ * assignee. A false refusal here costs more than a delay — it pushes to create the card a second
17
+ * time, and only an administrator can take it off the board. The list of pauses can be set by
18
+ * `RT_TASK_NEW_PAUSES_MS` — a suite does not wait half a minute for it.
19
+ */
20
+ export const QUEUE_PAUSES_MS = (process.env.RT_TASK_NEW_PAUSES_MS || '1000,2000,4000,8000,15000')
21
+ .split(',')
22
+ .map((pause) => Number(pause))
23
+ .filter((pause) => Number.isFinite(pause) && pause >= 0);
24
+
25
+ const WAITED_SECONDS = Number((QUEUE_PAUSES_MS.reduce((sum, pause) => sum + pause, 0) / 1000).toFixed(1));
26
+
27
+ /**
28
+ * One reading of the queue. `unreachable` — there was nothing to ask with: there is nothing to
29
+ * repeat, the answer is not late, there will be none at all.
30
+ */
31
+ function askQueue(number, token, waitedSeconds) {
32
+ try {
33
+ return { answer: describeTaskState(number, taskState(number, { token }), waitedSeconds), unreachable: false };
34
+ } catch (error) {
35
+ const reason = error instanceof OfflineError ? error.message : String(error.message ?? error);
36
+ return { answer: describeTaskState(number, { offline: reason }), unreachable: true };
37
+ }
38
+ }
39
+
40
+ /**
41
+ * The queue's answer about the created task. «NO» is printed only after the whole window: until then
42
+ * it is the queue's delay, not an answer.
43
+ */
44
+ export function confirmInQueue(number, token) {
45
+ let reading = askQueue(number, token, 0);
46
+ for (let attempt = 0; !reading.answer.ok && !reading.unreachable && attempt < QUEUE_PAUSES_MS.length; attempt += 1) {
47
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, QUEUE_PAUSES_MS[attempt]);
48
+ reading = askQueue(number, token, WAITED_SECONDS);
49
+ }
50
+ return reading.answer;
51
+ }
@@ -50,14 +50,13 @@ import {
50
50
  STATUS_FIELD_ID,
51
51
  TASK_KEY,
52
52
  botToken,
53
- describeTaskState,
54
53
  gh,
55
54
  ghJson,
56
55
  graphql,
57
56
  numberFromTitle,
58
- taskState,
59
57
  unstampFolder,
60
58
  } from './board.mjs';
59
+ import { confirmInQueue } from './task-new-queue.mjs';
61
60
  import { CONFIG, ROOT } from './rt-kit-checks.config.mjs';
62
61
 
63
62
  /**
@@ -437,45 +436,9 @@ if (args.epic) {
437
436
  console.log(`[${TASK_KEY}-${number}] ${args.title}`);
438
437
  console.log(`https://github.com/${OWNER}/${REPO}/issues/${number}`);
439
438
 
440
- /**
441
- * The fifth step: creation is confirmed by the answer of the work queue, not by the output of this
442
- * command.
443
- *
444
- * All four steps above answer for their own calls and stay silent about whether the task is visible
445
- * to whoever comes for it. Sixteen creations in a row printed the number with a link that way, and
446
- * not one of them landed in the queue: the account was limited by the hosting, and the calls gave
447
- * no refusal at that.
448
- */
449
- /**
450
- * This is read more than once. The queue does not hand back a new card the same second it was
451
- * created, and the reading goes as the next call after the adding: two creations in a row printed
452
- * that the task is not in the queue while the card was in place. A false refusal here costs more
453
- * than a delay — it pushes to create the card a second time, and only an administrator can take it
454
- * off the board.
455
- */
456
- let unreachable = false;
457
-
458
- function askQueue() {
459
- try {
460
- return describeTaskState(number, taskState(number, { token }));
461
- } catch (error) {
462
- // There was nothing to ask with — there is nothing to repeat: the answer is not late,
463
- // there will be none at all.
464
- unreachable = true;
465
- const reason = error instanceof OfflineError ? error.message : String(error.message ?? error);
466
- return describeTaskState(number, { offline: reason });
467
- }
468
- }
469
-
470
- /** How long to wait between readings and how many times to re-read: the queue delay is seconds. */
471
- const QUEUE_RETRIES = 3;
472
- const QUEUE_PAUSE_MS = 1500;
473
-
474
- let answer = askQueue();
475
- for (let attempt = 1; !answer.ok && !unreachable && attempt < QUEUE_RETRIES; attempt += 1) {
476
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, QUEUE_PAUSE_MS);
477
- answer = askQueue();
478
- }
439
+ // The fifth step: creation is confirmed by the answer of the work queue, not by the output of this
440
+ // command. How long it waits and why is in the module of the step.
441
+ const answer = confirmInQueue(number, token);
479
442
  for (const line of answer.lines) {
480
443
  (answer.ok ? console.log : console.error)(`task-new: ${line}`);
481
444
  }
@@ -101,8 +101,11 @@ skill_for_default() {
101
101
  printf '%s\n' 'styling-bem' ;;
102
102
  */check-lib-layers.mjs | */lib-layers-allowlist.json) printf '%s\n' 'lib-layers' ;;
103
103
  */check-reuse.mjs | */reuse-allowlist.json) printf '%s\n' 'reuse-first' ;;
104
- */check-board.mjs | */board.mjs | */task-new.mjs | */check-schema-drift.mjs)
104
+ # The queue audit has a rule of its own, laid out on GitHub only; the folders
105
+ # module is laid out on every host and stays with the rule about tasks.
106
+ */board-folders.mjs | */task-new.mjs | */check-schema-drift.mjs)
105
107
  printf '%s\n' 'git-workflow' ;;
108
+ */check-board.mjs | */board.mjs | */board-*.mjs) printf '%s\n' 'queue-audit' ;;
106
109
  # A tree's own code linter rule is written by the same conventions as the code under
107
110
  # it.
108
111
  */eslint-rules/*) printf '%s\n' 'typescript-conventions' ;;
@@ -42,6 +42,10 @@
42
42
  # and only the target tells them apart. Behind a real sign stands a path, not a word in words. The
43
43
  # price is named directly: a path typed not in Latin letters no longer counts as a write — there is
44
44
  # not one such in the tree, and should they appear, the sign will have to be widened.
45
+ #
46
+ # The in-place flag of a stream editor is matched as a flag word, not as a substring. A path such
47
+ # as `order-item-list.html` carries `-i` inside it, and a read-only `sed -n …p` over such a path
48
+ # was refused as an in-place edit, together with any command that merely quoted the path.
45
49
  rt_shell_writes_default() {
46
50
  cleaned="$(printf '%s' "$1" \
47
51
  | sed -E 's#(&|[0-9]*)>>?[[:space:]]*/dev/(null|stderr)##g; s#[0-9]*>&[0-9-]##g; s#[-=]+>##g')"
@@ -62,7 +66,7 @@ rt_shell_writes_default() {
62
66
 
63
67
  printf '%s' "$cleaned" \
64
68
  | grep -Eq \
65
- '>>?[[:space:]]*[A-Za-z0-9_./~$"'"'"'-]|\btee\b|\bsed\b[^|]*-i|\bperl\b[^|]*-i|\bdd\b[^|]*of=|\bcp\b|\bmv\b|\brm\b|\btouch\b|\btruncate\b|\binstall\b|\bpatch\b|\bgit[[:space:]]+(checkout|restore|apply|stash)\b'
69
+ '>>?[[:space:]]*[A-Za-z0-9_./~$"'"'"'-]|\btee\b|\bsed\b[^|]*[[:space:]]-[a-zA-Z]*i\b|\bsed\b[^|]*--in-place|\bperl\b[^|]*[[:space:]]-[a-zA-Z]*i\b|\bdd\b[^|]*of=|\bcp\b|\bmv\b|\brm\b|\btouch\b|\btruncate\b|\binstall\b|\bpatch\b|\bgit[[:space:]]+(checkout|restore|apply|stash)\b'
66
70
  }
67
71
 
68
72
  # The paths named by a shell command. Prints one per line; the caller judges them.
@@ -149,7 +153,7 @@ rt_shell_paths_default() {
149
153
  #
150
154
  # The other kinds of writing are parsed as before: for an in-place edit, a copy, a move
151
155
  # and an interpreter the path stands in the command itself and not in one place.
152
- if ! printf '%s' "$piece" | grep -Eq '\bsed\b[^|]*-i|\bperl\b[^|]*-i|\bpython3?\b|\bnode\b|\bruby\b|\bdd\b[^|]*of=|\bcp\b|\bmv\b|\brm\b|\btouch\b|\btruncate\b|\binstall\b|\bpatch\b|\bgit[[:space:]]+(checkout|restore|apply|stash)\b'; then
156
+ if ! printf '%s' "$piece" | grep -Eq '\bsed\b[^|]*[[:space:]]-[a-zA-Z]*i\b|\bsed\b[^|]*--in-place|\bperl\b[^|]*[[:space:]]-[a-zA-Z]*i\b|\bpython3?\b|\bnode\b|\bruby\b|\bdd\b[^|]*of=|\bcp\b|\bmv\b|\brm\b|\btouch\b|\btruncate\b|\binstall\b|\bpatch\b|\bgit[[:space:]]+(checkout|restore|apply|stash)\b'; then
153
157
  printf '%s' "$piece" \
154
158
  | grep -oE '(>>?[[:space:]]*|\btee\b([[:space:]]+-a)?[[:space:]]+)[A-Za-z0-9_@.~/-]+' \
155
159
  | sed -E 's/^(>>?|tee([[:space:]]+-a)?)[[:space:]]*//' \
@@ -118,40 +118,69 @@ judged="$(printf '%s\n' "$said" \
118
118
  !code && !/^[[:space:]]*>/' \
119
119
  | sed -E 's/`[^`]*`/ /g; s/«[^»]*»/ /g; s/"[^"]*"/ /g' \
120
120
  | sed -E 's/([.!?])[[:space:]]+/\1\'$'\n''/g' \
121
- | grep -viE '(^|[[:space:]])(бы|если|разве|неужели|ли)([[:space:]]|[,.]|$)' 2>/dev/null)"
121
+ | grep -viE '(^|[[:space:]])(бы|если|разве|неужели|ли)([[:space:]]|[,.]|$)' 2>/dev/null \
122
+ | sed -E 's/^/ /; s/([[:space:]])не[[:space:]]+/\1не~/g')"
122
123
  [ -z "$judged" ] && exit 0
123
124
  said="$judged"
125
+ # Every sentence starts with a space, and a negation is glued to the word after it by `~`. The
126
+ # space is the word boundary: an anchor inside a group and a class with a negation do not hold one
127
+ # — `^` in a group under `grep -o` is true at any position where PATH leads to ugrep, and a class
128
+ # like `[^а-яё]` matches half of a two-byte letter. Without the boundary «слит» was found inside
129
+ # «числит», and a sentence about counting was read as merged work.
124
130
 
125
131
  # The claims map: what is said about the tree | what shows it | what to name in the refusal.
126
132
  #
127
133
  # The word is taken in the form it is said to the owner in. The future tense does not go here:
128
134
  # "I will check" and "I will start" are not claims — they are a promise, and there is nothing in
129
135
  # them to lie with.
136
+ #
137
+ # `@` stands before a claim word: it reads as the word boundary for the claim and as «не» before
138
+ # the word for its negation. A done action is named by a past form: «удаляет» and «удалить» describe
139
+ # what a command does, not what was done.
130
140
  claims=(
131
- 'проверено|прогнал[а]?|тесты (зелёные|прошли)|линт(ер)? (зелёный|прошёл|чистый)|сборка (зелёная|прошла)|набор зелёный|проверки зелёные|спеки зелёные|всё зелен(о|ое)§nx (test|lint|build|run|affected|run-many)|npm (run|test)|pnpm (run|exec|test)|jest|vitest|playwright|check:|run\.sh§команду набора — прогон тестов, линта или сборки'
132
- 'запушен[аоы]?|запушил[а]?|пуш прошёл|ветка уехала§git push§`git push`'
133
- '(PR|правка|ветка|работа)[^.]{0,20}(влит|слит|смержен)|влит[оа] в|слит[оа] в§git merge|gh pr merge§`git merge` или `gh pr merge`'
134
- '(ветки|ветка|файлы|файл|папка|каталог)[^.]{0,40}(снят|удал|почищ|вычищ)|снят[оыа] с§git branch|git push .*--delete|git rm|gh api|rm §команду удаления — `git branch -d`, `git push --delete` или `git rm`'
135
- 'прогон (зелёный|прошёл|кончился)|конвейер зелёный|проверки на PR зелёные§gh run§`gh run list` или `gh run view`'
136
- '(работа|правка|задача) готова|можно вливать|PR открыт|черновик снят§gh pr §`gh pr create`, `gh pr view` или `gh pr ready`'
141
+ '@проверено|@прогнал[а]?|@тесты (зелёные|прошли)|@линт(ер)? (зелёный|прошёл|чистый)|@сборка (зелёная|прошла)|@набор зелёный|@проверки зелёные|@спеки зелёные|@всё зелен(о|ое)§nx (test|lint|build|run|affected|run-many)|npm (run|test)|pnpm (run|exec|test)|jest|vitest|playwright|check:|run\.sh§команду набора — прогон тестов, линта или сборки'
142
+ # A gate called fixed is a claim about a run: the fix is shown by the gate passing, and the
143
+ # phrase was once said with not one run behind it.
144
+ '@проверк[аи] перед (push|пушем|отправкой)[^.]{0,30}(починен|исправлен)§git push|check:all|pnpm (run|exec)§прогон набора перед push — `git push` или `pnpm run check:all`'
145
+ '@запушен[аоы]?|@запушил[а]?|@пуш прошёл|@ветка уехала§git push§`git push`'
146
+ '(PR|правка|ветка|работа)[^.]{0,20}@(влит|слит|смержен)|@влит[оа] в|@слит[оа] в§git merge|gh pr merge§`git merge` или `gh pr merge`'
147
+ '(ветки|ветка|файлы|файл|папка|каталог)[^.]{0,40}@(снят|удал[её]н|удалил|почищен|почистил|вычищен|вычистил)|@снят[оыа] с§git branch|git push .*--delete|git rm|gh api|rm §команду удаления — `git branch -d`, `git push --delete` или `git rm`'
148
+ '@прогон (зелёный|прошёл|кончился)|@конвейер зелёный|@проверки на PR зелёные§gh run§`gh run list` или `gh run view`'
149
+ '@(работа|правка|задача) готова|@можно вливать|@PR открыт|@черновик снят§gh pr §`gh pr create`, `gh pr view` или `gh pr ready`'
137
150
  # Waiting for someone else's step is a claim about the state too, and there is something in it
138
151
  # to lie with: a run is green for an hour, and sometimes never starts at all. Said without a
139
152
  # command, it leaves finished work a draft, and the owner learns of it last — that is exactly
140
153
  # how it went twice in one day.
141
- 'жд[уёя][^.]{0,20}прогон|дожида[ею][^.]{0,20}прогон|прогон[^.]{0,20}(ещё идёт|не встал|не кончился|не дошёл)|черновик[^.]{0,30}(не снимаю|сниму|снимется)§gh run|gh pr checks|check-runs|check:board|board\.mjs§команду о прогоне — `gh run list`, `gh pr checks` или сверку очереди работ'
142
- 'задача заведена|задача (в|переведена в) колонк|колонка переведена§gh issue|gh api|task:new|task:move|board\.mjs§команду очереди работ — заведение задачи или перевод колонки'
143
- '(в дереве|в репозитории|здесь|такого файла|такой команды)[^.]{0,30}(нет|не бывает)|не заводили|нигде не встречается§grep|rg |ls |find |git ls-files|git grep|git log|cat §команду поиска — `grep`, `git ls-files` или обход каталога'
154
+ '@жд[уёя][^.]{0,20}прогон|@дожида[ею][^.]{0,20}прогон|@прогон[^.]{0,20}(ещё идёт|не встал|не кончился|не дошёл)|@черновик[^.]{0,30}(не снимаю|сниму|снимется)§gh run|gh pr checks|check-runs|check:board|board\.mjs§команду о прогоне — `gh run list`, `gh pr checks` или сверку очереди работ'
155
+ '@задача заведена|@задача (в|переведена в) колонк|@колонка переведена§gh issue|gh api|task:new|task:move|board\.mjs§команду очереди работ — заведение задачи или перевод колонки'
156
+ '(в дереве|в репозитории|здесь|такого файла|такой команды)[^.]{0,30}(нет|не бывает)|@не заводили|@нигде не встречается§grep|rg |ls |find |git ls-files|git grep|git log|cat §команду поиска — `grep`, `git ls-files` или обход каталога'
144
157
  )
145
158
 
159
+ # A negated claim is a statement about the tree too, but the action command cannot show it: «not
160
+ # pushed» is shown by a read of the branch state, not by a push.
161
+ read_proof='git (status|log|ls-remote|branch|show|rev-parse|fetch|diff)|gh (pr|run|api|issue)|ls |grep|board\.mjs'
162
+
146
163
  for row in "${claims[@]}"; do
147
164
  words="${row%%§*}"
148
165
  rest="${row#*§}"
149
166
  proof="${rest%%§*}"
150
167
  name="${rest#*§}"
151
168
 
152
- found="$(printf '%s' "$said" | grep -oiE "$words" 2>/dev/null | head -1)"
153
- [ -z "$found" ] && continue
154
- printf '%s' "$ran" | grep -qiE "$proof" 2>/dev/null && continue
169
+ # The text glues «не» to the next word, so the row does the same with its own «не».
170
+ words="${words//не /не~}"
171
+ claim_re="${words//@/ }"
172
+ negated_re="${words//@/ не~}"
173
+
174
+ found="$(printf '%s' "$said" | grep -oiE "$claim_re" 2>/dev/null | head -1)"
175
+ if [ -n "$found" ]; then
176
+ printf '%s' "$ran" | grep -qiE "$proof" 2>/dev/null && continue
177
+ else
178
+ found="$(printf '%s' "$said" | grep -oiE "$negated_re" 2>/dev/null | head -1)"
179
+ [ -z "$found" ] && continue
180
+ printf '%s' "$ran" | grep -qiE "$proof|$read_proof" 2>/dev/null && continue
181
+ name="команду чтения — \`git status\`, \`git log\` или \`git ls-remote\`"
182
+ fi
183
+ found="$(printf '%s' "$found" | sed -E 's/~/ /g; s/^[[:space:]]+//')"
155
184
 
156
185
  reason="BLOCKED by claim-guard: the owner was told «${found}» — that is a statement about the state of the tree, and there was no command showing it in this turn.
157
186
 
@@ -85,13 +85,43 @@ fi
85
85
  command -v rt_epic_over >/dev/null 2>&1 || exit 0
86
86
  rt_epic_over || exit 0
87
87
 
88
+ # The word of the owner about this very work releases the call: their message or their answer to a
89
+ # menu that names the number the call takes. The line in the call was the only form before, and an
90
+ # owner who forbade writing it left the executor one way out — stopping the work they had just set.
91
+ # The number is read from the call; the words of the executor do not count.
92
+ taken="$(printf '%s' "$cmd" | sed -nE 's/.*(checkout|switch)[[:space:]]+(-[A-Za-z]+[[:space:]]+)*-(b|c)[[:space:]]+[A-Za-z]+-([0-9]+)-.*/\4/p; s/.*(task:move|board\.mjs[[:space:]]+move)[^0-9|;&]*([0-9]+).*/\2/p; s/.*--epic-of[[:space:]=]+([0-9]+).*/\1/p' | head -1)"
93
+ transcript="$(printf '%s' "$input" | jq -r '.transcript_path // empty' 2>/dev/null)"
94
+ if [ -n "$taken" ] && [ -n "$transcript" ] && [ -f "$transcript" ]; then
95
+ # A menu answer comes in two forms, «The user answered:» and «Your questions have been answered:»,
96
+ # followed by "question"="answer" pairs. Only the answers count: the question is written by the
97
+ # executor, and a number in «take RT-N?» answered «no» is not the owner's word.
98
+ named="$(tail -n 400 "$transcript" 2>/dev/null | jq -s -r --arg n "$taken" '
99
+ def menu_answers: if test("^(The user answered|Your questions have been answered):")
100
+ then ([match("\"=\"([^\"]*)\""; "g") | .captures[0].string] | join("\n")) else "" end;
101
+ [.[] | select(.type == "user")
102
+ | select(((.isMeta // false) or (.isCompactSummary // false)) | not)
103
+ | (.message.content // "")
104
+ | if type == "string" then .
105
+ elif type == "array" then (map(
106
+ if .type == "text" then (.text // "")
107
+ elif .type == "tool_result" then ((.content
108
+ | if type == "string" then . elif type == "array"
109
+ then (map(if type == "object" then (.text // "") else "" end) | join(" ")) else "" end)
110
+ | menu_answers)
111
+ else "" end) | join("\n"))
112
+ else "" end]
113
+ | map(test("(^|[^0-9])" + $n + "([^0-9]|$)")) | any
114
+ ' 2>/dev/null)"
115
+ [ "$named" = "true" ] && exit 0
116
+ fi
117
+
88
118
  root="$(git rev-parse --show-toplevel 2>/dev/null)"
89
119
  checks="$(jq -r '.layout.checks // "tools"' "$root/.claude/rt-kit.json" 2>/dev/null)"
90
120
  if [ -z "$checks" ] || [ "$checks" = null ]; then
91
121
  checks=tools
92
122
  fi
93
123
 
94
- reason="Refused: the epic is over — every task of it is merged or handed over by a request, and this call takes new work. The end of an epic is a stop: print the table by «npm run epic:table» (or «node $checks/epic-table.mjs»), tell the owner what was done on each task and what confirms it, and say outright that the session waits for their orders. New work is taken by their word, not by the count of what is left."
124
+ reason="Refused: the epic is over — every task of it is merged or handed over by a request, and this call takes new work. The end of an epic is a stop: print the table by «npm run epic:table» (or «node $checks/epic-table.mjs»), tell the owner what was done on each task and what confirms it, and say outright that the session waits for their orders. New work is taken by their word, not by the count of what is left: their message or their answer to a menu that names the number of this work releases the call."
95
125
 
96
126
  # shellcheck disable=SC1090
97
127
  [ -f "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/deny-tail.sh" ] \
@@ -125,7 +125,17 @@ rt_epic_pull_base() {
125
125
  ' 2>/dev/null)"
126
126
  fi
127
127
 
128
- if [ "$_base" != "$_epic_branch" ]; then
128
+ # A chain base: the branch of the task below, standing on the epic branch. It is lawful
129
+ # while its history carries the epic branch — the rule puts a chain PR on the previous branch.
130
+ _chain=''
131
+ if [ -n "$_base" ] && [ "$_base" != "$_epic_branch" ] && [ "$_base" != "${main_branch:-main}" ] \
132
+ && git rev-parse --verify --quiet "origin/${_epic_branch}" >/dev/null 2>&1 \
133
+ && git rev-parse --verify --quiet "origin/${_base}" >/dev/null 2>&1 \
134
+ && git merge-base --is-ancestor "origin/${_epic_branch}" "origin/${_base}" 2>/dev/null; then
135
+ _chain=1
136
+ fi
137
+
138
+ if [ "$_base" != "$_epic_branch" ] && [ -z "$_chain" ]; then
129
139
  fault "the request of a task of the epic #${_epic} goes into the branch of the epic «${_epic_branch}», and the base here is ${_base:-the default branch of the repository}. A request into the main branch takes the task past its epic: the epic is handed in without it. Name the base: --base ${_epic_branch}."
130
140
  return 0
131
141
  fi
@@ -30,6 +30,16 @@ rt_delivery_exec_dir() {
30
30
  named="$(printf '%s' "$cmd" | sed -nE 's/.*(^|[;&|[:space:]])cd[[:space:]]+([^[:space:];&|]+).*/\2/p' | head -1)"
31
31
  named="${named%\'}"; named="${named#\'}"
32
32
  named="${named%\"}"; named="${named#\"}"
33
+ # The shell expands the home directory before `cd` runs, and the guard reads the command text
34
+ # unexpanded: a path with a tilde named no directory, and the command counted as running in the
35
+ # tree of the session.
36
+ case "$named" in
37
+ '~') named="$HOME" ;;
38
+ '~/'*) named="$HOME/${named#\~/}" ;;
39
+ '$HOME'|'${HOME}') named="$HOME" ;;
40
+ '$HOME/'*) named="$HOME/${named#\$HOME/}" ;;
41
+ '${HOME}/'*) named="$HOME/${named#\$\{HOME\}/}" ;;
42
+ esac
33
43
  [ -z "$named" ] && return 0
34
44
  [ -d "$named" ] || return 0
35
45
  git -C "$named" rev-parse --show-toplevel 2>/dev/null
@@ -95,3 +105,22 @@ rt_delivery_current_branch() {
95
105
  other="$(rt_delivery_foreign_root)"
96
106
  git -C "${other:-.}" branch --show-current 2>/dev/null
97
107
  }
108
+
109
+ # The form of the task number in a request title, by the profile of the tree of execution. The key of
110
+ # a neighbouring tree is its own: judged by the session's form, a lawful title of that tree was
111
+ # refused as having no number at all.
112
+ rt_delivery_title_re() {
113
+ other="$(rt_delivery_foreign_root)"
114
+ if [ -z "$other" ] || [ ! -f "$other/.claude/rt-kit/project.sh" ]; then
115
+ printf '%s' "$1"
116
+ return 0
117
+ fi
118
+ (
119
+ cd "$other" 2>/dev/null || { printf '%s' "$1"; exit 0; }
120
+ unset RT_TASK_TITLE_RE
121
+ for profile in "$other/.claude/rt-kit/defaults/project.sh" "$other/.claude/rt-kit/project.sh"; do
122
+ [ -f "$profile" ] && . "$profile" >/dev/null 2>&1
123
+ done
124
+ printf '%s' "${RT_TASK_TITLE_RE:-^\[[A-Za-z]+-[0-9]+\][[:space:]]+[^[:space:]]}"
125
+ )
126
+ }
@@ -33,15 +33,12 @@
33
33
  # RT_TASK_BOT — the account put as the assignee; the PR is opened by it as well;
34
34
  # RT_PULL_TOKEN_VAR — the variable through which its token is substituted into the call;
35
35
  # RT_PULL_TOKEN_HINT — the ready-made substitution of that token, whole;
36
- # RT_COMMIT_EMAIL — the address a machine commit is signed with; by its left part the commit
37
- # is recognised as well.
38
- # The refusal names both what is wrong and what fixes it: a refusal without an action is bypassed,
39
- # not carried out.
36
+ # RT_COMMIT_EMAIL — the address of a machine commit; its left part recognises the commit too.
37
+ # A refusal names what is wrong and what fixes it: one without an action is bypassed, not obeyed.
40
38
  #
41
39
  # FAIL-OPEN: not a repository, no parser, broken input, no profile — let through.
42
40
 
43
- # Its own name in the observations: the refusal is written by the shared deny tail, not by the
44
- # guard itself.
41
+ # Its own name in the observations: the refusal is written by the shared deny tail, not here.
45
42
  RT_GUARD_NAME=git-guard-delivery
46
43
 
47
44
  . "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/utf8.sh" 2>/dev/null || true
@@ -365,6 +362,9 @@ epic_pull="$(printf '%s' "$state" | jq -r '.epic // empty' 2>/dev/null)"
365
362
  # folders of all its tasks are taken apart.
366
363
  command -v rt_epic_own_pull >/dev/null 2>&1 && rt_epic_own_pull "$state"
367
364
 
365
+ # A request in another repository is judged by the title form of that repository.
366
+ command -v rt_delivery_title_re >/dev/null 2>&1 && title_re="$(rt_delivery_title_re "$title_re")"
367
+
368
368
  title=''
369
369
  if command -v perl >/dev/null 2>&1; then
370
370
  title="$(printf '%s' "$cmd" | perl -0ne '