@bluenyang/reins 0.3.4 → 0.4.0-rc.2

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 (66) hide show
  1. package/README.md +164 -39
  2. package/cli/dist/commands/config-gates.js +64 -6
  3. package/cli/dist/commands/config-models.js +19 -0
  4. package/cli/dist/commands/config.js +40 -16
  5. package/cli/dist/commands/configure.js +207 -47
  6. package/cli/dist/commands/install.js +91 -31
  7. package/cli/dist/commands/migrate.js +17 -20
  8. package/cli/dist/commands/update.js +164 -12
  9. package/cli/dist/lib/agents-md.js +55 -13
  10. package/cli/dist/lib/bindings.js +7 -10
  11. package/cli/dist/lib/blocks.js +82 -18
  12. package/cli/dist/lib/detect.js +88 -3
  13. package/cli/dist/lib/gate-refresh.js +35 -5
  14. package/cli/dist/lib/gate-script.js +303 -25
  15. package/cli/dist/lib/generate.js +48 -6
  16. package/cli/dist/lib/git.js +33 -0
  17. package/cli/dist/lib/migrate-plan.js +1 -1
  18. package/cli/dist/lib/profile.js +101 -0
  19. package/cli/dist/lib/prompter.js +2 -1
  20. package/cli/dist/lib/release.js +1 -1
  21. package/cli/dist/lib/schema.js +6 -3
  22. package/cli/dist/lib/upstream.js +1 -1
  23. package/cli/dist/reins.js +40 -14
  24. package/docs/README.ko.md +113 -23
  25. package/harness/CHANGELOG.md +12 -0
  26. package/harness/VERSION +1 -1
  27. package/harness/policy/common-red-lines.yaml +7 -5
  28. package/harness/roles/advisor.md +1 -1
  29. package/harness/roles/auditor.md +12 -11
  30. package/harness/roles/executor.md +4 -3
  31. package/harness/roles/implementer.md +5 -5
  32. package/harness/roles/pl.md +4 -4
  33. package/harness/roles/planner.md +7 -8
  34. package/harness/roles/pm.md +7 -8
  35. package/harness/schemas/bindings.schema.json +2 -0
  36. package/harness/schemas/install.schema.json +1 -0
  37. package/harness/schemas/intent.schema.json +9 -1
  38. package/harness/schemas/plan.schema.json +18 -0
  39. package/harness/schemas/spec.schema.json +9 -6
  40. package/harness/templates/agents-md-blocks.md +19 -54
  41. package/harness/templates/agents-md-guide.md +11 -10
  42. package/harness/templates/audit.md +14 -41
  43. package/harness/templates/history.md +1 -5
  44. package/harness/templates/intent.md +8 -19
  45. package/harness/templates/plan.md +23 -0
  46. package/harness/templates/spec.md +21 -16
  47. package/package.json +1 -1
  48. package/skills/audit/SKILL.md +27 -33
  49. package/skills/gates/SKILL.md +41 -0
  50. package/skills/implement/SKILL.md +33 -22
  51. package/skills/implement/references/procedure.md +51 -0
  52. package/skills/intent/SKILL.md +29 -20
  53. package/skills/intent/references/procedure.md +60 -0
  54. package/skills/onboard/SKILL.md +39 -28
  55. package/skills/plan/SKILL.md +35 -0
  56. package/skills/plan/references/procedure.md +52 -0
  57. package/skills/reins-setup/SKILL.md +4 -4
  58. package/skills/release/SKILL.md +18 -20
  59. package/skills/retro/SKILL.md +21 -26
  60. package/skills/review/SKILL.md +33 -17
  61. package/skills/review/references/procedure.md +50 -0
  62. package/skills/spec/SKILL.md +25 -19
  63. package/skills/spec/references/procedure.md +67 -0
  64. package/skills/merge/SKILL.md +0 -32
  65. package/skills/roadmap/SKILL.md +0 -29
  66. package/skills/test/SKILL.md +0 -26
@@ -2,9 +2,10 @@ import { readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { parseBlocks } from './blocks.js';
4
4
  import { KNOWN_TOOLS, auditBinding, auditFallback, resolveRoles, } from './bindings.js';
5
+ import { profileOf } from './profile.js';
5
6
  /**
6
- * AGENTS.md managed blocks for 0.3 (design §5): the static blocks from the template plus the delegation
7
- * table, resolved from the team bindings when `config`, `install` or `update` writes — never at work time.
7
+ * AGENTS.md managed blocks (design §5): the static blocks from the template plus the delegation table,
8
+ * resolved from the team bindings when `config`, `install` or `update` writes — never at work time.
8
9
  */
9
10
  /** The name of the generated Claude agent file of a role (design §6). */
10
11
  export const agentName = (group, role) => group === role ? `rs-${group}` : `rs-${group}-${role}`;
@@ -41,13 +42,22 @@ export const LOCAL_DELEGATION = '.loctx/delegation.local.md';
41
42
  export const cliOf = (doc, vendor) => doc.tools?.[vendor]?.cli ?? KNOWN_TOOLS[vendor] ?? vendor;
42
43
  /** When the PM may use a role's fallback line (design §5): the call cannot be made, not a disliked answer. */
43
44
  export const FALLBACK_RULE = "When a role's call cannot be made (its CLI is missing, the model is refused or over its limit — not when you dislike the answer), use the role's `fallback` once, and say that you did and why in your report to the user and in the record of that step. Without a fallback, or when the fallback cannot be called either, stop and ask.";
45
+ /**
46
+ * How to call a Claude role that has no `rs-*` file: in full, a general subagent given the role file; in
47
+ * light there are no role files (design §2), so a plain subagent of that model given the task.
48
+ */
49
+ function claudeSubagent(doc, r, model) {
50
+ return profileOf(doc) === 'full'
51
+ ? `a general subagent on \`${model}\`, given the \`${r.role}\` section of \`.agents/harness/roles/${r.group}.md\``
52
+ : `a subagent on \`${model}\``;
53
+ }
44
54
  /** The fallback part of a role's "how to call" cell; empty when the role has none. */
45
55
  function fallbackHow(doc, r) {
46
56
  const f = r.fallback;
47
57
  if (!f)
48
58
  return '';
49
59
  const how = f.vendor === 'claude'
50
- ? `a general subagent on \`${f.model}\`, given the \`${r.role}\` section of \`.agents/harness/roles/${r.group}.md\``
60
+ ? claudeSubagent(doc, r, f.model)
51
61
  : callLine(f, cliOf(doc, f.vendor), WRITES.has(r.group));
52
62
  return `; fallback: ${f.vendor} ${f.model} — ${how}`;
53
63
  }
@@ -57,10 +67,11 @@ function fallbackHow(doc, r) {
57
67
  */
58
68
  export function renderDelegation(doc, local) {
59
69
  const lines = ['## Delegation', ''];
70
+ // the personal table wins (spec 025 Q-2, R-9): the block's first line says so
60
71
  if (!local)
61
- lines.push(`If \`${LOCAL_DELEGATION}\` exists, follow it instead of this section (your personal settings; \`reins config --local\` writes it): open it before anything else and use its table.`, '');
72
+ lines.push(`If \`${LOCAL_DELEGATION}\` exists, that table wins: open it before anything else and use it instead of this one (your personal settings; \`reins config --local\` writes it).`, '');
62
73
  if (doc.mode !== 'multi') {
63
- lines.push(`Mode: **single** — you are the PM — the model in this conversation — and do every role yourself, stage by stage. You may use subagents of your own model for read-heavy work (research, large log summaries, review, audit) and, when urgent, for parallel work on independent units; keep connected work (plan and implementation of one feature) in one run. Switching to multi is the user's choice.`);
74
+ lines.push(`Mode: **single** — you are the PM — the model in this conversation — and do every role yourself. You may use subagents of your own model for read-heavy work (research, large log summaries, review, audit) and for building independent features in parallel; the first review is such a fresh run that gets only the diff. Switching to multi is the user's choice.`);
64
75
  }
65
76
  else {
66
77
  lines.push(`Mode: **multi** — you are the PM — the model in this conversation. Hand a role its work with the list of files and decisions it needs; every report comes back to you, and a role never calls another model itself. Roles not listed are yours.`, '', '| role | model | how to call |', '|---|---|---|');
@@ -74,22 +85,25 @@ export function renderDelegation(doc, local) {
74
85
  how = callLine(b, cli, WRITES.has(r.group));
75
86
  else {
76
87
  const name = agents[k++].name;
77
- how =
78
- !local || local.teamAgents.some((a) => a.name === name && a.model === b.model)
79
- ? `subagent \`${name}\``
80
- : `a general subagent on \`${b.model}\`, given the \`${r.role}\` section of \`.agents/harness/roles/${r.group}.md\``;
88
+ // the rs-* file exists in full only; a personal table names it only when the team generated it
89
+ const generated = local
90
+ ? local.teamAgents.some((a) => a.name === name && a.model === b.model)
91
+ : profileOf(doc) === 'full';
92
+ how = generated ? `subagent \`${name}\`` : claudeSubagent(doc, r, b.model);
81
93
  }
82
94
  lines.push(`| ${r.group}/${r.role} | ${b.vendor} ${b.model} | ${how}${fallbackHow(doc, r)} |`);
83
95
  }
84
96
  }
85
- lines.push('', 'Routine review takes one reviewer; `pl/discussion` and `advisor/committee` (every listed model, without seeing each other) are for large decisions, audit remedies, incidents and unresolved disagreements.');
97
+ lines.push('', 'Routine review takes one reviewer; `pl/discussion` and `advisor/committee` (every listed model, without seeing each other) are for large decisions, incidents and unresolved disagreements.');
86
98
  // said only when some role has one, so a table without fallbacks reads exactly as before
87
99
  if (resolveRoles(doc).some((x) => x.on && x.fallback))
88
100
  lines.push('', FALLBACK_RULE);
89
101
  }
102
+ // the audit is optional and started by a person (spec 025 R-6): only a model set for it is named
90
103
  const a = auditBinding(doc);
91
104
  const af = auditFallback(doc);
92
- lines.push('', `Audit: ${doc.audit?.required === false ? '**switched off by the user**' : '**required every version, before the merge and after the release**'}; run it ${a ? `on ${a.vendor} ${a.model}${af ? ` (fallback: ${af.vendor} ${af.model}, when that model cannot be called — say so in the audit report)` : ''} in a fresh run` : 'in a fresh run of your own model (or another one the user chooses)'} that gets only the records, never this conversation.`);
105
+ if (a)
106
+ lines.push('', `Audit: when a person asks for one, the recommended model is ${a.vendor} ${a.model}${af ? ` (fallback: ${af.vendor} ${af.model}, when that model cannot be called — say so in the audit report)` : ''}, in a fresh run that gets only the records, never this conversation.`);
93
107
  return lines.join('\n');
94
108
  }
95
109
  /**
@@ -101,7 +115,7 @@ export function renderDelegation(doc, local) {
101
115
  export function localDelegation(team, effective, managed = () => true) {
102
116
  if (renderDelegation(effective) === renderDelegation(team))
103
117
  return null;
104
- const teamAgents = team.mode === 'multi'
118
+ const teamAgents = team.mode === 'multi' && profileOf(team) === 'full'
105
119
  ? resolveRoles(team)
106
120
  .filter((r) => r.on)
107
121
  .flatMap(claudeAgents)
@@ -155,7 +169,7 @@ export const TIDY_PENDING = '<!-- reins:tidy pending -->';
155
169
  export function tidyNote() {
156
170
  return [
157
171
  TIDY_PENDING,
158
- `> **AGENTS.md guide — do this first in the next conversation.** reins now ships a guide for what this file holds (\`.agents/harness/templates/agents-md-guide.md\`). Run the \`onboard\` skill: with the user, sort the project sections by the guide — current work and plans to the roadmap, decisions to knowledge candidates, personal notes to \`.loctx/\` — and show what went where. Then change the marker above to \`<!-- reins:tidy done -->\`.`,
172
+ `> **AGENTS.md guide — offer this at the start of the next conversation.** It does not block other work: if the person asks for something else, do that and mention once that this is pending. reins now ships a guide for what this file holds (\`.agents/harness/templates/agents-md-guide.md\`). Run the \`onboard\` skill: with the user, sort the project sections by the guide — current work and plans to the roadmap, decisions to knowledge candidates, personal notes to \`.loctx/\` — and show what went where. Then change the marker above to \`<!-- reins:tidy done -->\`.`,
159
173
  ].join('\n');
160
174
  }
161
175
  /** The light check after a mode switch (design §5, spec ST-5): only the delegation block changed. */
@@ -165,6 +179,33 @@ export function modeChangedNote(from, to) {
165
179
  `> **Mode changed from ${from} to ${to}.** reins rewrote the delegation section. In the next conversation (the \`onboard\` skill), check that the project sections below say nothing that contradicts the new mode, then change the marker above to \`<!-- reins:mode-changed done -->\`.`,
166
180
  ].join('\n');
167
181
  }
182
+ export const RESET_PENDING = '<!-- reins:reset pending -->';
183
+ /**
184
+ * The note an update from 0.3 to 0.4 leaves once (design §7): what reins cannot sort by itself. `profile` is
185
+ * the one `bindings.yaml` holds after the update (written by it when the file had none).
186
+ */
187
+ export function resetNote(profile) {
188
+ const todo = [
189
+ 'old flow wording left in the project sections (stages in a fixed order, approvals, waivers, two audits, work units) — propose what to drop or rewrite',
190
+ 'whether to split `.loctx/ROADMAP.local.md` into notes under `.loctx/intent/`',
191
+ 'whether to split the gates into areas (the `gates` skill, or `reins config gates`)',
192
+ `the profile in \`.agents/harness/bindings.yaml\` is \`${profile}\`, which keeps how the harness worked — confirm it; \`reins config\` changes it`,
193
+ 'the records up to 0.3 (`.agents/intent/`, `.agents/audit/`) are reference material, not current rules; a spec in progress can be continued',
194
+ ];
195
+ return [
196
+ RESET_PENDING,
197
+ `> **Reset to 0.4 — offer this at the start of the next conversation.** It does not block other work: if the person asks for something else, do that and mention once that this is pending. reins moved this repository from the 0.3 flow to 0.4: skills picked by their description instead of a fixed flow, and a person who confirms the plan, checks the completion report, merges and releases. Run the \`onboard\` skill and go through these with the person: ${todo.map((t, i) => `(${i + 1}) ${t}`).join('; ')}. Then change the marker above to \`<!-- reins:reset done -->\`.`,
198
+ ].join('\n');
199
+ }
200
+ /**
201
+ * Give a pending note the wording of this version: the marker stays pending, only the note line reins wrote
202
+ * under it changes (a note from 0.4.0-rc.1 told the agent to do the clean-up before anything else).
203
+ */
204
+ export function refreshNote(text, note, kind) {
205
+ const lead = { tidy: 'AGENTS.md guide', reset: 'Reset to 0.4' }[kind];
206
+ const re = new RegExp(`<!-- reins:${kind} pending -->\\n> \\*\\*${lead}[^\\n]*`);
207
+ return re.test(text) ? text.replace(re, () => note) : text;
208
+ }
168
209
  /** Put a note right after the first H1 (or at the top) unless one of that kind is still pending. */
169
210
  export function placeNote(text, note, kind) {
170
211
  if (text.includes(`<!-- reins:${kind} pending -->`))
@@ -176,6 +217,7 @@ export function placeNote(text, note, kind) {
176
217
  reconcile: 'Reconcile',
177
218
  'mode-changed': 'Mode changed',
178
219
  tidy: 'AGENTS.md guide',
220
+ reset: 'Reset to 0.4',
179
221
  }[kind];
180
222
  text = text.replace(new RegExp(`<!-- reins:${kind} done -->\\n(?:> \\*\\*${lead}[^\\n]*\\n)?\\n?`), '');
181
223
  const m = /^# .*\n/m.exec(text);
@@ -129,10 +129,9 @@ export function fallbackProblems(doc) {
129
129
  }
130
130
  return out;
131
131
  }
132
- /** Whether the per-version audit is mandatory (design §3-3): true unless the file says false. */
133
- export const auditRequired = (doc) => doc.audit?.required !== false;
134
132
  /**
135
- * The local override wins per key: mode, audit and each tool; a group wins only where it speaks (023 S-20).
133
+ * The local override wins per key: mode and each tool; a group wins only where it speaks (023 S-20). The
134
+ * profile is the team's: it decides which files are committed, so a personal file does not change it.
136
135
  * `{}` switches the team's group off. A group model (`vendor`/`model` or `models`) replaces the team's group
137
136
  * model, its fallback and its role entries; each personal role replaces that role; a personal fallback
138
137
  * replaces the group's. `default` is read from neither.
@@ -144,8 +143,6 @@ export function mergeLocal(team, local) {
144
143
  delete out.default;
145
144
  if (local.mode)
146
145
  out.mode = local.mode;
147
- if (local.audit)
148
- out.audit = { ...team.audit, ...local.audit };
149
146
  if (local.tools)
150
147
  out.tools = { ...team.tools, ...local.tools };
151
148
  if (local.groups) {
@@ -203,6 +200,7 @@ export const V1_ROLE_MAP = {
203
200
  advisor: { group: 'advisor' },
204
201
  };
205
202
  const DROPPED_V1_KEYS = ['escalation', 'limits'];
203
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
206
204
  /**
207
205
  * A version-1 `bindings.yaml` (`roles.<r>: {vendor, model, enabled, fallback, parallel}`, `vendors`)
208
206
  * as version 2. A role's `fallback` moves with its model; `parallel` has no place. The result is single mode; the converted groups take effect once the user switches to
@@ -210,8 +208,7 @@ const DROPPED_V1_KEYS = ['escalation', 'limits'];
210
208
  */
211
209
  export function convertV1(v1) {
212
210
  const notes = [];
213
- const doc = { schema: 'reins/bindings@2', mode: 'single', audit: { required: true } };
214
- const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
211
+ const doc = { schema: 'reins/bindings@2', mode: 'single' };
215
212
  const roles = isObj(v1['roles']) ? v1['roles'] : {};
216
213
  const bindingOf = (v) => isObj(v) && typeof v['vendor'] === 'string' && typeof v['model'] === 'string'
217
214
  ? { vendor: v['vendor'], model: v['model'] }
@@ -336,12 +333,12 @@ export function writeBindings(root, doc, scope) {
336
333
  mkdirSync(dirname(p), { recursive: true });
337
334
  writeFileSync(p, `${HEADER}${stringify({ ...doc, schema: 'reins/bindings@2' })}`);
338
335
  }
339
- /** A fresh file for install: single mode, the audit required, the detected tools. */
340
- export function defaultBindings(tools) {
336
+ /** A fresh file for install: single mode, the light profile unless asked, the detected tools. */
337
+ export function defaultBindings(tools, profile = 'light') {
341
338
  return {
342
339
  schema: 'reins/bindings@2',
343
340
  mode: 'single',
344
- audit: { required: true },
341
+ profile,
345
342
  tools: Object.fromEntries(tools.map((t) => [t.name, { cli: t.cli, use: t.use }])),
346
343
  };
347
344
  }
@@ -23,15 +23,61 @@ export function hasOwnSection(text, block) {
23
23
  const h = headingOf(block);
24
24
  return h !== null && new RegExp(`^## ${h}\\s*$`, 'm').test(outside(text));
25
25
  }
26
+ /** Cut `body` out of `text`, leaving one blank line between what was before and after it. */
27
+ function cut(text, body) {
28
+ const i = text.indexOf(body);
29
+ if (i < 0)
30
+ return text;
31
+ const before = text.slice(0, i).replace(/\n+$/, '');
32
+ const after = text.slice(i + body.length).replace(/^\n+/, '');
33
+ if (!before)
34
+ return after;
35
+ if (!after)
36
+ return `${before}\n`;
37
+ return `${before}\n\n${after}`;
38
+ }
39
+ /** Where the blocks go when none is there yet: after the first H1, else at the top. */
40
+ function anchorAt(text) {
41
+ const h1 = /^# .*$/m.exec(text);
42
+ return h1 ? h1.index + h1[0].length : 0;
43
+ }
44
+ const SLOT = '\u0000reins-blocks\u0000';
26
45
  /**
27
- * Put the upstream blocks into an AGENTS.md. Existing blocks are replaced in place; an overridden block is
28
- * left alone; a block whose heading the project already has outside any block is skipped (migrate replaces it).
29
- * New blocks go after the first H1 (notice) or at the end.
46
+ * Put the upstream blocks into an AGENTS.md (design §5). Blocks the source no longer provides are taken
47
+ * out; existing blocks are brought up to date; new ones are added; then every managed block stands together,
48
+ * in the source's order (delegation first), where the first of them stood — or after the first H1 when there
49
+ * was none. An overridden block is left alone where it is; a block whose heading the project already has
50
+ * outside any block is skipped (the project section stands in for it). Text outside the blocks is not changed, except for the
51
+ * blank lines where a block was taken out.
30
52
  */
31
53
  export function applyBlocks(text, upstream) {
32
- const res = { text, inserted: [], replaced: [], skipped: [] };
33
- const present = new Map(parseBlocks(text).map((b) => [b.name, b]));
54
+ const res = {
55
+ text,
56
+ inserted: [],
57
+ replaced: [],
58
+ removed: [],
59
+ moved: false,
60
+ skipped: [],
61
+ };
34
62
  const over = overrides(text);
63
+ const names = new Set(upstream.map((b) => b.name));
64
+ // 1. what the source no longer provides goes (an overridden one is the project's)
65
+ for (const b of parseBlocks(res.text)) {
66
+ if (names.has(b.name))
67
+ continue;
68
+ if (over.has(b.name)) {
69
+ res.skipped.push({
70
+ name: b.name,
71
+ why: 'overridden by the project; reins no longer ships it',
72
+ });
73
+ continue;
74
+ }
75
+ res.text = cut(res.text, b.body);
76
+ res.removed.push(b.name);
77
+ }
78
+ // 2. which blocks stand, with their new text, in the source's order
79
+ const present = new Map(parseBlocks(res.text).map((b) => [b.name, b]));
80
+ const placed = [];
35
81
  for (const b of upstream) {
36
82
  if (over.has(b.name)) {
37
83
  res.skipped.push({ name: b.name, why: 'overridden by the project' });
@@ -39,29 +85,47 @@ export function applyBlocks(text, upstream) {
39
85
  }
40
86
  const cur = present.get(b.name);
41
87
  if (cur) {
42
- if (cur.body !== b.body) {
43
- res.text = res.text.replace(cur.body, b.body);
88
+ if (cur.body !== b.body)
44
89
  res.replaced.push(b.name);
45
- }
90
+ placed.push(b);
46
91
  continue;
47
92
  }
48
- const h = headingOf(b);
49
93
  if (hasOwnSection(res.text, b)) {
50
94
  res.skipped.push({
51
95
  name: b.name,
52
- why: `the project already has a "## ${h}" section — \`reins migrate\` replaces it`,
96
+ why: `the project already has a "## ${headingOf(b)}" section — it stands in for the block; remove it to have reins place the block`,
53
97
  });
54
98
  continue;
55
99
  }
56
- if (b.name === 'notice') {
57
- const h1 = /^# .*$/m.exec(res.text);
58
- res.text = h1
59
- ? `${res.text.slice(0, h1.index + h1[0].length)}\n\n${b.body}\n${res.text.slice(h1.index + h1[0].length)}`
60
- : `${b.body}\n\n${res.text}`;
61
- }
62
- else
63
- res.text = `${res.text.replace(/\s*$/, '')}\n\n${b.body}\n`;
64
100
  res.inserted.push(b.name);
101
+ placed.push(b);
102
+ }
103
+ // 3. all of them together, where the first one stood
104
+ const mine = [...present.values()].filter((b) => placed.some((p) => p.name === b.name));
105
+ const first = mine
106
+ .map((b) => ({ b, at: res.text.indexOf(b.body) }))
107
+ .toSorted((x, y) => x.at - y.at)[0];
108
+ let slotted;
109
+ if (first) {
110
+ slotted = res.text.replace(first.b.body, () => SLOT);
111
+ for (const b of mine)
112
+ if (b !== first.b)
113
+ slotted = cut(slotted, b.body);
114
+ }
115
+ else {
116
+ const at = anchorAt(res.text);
117
+ slotted = `${res.text.slice(0, at)}\n\n${SLOT}\n\n${res.text.slice(at)}`;
118
+ }
119
+ const i = slotted.indexOf(SLOT);
120
+ const before = slotted.slice(0, i).replace(/\n+$/, '');
121
+ const after = slotted.slice(i + SLOT.length).replace(/^\n+/, '');
122
+ const group = placed.map((b) => b.body).join('\n\n');
123
+ const next = `${before ? `${before}\n\n` : ''}${group}${after ? `\n\n${after}` : '\n'}`;
124
+ if (placed.length) {
125
+ // moved: the same blocks, with the same text, stood elsewhere or in another order
126
+ const same = res.inserted.length === 0 && res.replaced.length === 0 && res.removed.length === 0;
127
+ res.moved = same && next !== text;
128
+ res.text = next;
65
129
  }
66
130
  return res;
67
131
  }
@@ -223,6 +223,8 @@ function makeTargets(text) {
223
223
  return out;
224
224
  }
225
225
  const MAKE_TARGETS = ['check', 'lint', 'test', 'build', 'vet', 'verify'];
226
+ /** A workflow command that is never a gate, whatever its name. */
227
+ const skip = (cmd) => exclusion('', cmd) !== null;
226
228
  /** The pieces of a body split into words, quoted words unquoted (for the workspace forms). */
227
229
  const pieceWords = (piece) => piece.split(' ').map(unquote);
228
230
  /**
@@ -380,7 +382,6 @@ export function detectCandidates(root) {
380
382
  c.reasons.push(REASON.outside(own));
381
383
  }
382
384
  // pull-request workflows (S-8)
383
- const skip = (cmd) => exclusion('', cmd) !== null;
384
385
  for (const r of ciRuns(root, compound, skip)) {
385
386
  const same = out.find((c) => c.status !== 'excluded' && c.cmd === r.cmd) ??
386
387
  out.find((c) => c.status !== 'excluded' &&
@@ -551,12 +552,94 @@ const pickRank = (c) => {
551
552
  const i = PICK_ORDER.indexOf(c.name);
552
553
  return i < 0 ? PICK_ORDER.length : i;
553
554
  };
555
+ /** Top-level directories that are never an area of their own: output, dependencies, tool state. */
556
+ const NOT_AREAS = new Set([...SKIP_DIRS, 'coverage', 'out', 'target', 'tmp', 'docs']);
557
+ /** An area name the gate script reads as a key: letters, digits, `_`, `.`, `-`. */
558
+ const areaName = (s) => s.replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'area';
559
+ /** Add an area for `dir` named `first`; a name taken already gets the directory's whole path, then -2, -3 … */
560
+ function addArea(out, dir, first, globs) {
561
+ const whole = areaName(dir.replace(/\//g, '-'));
562
+ let name = areaName(first);
563
+ if (name in out)
564
+ name = whole;
565
+ for (let i = 2; name in out; i++)
566
+ name = `${whole}-${i}`;
567
+ out[name] = globs;
568
+ return name;
569
+ }
570
+ /**
571
+ * The area candidates of the repository (spec 025 R-5): one per workspace package (`<dir>/**`), one per
572
+ * top-level directory that holds no package (`<dir>/**`), and `docs` (`docs/**` and the root `*.md`) when
573
+ * there is either. A name taken already gets the directory's whole path, then -2, -3 …
574
+ */
575
+ export function areaCandidates(root) {
576
+ const out = {};
577
+ const add = (dir, first, globs) => addArea(out, dir, first, globs);
578
+ const pkgs = workspacePackages(root).filter((p) => SAFE_DIR.test(p.dir));
579
+ for (const p of pkgs)
580
+ add(p.dir, p.dir.split('/').at(-1), [`${p.dir}/**`]);
581
+ let entries = [];
582
+ try {
583
+ entries = readdirSync(root, { withFileTypes: true })
584
+ .filter((e) => e.isDirectory())
585
+ .map((e) => e.name)
586
+ .toSorted();
587
+ }
588
+ catch {
589
+ // no directory to read: no area
590
+ }
591
+ for (const d of entries) {
592
+ if (d.startsWith('.') || NOT_AREAS.has(d) || !SAFE_DIR.test(d))
593
+ continue;
594
+ if (pkgs.some((p) => p.dir === d || p.dir.startsWith(`${d}/`)))
595
+ continue;
596
+ add(d, d, [`${d}/**`]);
597
+ }
598
+ let md = false;
599
+ try {
600
+ md = readdirSync(root).some((f) => f.endsWith('.md'));
601
+ }
602
+ catch {
603
+ // none
604
+ }
605
+ const docs = [...(entries.includes('docs') ? ['docs/**'] : []), ...(md ? ['*.md'] : [])];
606
+ if (docs.length)
607
+ add('docs', 'docs', docs);
608
+ return out;
609
+ }
610
+ /**
611
+ * The area of a directory a gate was found in (spec 025 R-5): the area of the deepest `<dir>/**` that holds
612
+ * it. The root, and a directory no area holds, have none: such a gate always runs.
613
+ */
614
+ export function areaOf(areas, dir) {
615
+ let best;
616
+ for (const [name, globs] of Object.entries(areas))
617
+ for (const g of globs) {
618
+ const base = /^(.+)\/\*\*$/.exec(g)?.[1];
619
+ if (base && (dir === base || dir.startsWith(`${base}/`)) && (!best || base.length > best.len))
620
+ best = { name, len: base.length };
621
+ }
622
+ return best?.name;
623
+ }
554
624
  /**
555
625
  * The discovery of installation (design §5, 024 S-10): the candidates chosen by default become `gates`,
556
- * the excluded ones are listed, and the ones only offered are `proposals`.
626
+ * the excluded ones are listed, and the ones only offered are `proposals`. Each gate and proposal carries
627
+ * the area of where it was found (spec 025 R-5); a root gate carries none and always runs.
557
628
  */
558
629
  export function discoverGates(root) {
559
630
  const candidates = detectCandidates(root);
631
+ const areas = areaCandidates(root);
632
+ // a directory a gate is found in that no area holds (a project of its own, outside the workspace) gets
633
+ // an area of its own, the shallow ones first so a directory below one is held by it
634
+ for (const c of candidates
635
+ .filter((x) => x.dir && SAFE_DIR.test(x.dir) && (x.status === 'pick' || x.status === 'offer'))
636
+ .toSorted((a, b) => a.dir.split('/').length - b.dir.split('/').length))
637
+ if (!areaOf(areas, c.dir))
638
+ addArea(areas, c.dir, c.dir.split('/').at(-1), [`${c.dir}/**`]);
639
+ const area = (c) => {
640
+ const a = areaOf(areas, c.dir);
641
+ return a ? { areas: [a] } : {};
642
+ };
560
643
  return {
561
644
  gates: candidates
562
645
  .filter((c) => c.status === 'pick')
@@ -566,14 +649,16 @@ export function discoverGates(root) {
566
649
  cmd: c.cmd,
567
650
  from: c.from,
568
651
  ...(c.optional ? { optional: true } : {}),
652
+ ...area(c),
569
653
  })),
570
654
  excluded: candidates
571
655
  .filter((c) => c.status === 'excluded')
572
656
  .map((c) => ({ name: c.script, cmd: c.cmd, why: c.reasons[0] ?? '' })),
573
657
  proposals: candidates
574
658
  .filter((c) => c.status === 'offer')
575
- .map((c) => ({ name: c.name, cmd: c.cmd, from: c.from })),
659
+ .map((c) => ({ name: c.name, cmd: c.cmd, from: c.from, ...area(c) })),
576
660
  candidates,
661
+ areas,
577
662
  };
578
663
  }
579
664
  /** The candidates offered and not chosen by default (`config gates --add`). */
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { REASON } from './detect.js';
3
+ import { areaOf, REASON } from './detect.js';
4
4
  import { forwards, workspacePackages } from './detect-workspaces.js';
5
5
  /** `<path>#x` and `<path>:x` are one source (the old notation, 024 S-11). */
6
6
  const normal = (from) => from.replace(/#(?!scripts\.)/, ':');
@@ -35,12 +35,13 @@ export function sourceThere(root, from) {
35
35
  return true;
36
36
  }
37
37
  const pieceWords = (cmd) => cmd.trim().split(/\s+/);
38
+ const scriptOf = (cmd) => cmd.split(' ').find((w) => ['test', 'vet', 'build', 'check', 'lint'].includes(w));
38
39
  /**
39
40
  * Pair the gates of the file with the candidates (024 S-11): the same command is the same gate whatever
40
41
  * the source; then the same source. A gate's own command may run candidates through the workspace
41
42
  * (`pnpm -r test`): those read `not applied, already runs`. Excluded candidates are not listed.
42
43
  */
43
- export function gateStatus(root, file, candidates) {
44
+ export function gateStatus(root, file, candidates, areas = {}) {
44
45
  let left = candidates.filter((c) => c.status !== 'excluded');
45
46
  const take = (match) => {
46
47
  const c = left.find(match);
@@ -63,19 +64,31 @@ export function gateStatus(root, file, candidates) {
63
64
  }
64
65
  };
65
66
  const same = (g, c) => normal(c.from) === normal(g.from);
66
- const scriptOf = (cmd) => cmd.split(' ').find((w) => ['test', 'vet', 'build', 'check', 'lint'].includes(w));
67
67
  pass((g, c) => c.cmd === g.cmd);
68
68
  pass((g, c) => same(g, c) && c.name === g.name, true);
69
69
  pass((g, c) => same(g, c) && c.script === scriptOf(g.cmd), true);
70
70
  pass(same, true);
71
71
  pass((g, c) => c.name === g.name, true);
72
+ const firstOf = new Map();
72
73
  for (const g of file) {
73
74
  const c = pair.get(g);
75
+ // removal candidates (spec 025 R-5): a command an earlier gate runs already, a candidate another
76
+ // script or gate runs, a source that is gone
77
+ const twin = firstOf.get(g.cmd);
78
+ if (!twin)
79
+ firstOf.set(g.cmd, g.name);
80
+ const removal = twin
81
+ ? `the same command as ${twin}`
82
+ : c?.status === 'covered'
83
+ ? 'something else runs it already'
84
+ : undefined;
74
85
  const base = {
75
86
  name: g.name,
76
87
  cmd: g.cmd,
77
88
  ...(g.from ? { from: g.from } : {}),
78
89
  ...(g.optional ? { optional: true } : {}),
90
+ ...(g.areas?.length ? { areas: g.areas } : {}),
91
+ ...(removal ? { removal } : {}),
79
92
  reasons: c ? c.reasons.filter((r) => !r.startsWith('unclear')) : [],
80
93
  };
81
94
  if (!g.from)
@@ -87,7 +100,11 @@ export function gateStatus(root, file, candidates) {
87
100
  found: { cmd: c.cmd, from: c.from },
88
101
  });
89
102
  else if (!c && !sourceThere(root, g.from))
90
- rows.push({ ...base, state: 'applied, source not found' });
103
+ rows.push({
104
+ ...base,
105
+ removal: base.removal ?? 'its source is not found',
106
+ state: 'applied, source not found',
107
+ });
91
108
  else
92
109
  rows.push({ ...base, state: 'applied' });
93
110
  }
@@ -112,12 +129,14 @@ export function gateStatus(root, file, candidates) {
112
129
  name = `${c.name}-${i}`;
113
130
  taken.add(name);
114
131
  const extra = by.get(c) ?? [];
132
+ const area = areaOf(areas, c.dir);
115
133
  rows.push({
116
134
  state: c.status === 'covered' || extra.length ? 'not applied, already runs' : 'not applied',
117
135
  name,
118
136
  cmd: c.cmd,
119
137
  from: c.from,
120
138
  ...(c.optional ? { optional: true } : {}),
139
+ ...(area ? { areas: [area] } : {}),
121
140
  reasons: [...c.reasons, ...extra.filter((r) => !c.reasons.includes(r))],
122
141
  });
123
142
  }
@@ -133,5 +152,16 @@ export function actionsOf(row) {
133
152
  export function formatGateRow(r) {
134
153
  const cmd = r.found ? `${r.cmd} → ${r.found.cmd}` : r.cmd;
135
154
  const why = r.reasons.length ? ` — ${r.reasons.join('; ')}` : '';
136
- return `${r.state.padEnd(27)} ${r.name} ${cmd}${r.from ? ` (${r.from})` : ''}${r.optional ? ' optional' : ''}${why}`;
155
+ const areas = ` [${r.areas?.length ? `areas: ${r.areas.join(', ')}` : 'always'}]`;
156
+ const removal = r.removal ? ` remove? ${r.removal}` : '';
157
+ return `${r.state.padEnd(27)} ${r.name} ${cmd}${r.from ? ` (${r.from})` : ''}${r.optional ? ' optional' : ''}${areas}${removal}${why}`;
158
+ }
159
+ /** The report's lines (spec 025 R-5): a heading for the removal candidates, then every other row. */
160
+ export function reportLines(rows) {
161
+ const out = [];
162
+ const remove = rows.filter((r) => r.removal);
163
+ if (remove.length)
164
+ out.push('removal candidates (look at these first):', ...remove.map(formatGateRow), '');
165
+ out.push(remove.length ? 'gates and candidates:' : 'gates and candidates (no removal candidate):', ...rows.filter((r) => !r.removal).map(formatGateRow));
166
+ return out;
137
167
  }