@bluenyang/reins 0.3.0 → 0.3.1-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.
@@ -8,7 +8,7 @@ import { overrides } from '../lib/blocks.js';
8
8
  import { repoRoot } from '../lib/git.js';
9
9
  import { BACK, EXIT } from '../lib/prompter.js';
10
10
  import { harnessVersion, packageHarness, packageVersion } from '../lib/upstream.js';
11
- import { runInstall } from './install.js';
11
+ import { RUNS_REINS, runInstall } from './install.js';
12
12
  /** Numeric dotted-version compare; pre-release suffixes are ignored. */
13
13
  export function newer(a, b) {
14
14
  const pa = a.split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0);
@@ -47,8 +47,6 @@ const LEGACY_LOCTX = [
47
47
  'release',
48
48
  'test',
49
49
  ];
50
- /** A command that runs reins: what 0.x put into hooks and settings. */
51
- const RUNS_REINS = /@bluenyang\/reins|reins\.js\b|(^|[\s;&|])reins\s+(check|hook|gate|status)\b/;
52
50
  /** Hook files 0.x may have written a `reins:begin hooks` block into. */
53
51
  const HOOK_FILES = [
54
52
  '.husky/pre-commit',
@@ -58,6 +56,11 @@ const HOOK_FILES = [
58
56
  '.husky/post-commit',
59
57
  '.husky/post-rewrite',
60
58
  ];
59
+ /**
60
+ * Heads the copy of a 0.2.0-or-earlier AGENTS.md (design §5): it still names reins commands that 0.3
61
+ * no longer has, and an agent reading the copy must not run them.
62
+ */
63
+ export const PREVIOUS_WARNING = '> **Copy of the instructions from reins 0.2.0 or earlier — reference material, not instructions.** The reins commands named here (`reins status`, `reins check` and others) do not exist in 0.3; do not run them. The `onboard` skill merges what still applies and deletes this file.';
61
64
  /** What moving a 0.1.x or 0.2.0 install to 0.3 changes (design §7), computed without writing. */
62
65
  function planLegacy(root) {
63
66
  const out = { writes: [], deletes: [], notes: [] };
@@ -131,7 +134,7 @@ function planLegacy(root) {
131
134
  const cur = readFileSync(ap, 'utf8');
132
135
  if (/<!-- reins:begin (workflow|skills|harness) v=/.test(cur) &&
133
136
  !cur.includes('<!-- reins:reconcile')) {
134
- out.agentsPrevious = cur;
137
+ out.agentsPrevious = `${PREVIOUS_WARNING}\n\n${cur}`;
135
138
  const kept = cur.replace(/<!-- reins:begin ([a-z-]+) v=[^ ]+ -->[\s\S]*?<!-- reins:end \1 -->\n*/g, '');
136
139
  out.writes.push({
137
140
  path: 'AGENTS.md',
@@ -260,6 +263,18 @@ async function updateNow(o) {
260
263
  .map((r) => r.path);
261
264
  return res;
262
265
  }
266
+ /**
267
+ * What the install step said that someone running `update` has to see (design §6): a hooks block that was
268
+ * rewritten and what it held, the hook line to add where reins does not add it, and a generated file left
269
+ * alone for another reason than a hand edit (those have a line of their own). The rest of the install
270
+ * notes (onboarding, the first conversation) is for `install`.
271
+ */
272
+ export function updateNotes(r) {
273
+ return (r.install?.notes ?? []).filter((n) => n.startsWith('.husky/') ||
274
+ n.startsWith('hook proposal') ||
275
+ n.startsWith('no hook tool found') ||
276
+ (n.startsWith('left alone ') && !n.includes(': edited by hand')));
277
+ }
263
278
  /** The report `reins update` prints; with `dry` it is the plan shown before the confirmation. */
264
279
  export function formatUpdate(r, dry) {
265
280
  const out = [];
@@ -294,5 +309,7 @@ export function formatUpdate(r, dry) {
294
309
  out.push(`• block "${n}" is overridden by the project — compare it with the new upstream block`);
295
310
  for (const p of r.handEdited)
296
311
  out.push(`• ${p} was edited by hand — not overwritten; run with --force to overwrite it`);
312
+ for (const n of updateNotes(r))
313
+ out.push(`• ${n}`);
297
314
  return `${out.join('\n')}\n`;
298
315
  }
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { parseBlocks } from './blocks.js';
4
- import { auditBinding, pmBinding, resolveRoles, } from './bindings.js';
4
+ import { KNOWN_TOOLS, auditBinding, auditFallback, pmBinding, resolveRoles, } from './bindings.js';
5
5
  /**
6
6
  * AGENTS.md managed blocks for 0.3 (design §5): the static blocks from the template plus the delegation
7
7
  * table, resolved from the team bindings when `config`, `install` or `update` writes — never at work time.
@@ -30,9 +30,27 @@ export function callLine(b, cli, writes) {
30
30
  return `\`${cli}\` with model \`${b.model}\``;
31
31
  }
32
32
  }
33
- const WRITES = new Set(['implementer', 'planner', 'auditor']);
33
+ /** Groups whose roles write files (`tools.write` in `harness/roles/<group>.md`); the others are called read-only. */
34
+ export const WRITES = new Set(['implementer', 'planner']);
34
35
  /** Where `config`, `install` and `update` write a person's own delegation table (spec 020 S-1). */
35
36
  export const LOCAL_DELEGATION = '.loctx/delegation.local.md';
37
+ /**
38
+ * The command that runs a vendor's agent: what the settings record, else the CLI reins knows for that vendor
39
+ * (openai is `codex`, not `openai`), else the vendor's name.
40
+ */
41
+ export const cliOf = (doc, vendor) => doc.tools?.[vendor]?.cli ?? KNOWN_TOOLS[vendor] ?? vendor;
42
+ /** When the PM may use a role's fallback line (design §5): the call cannot be made, not a disliked answer. */
43
+ 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.";
44
+ /** The fallback part of a role's "how to call" cell; empty when the role has none. */
45
+ function fallbackHow(doc, r) {
46
+ const f = r.fallback;
47
+ if (!f)
48
+ return '';
49
+ const how = f.vendor === 'claude'
50
+ ? `a general subagent on \`${f.model}\`, given the \`${r.role}\` section of \`.agents/harness/roles/${r.group}.md\``
51
+ : callLine(f, cliOf(doc, f.vendor), WRITES.has(r.group));
52
+ return `; fallback: ${f.vendor} ${f.model} — ${how}`;
53
+ }
36
54
  /**
37
55
  * The `## Delegation` section for this bindings file. `local` renders a person's own table: no pointer to
38
56
  * itself, and a Claude role names its `rs-*` file only when the team generated that file with the same model.
@@ -51,7 +69,7 @@ export function renderDelegation(doc, local) {
51
69
  const agents = claudeAgents(r);
52
70
  let k = 0;
53
71
  for (const b of r.models) {
54
- const cli = doc.tools?.[b.vendor]?.cli ?? b.vendor;
72
+ const cli = cliOf(doc, b.vendor);
55
73
  let how;
56
74
  if (b.vendor !== 'claude')
57
75
  how = callLine(b, cli, WRITES.has(r.group));
@@ -62,13 +80,17 @@ export function renderDelegation(doc, local) {
62
80
  ? `subagent \`${name}\``
63
81
  : `a general subagent on \`${b.model}\`, given the \`${r.role}\` section of \`.agents/harness/roles/${r.group}.md\``;
64
82
  }
65
- lines.push(`| ${r.group}/${r.role} | ${b.vendor} ${b.model} | ${how} |`);
83
+ lines.push(`| ${r.group}/${r.role} | ${b.vendor} ${b.model} | ${how}${fallbackHow(doc, r)} |`);
66
84
  }
67
85
  }
68
86
  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.');
87
+ // said only when some role has one, so a table without fallbacks reads exactly as before
88
+ if (resolveRoles(doc).some((x) => x.on && x.fallback))
89
+ lines.push('', FALLBACK_RULE);
69
90
  }
70
91
  const a = auditBinding(doc);
71
- lines.push('', `Audit: ${doc.audit?.required === false ? '**switched off by the user**' : '**required every version**'}; run it on ${a.vendor} ${a.model} in a fresh run that gets only the records, never this conversation.`);
92
+ const af = auditFallback(doc);
93
+ lines.push('', `Audit: ${doc.audit?.required === false ? '**switched off by the user**' : '**required every version**'}; run it 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 that gets only the records, never this conversation.`);
72
94
  return lines.join('\n');
73
95
  }
74
96
  /**
@@ -59,7 +59,14 @@ export function resolveRoles(doc) {
59
59
  continue;
60
60
  }
61
61
  if (own) {
62
- out.push({ group, role, on: true, models: [pair(own)], source: 'role' });
62
+ out.push({
63
+ group,
64
+ role,
65
+ on: true,
66
+ models: [pair(own)],
67
+ source: 'role',
68
+ ...(own.fallback ? { fallback: pair(own.fallback) } : {}),
69
+ });
63
70
  continue;
64
71
  }
65
72
  let picked;
@@ -69,7 +76,14 @@ export function resolveRoles(doc) {
69
76
  picked = [models[1] ?? models[0]];
70
77
  else
71
78
  picked = [models[0]];
72
- out.push({ group, role, on: true, models: picked, source: 'group' });
79
+ out.push({
80
+ group,
81
+ role,
82
+ on: true,
83
+ models: picked,
84
+ source: 'group',
85
+ ...(spec?.fallback ? { fallback: pair(spec.fallback) } : {}),
86
+ });
73
87
  }
74
88
  }
75
89
  return out;
@@ -87,6 +101,38 @@ export function auditBinding(doc) {
87
101
  const ms = a ? groupModels(a) : [];
88
102
  return ms[0] ?? pmBinding(doc);
89
103
  }
104
+ /** The fallback of the model `auditBinding` names, if the file gives one. */
105
+ export function auditFallback(doc) {
106
+ const a = doc.groups?.auditor;
107
+ const own = a?.roles?.auditor;
108
+ if (own)
109
+ return own.fallback ? pair(own.fallback) : undefined;
110
+ return a && groupModels(a).length && a.fallback ? pair(a.fallback) : undefined;
111
+ }
112
+ const same = (a, b) => a.vendor === b.vendor && a.model === b.model;
113
+ /**
114
+ * What is wrong with the fallbacks of one file (team or personal), judged on that file alone: a fallback
115
+ * needs a model beside it in the same place, and must be another model. A group with a fallback and no
116
+ * model would switch the group off for that person (`mergeLocal` replaces a group as a whole).
117
+ */
118
+ export function fallbackProblems(doc) {
119
+ const out = [];
120
+ for (const [g, spec] of Object.entries(doc.groups ?? {})) {
121
+ if (!spec)
122
+ continue;
123
+ const models = groupModels(spec);
124
+ if (spec.fallback) {
125
+ if (models.length === 0)
126
+ out.push(`${g}: a fallback needs the group's model in the same file — set the model first`);
127
+ else if (models.some((m) => same(m, spec.fallback)))
128
+ out.push(`${g}: the fallback is the group's own model (${spec.fallback.model})`);
129
+ }
130
+ for (const [r, b] of Object.entries(spec.roles ?? {}))
131
+ if (b.fallback && same(b, b.fallback))
132
+ out.push(`${g}.${r}: the fallback is the role's own model (${b.model})`);
133
+ }
134
+ return out;
135
+ }
90
136
  /** Whether the per-version audit is mandatory (design §3-3): true unless the file says false. */
91
137
  export const auditRequired = (doc) => doc.audit?.required !== false;
92
138
  /** The local override wins per key: mode, audit, default, each tool and each group as a whole. */
@@ -133,7 +179,7 @@ export const V1_ROLE_MAP = {
133
179
  const DROPPED_V1_KEYS = ['escalation', 'limits'];
134
180
  /**
135
181
  * A version-1 `bindings.yaml` (`roles.<r>: {vendor, model, enabled, fallback, parallel}`, `vendors`)
136
- * as version 2. The result is single mode; the converted groups take effect once the user switches to
182
+ * 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
137
183
  * multi with `config`. `notes` says what moved and what was dropped, for the user to confirm.
138
184
  */
139
185
  export function convertV1(v1) {
@@ -144,6 +190,20 @@ export function convertV1(v1) {
144
190
  const bindingOf = (v) => isObj(v) && typeof v['vendor'] === 'string' && typeof v['model'] === 'string'
145
191
  ? { vendor: v['vendor'], model: v['model'] }
146
192
  : null;
193
+ // a version-1 fallback: `{vendor, model}`, or a model id alone (its vendor read from the id)
194
+ const fallbackOf = (v) => {
195
+ if (typeof v !== 'string' || !v.trim())
196
+ return bindingOf(v);
197
+ const m = v.trim();
198
+ const vendor = m.startsWith('gpt')
199
+ ? 'openai'
200
+ : m.startsWith('gemini')
201
+ ? 'google'
202
+ : m.startsWith('cursor-')
203
+ ? 'cursor'
204
+ : 'claude';
205
+ return { vendor, model: m };
206
+ };
147
207
  const pm = bindingOf(roles['pm']);
148
208
  if (pm)
149
209
  doc.default = pm;
@@ -164,19 +224,31 @@ export function convertV1(v1) {
164
224
  continue;
165
225
  doc.groups ??= {};
166
226
  const spec = (doc.groups[target.group] ??= {});
227
+ // the fallback moves with the model it belongs to (design §5); it is dropped when that model did not
228
+ // become the group's, when it cannot be read, or when it is the model itself
229
+ const fb = isObj(raw) && 'fallback' in raw ? fallbackOf(raw['fallback']) : null;
230
+ const usable = fb && !(fb.vendor === b.vendor && fb.model === b.model) ? fb : null;
231
+ let carried = false;
167
232
  if (target.role) {
168
233
  spec.roles ??= {};
169
- spec.roles[target.role] = b;
234
+ spec.roles[target.role] = usable ? { ...b, fallback: usable } : b;
235
+ carried = !!usable;
170
236
  }
171
237
  else if (!spec.vendor) {
172
238
  spec.vendor = b.vendor;
173
239
  spec.model = b.model;
240
+ if (usable)
241
+ spec.fallback = usable;
242
+ carried = !!usable;
174
243
  }
175
244
  const where = target.role ? `${target.group}.${target.role}` : target.group;
176
245
  notes.push(`role ${name} → ${where} (${b.vendor} ${b.model})`);
177
- for (const k of ['fallback', 'parallel'])
178
- if (isObj(raw) && k in raw)
179
- notes.push(`role ${name}: ${k} dropped (no run-time keys)`);
246
+ if (isObj(raw) && 'fallback' in raw)
247
+ notes.push(carried
248
+ ? `role ${name}: fallback → ${where} (${usable.vendor} ${usable.model})`
249
+ : `role ${name}: fallback dropped (${fb ? (usable ? 'its model is not the one kept' : 'same as the model') : 'not a model'})`);
250
+ if (isObj(raw) && 'parallel' in raw)
251
+ notes.push(`role ${name}: parallel dropped (no run-time keys)`);
180
252
  }
181
253
  if (isObj(v1['vendors'])) {
182
254
  doc.tools = {};
@@ -228,7 +228,12 @@ export function vendorOf(model) {
228
228
  return 'claude';
229
229
  }
230
230
  /** Model IDs seen working in this environment. */
231
- export const CONFIRMED_MODELS = new Set(['claude-opus-5-5', 'claude-fable-5-1']);
231
+ export const CONFIRMED_MODELS = new Set([
232
+ 'claude-opus-5-5',
233
+ 'claude-fable-5-1',
234
+ 'gpt-6-sol',
235
+ 'gpt-6-luna',
236
+ ]);
232
237
  /** Runs `<cli> models` without a shell, stdin closed, 10 s limit. Nothing else is ever run. */
233
238
  export const spawnModels = (cli, args) => {
234
239
  if (process.env['REINS_NO_VENDOR_SPAWN'])
@@ -0,0 +1,82 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ /** The file a `from` points into: `a/package.json#scripts.x`, `a/Makefile:test`, `a/go.mod`. */
4
+ const sourceFile = (from) => from.split('#')[0].replace(/:[^/:]*$/, '');
5
+ /**
6
+ * Compare the file with the discovery, in this order: same source and command → the same gate, no
7
+ * difference; same source and name → `changed`; same name → `changed` (the root `check` now points at
8
+ * another script); what is left of the discovery is `new`, and of the file `gone`. A gate without `from`
9
+ * is the user's own: it is listed and never paired, changed or removed.
10
+ */
11
+ export function diffGates(root, file, found) {
12
+ const out = [];
13
+ let mine = file.filter((g) => g.from);
14
+ let theirs = [...found];
15
+ const pair = (match, emit) => {
16
+ const left = [];
17
+ for (const f of mine) {
18
+ const i = theirs.findIndex((d) => match(f, d));
19
+ if (i < 0) {
20
+ left.push(f);
21
+ continue;
22
+ }
23
+ emit?.(f, theirs[i]);
24
+ theirs = theirs.filter((_, k) => k !== i);
25
+ }
26
+ mine = left;
27
+ };
28
+ const changed = (f, d) => out.push({
29
+ kind: 'changed',
30
+ name: f.name,
31
+ cmd: d.cmd,
32
+ from: d.from,
33
+ was: { cmd: f.cmd, from: f.from },
34
+ });
35
+ pair((f, d) => f.from === d.from && f.cmd === d.cmd);
36
+ pair((f, d) => f.from === d.from && f.name === d.name, changed);
37
+ pair((f, d) => f.name === d.name, changed);
38
+ const taken = new Set(file.map((g) => g.name));
39
+ for (const d of theirs) {
40
+ let name = d.name;
41
+ for (let i = 2; taken.has(name); i++)
42
+ name = `${d.name}-${i}`;
43
+ taken.add(name);
44
+ out.push({
45
+ kind: 'new',
46
+ name,
47
+ cmd: d.cmd,
48
+ from: d.from,
49
+ ...(d.optional ? { optional: true } : {}),
50
+ });
51
+ }
52
+ for (const f of mine)
53
+ out.push({
54
+ kind: 'gone',
55
+ name: f.name,
56
+ cmd: f.cmd,
57
+ from: f.from,
58
+ why: existsSync(join(root, sourceFile(f.from)))
59
+ ? 'no longer proposed: its script or target is gone, or another gate now covers it'
60
+ : `its source is gone (${sourceFile(f.from)})`,
61
+ });
62
+ for (const g of file.filter((x) => !x.from))
63
+ out.push({ kind: 'yours', name: g.name, cmd: g.cmd });
64
+ const order = { changed: 0, gone: 1, new: 2, yours: 3 };
65
+ return out.toSorted((a, b) => order[a.kind] - order[b.kind]);
66
+ }
67
+ /** The differences the user can apply (`yours` is only shown). */
68
+ export const applicable = (diff) => diff.filter((d) => d.kind !== 'yours');
69
+ /** One line per difference, for the report and the screen. */
70
+ export function formatGateDiff(d) {
71
+ const tag = d.kind.padEnd(8);
72
+ switch (d.kind) {
73
+ case 'new':
74
+ return `${tag}${d.name} ${d.cmd} (${d.from})${d.optional ? ' optional' : ''}`;
75
+ case 'changed':
76
+ return `${tag}${d.name} ${d.was.cmd} → ${d.cmd} (${d.was.from === d.from ? d.from : `${d.was.from} → ${d.from}`})`;
77
+ case 'gone':
78
+ return `${tag}${d.name} ${d.cmd} (${d.from}) — ${d.why}`;
79
+ default:
80
+ return `${tag}${d.name} ${d.cmd} (written by hand — left alone)`;
81
+ }
82
+ }
@@ -0,0 +1,77 @@
1
+ import { parse } from 'yaml';
2
+ /**
3
+ * The project's gate script (design §6): one POSIX shell file that runs the required commands of
4
+ * `gates.yaml` in order and keeps their output, so a hook tool needs one line and the audit can tell
5
+ * whether a commit passed. reins writes it; nothing in it calls reins or the network.
6
+ */
7
+ export const GATE_SCRIPT = '.agents/harness/run-gates.sh';
8
+ /** Where the script keeps its logs: one file per tree hash of what was checked. */
9
+ export const GATE_LOGS = '.loctx/reports/gates';
10
+ /** The one line a hook tool runs for a stage (`pre-commit`, `pre-push`). */
11
+ export const hookLine = (stage) => `sh ${GATE_SCRIPT} ${stage}`;
12
+ /** The required (not optional) gate commands of a `gates.yaml` text, in its order. */
13
+ export function requiredGates(text) {
14
+ if (text === undefined)
15
+ return [];
16
+ const g = parse(text);
17
+ const gates = g?.gates ?? {};
18
+ return (g?.order ?? Object.keys(gates))
19
+ .map((n) => gates[n])
20
+ .filter((x) => !!x?.cmd && !x.optional)
21
+ .map((x) => x.cmd);
22
+ }
23
+ const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
24
+ /** The script for these commands. The commands are written in, so the hook line never changes with them. */
25
+ export function renderGateScript(cmds) {
26
+ return `#!/bin/sh
27
+ # generated by reins from .agents/harness/gates.yaml — do not edit; \`reins config gates\` or \`reins update\` rewrites it
28
+ #
29
+ # Runs the project's required checks in order and keeps their output in ${GATE_LOGS}/<tree>.log,
30
+ # where <tree> is the tree hash of what is checked: \`git rev-parse <commit>^{tree}\` names a commit's log.
31
+ # Usage: sh ${GATE_SCRIPT} <stage> (pre-commit, pre-push, audit, or any name of your own)
32
+ stage="\${1:-manual}"
33
+ root=$(git rev-parse --show-toplevel 2>/dev/null) || {
34
+ echo "run-gates: not inside a git work tree" >&2
35
+ exit 2
36
+ }
37
+ cd "$root" || exit 2
38
+ # pre-commit checks what is about to be committed (the index git prepared for this commit); every other
39
+ # stage checks HEAD. The checks run in the work tree, so a work tree that differs from that tree — a
40
+ # changed file left out of it, or a file git does not track and does not ignore — is "dirty", and the run
41
+ # is no evidence for it.
42
+ worktree=dirty
43
+ if [ "$stage" = pre-commit ]; then
44
+ tree=$(git write-tree 2>/dev/null)
45
+ if git diff --quiet 2>/dev/null; then worktree=clean; fi
46
+ else
47
+ tree=$(git rev-parse --verify --quiet 'HEAD^{tree}')
48
+ if git diff --quiet HEAD 2>/dev/null; then worktree=clean; fi
49
+ fi
50
+ if [ -n "$(git ls-files --others --exclude-standard 2>/dev/null)" ]; then worktree=dirty; fi
51
+ [ -n "$tree" ] || {
52
+ echo "run-gates: cannot tell which tree is being checked" >&2
53
+ exit 2
54
+ }
55
+ dir=${GATE_LOGS}
56
+ mkdir -p "$dir" || exit 2
57
+ log="$dir/$tree.log"
58
+ status="$dir/.status.$$"
59
+ printf '== %s stage: %s worktree: %s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$stage" "$worktree" >>"$log"
60
+ code=0
61
+ run() {
62
+ [ "$code" -eq 0 ] || return 0
63
+ printf '$ %s\\n' "$1" | tee -a "$log"
64
+ {
65
+ sh -c "$1" 2>&1
66
+ echo $? >"$status"
67
+ } | tee -a "$log"
68
+ code=$(cat "$status" 2>/dev/null || echo 1)
69
+ rm -f "$status"
70
+ # output that did not end its last line must not run into the next record
71
+ if [ -n "$(tail -c 1 "$log")" ]; then echo >>"$log"; fi
72
+ }
73
+ ${cmds.map((c) => `run ${quote(c)}`).join('\n')}
74
+ printf 'exit: %s\\n' "$code" >>"$log"
75
+ exit "$code"
76
+ `;
77
+ }
@@ -4,12 +4,14 @@ import { workTreeReader } from './reader.js';
4
4
  import { resolveRoles } from './bindings.js';
5
5
  import { agentName, claudeAgents } from './agents-md.js';
6
6
  import { splitFrontmatter } from './skills.js';
7
+ import { GATE_SCRIPT, renderGateScript, requiredGates } from './gate-script.js';
7
8
  /**
8
9
  * Files generated from `.agents/harness/` (design §6): `.claude/agents/rs-<group>-<role>.md` for roles
9
- * switched on in multi mode on a Claude model, the `.claude/skills/` copy, and `.claude/settings.json` deny
10
- * rules. Generated from the committed team file only, so no personal override makes drift.
10
+ * switched on in multi mode on a Claude model, the `.claude/skills/` copy, `.claude/settings.json` deny
11
+ * rules, and the gate script `.agents/harness/run-gates.sh` from `gates.yaml`. Generated from the committed team file only, so no personal override makes drift.
11
12
  */
12
13
  export const MANIFEST = '.agents/harness/generated.yaml';
14
+ export const SETTINGS_SCHEMA = 'https://json.schemastore.org/claude-code-settings.json';
13
15
  export const sha = (s) => createHash('sha256').update(s).digest('hex').slice(0, 16);
14
16
  export function readGroup(text) {
15
17
  const { data, body } = splitFrontmatter(text);
@@ -136,12 +138,23 @@ export function generateVendorFiles(root, rd = workTreeReader(root)) {
136
138
  why: `skill ${name}`,
137
139
  });
138
140
  }
141
+ // the gate script follows gates.yaml; with no required gate there is nothing to run and no script
142
+ const gateCmds = requiredGates(rd.read(`${harness}/gates.yaml`));
143
+ if (gateCmds.length)
144
+ out.writes.push({
145
+ path: GATE_SCRIPT,
146
+ content: renderGateScript(gateCmds),
147
+ why: 'the project gates, with their output kept',
148
+ });
139
149
  const redText = rd.read(`${harness}/policy/common-red-lines.yaml`);
140
- if (redText !== undefined)
150
+ if (redText !== undefined) {
151
+ const deny = denyRules(parse(redText).rules);
141
152
  out.writes.push({
142
153
  path: '.claude/settings.json',
143
- content: `${JSON.stringify({ $schema: 'https://json.schemastore.org/claude-code-settings.json', permissions: { deny: denyRules(parse(redText).rules) } }, null, 2)}\n`,
154
+ content: `${JSON.stringify({ $schema: SETTINGS_SCHEMA, permissions: { deny } }, null, 2)}\n`,
144
155
  why: 'secrets, force push, hook bypass',
156
+ deny,
145
157
  });
158
+ }
146
159
  return out;
147
160
  }
@@ -1,19 +1,69 @@
1
1
  import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { parse, stringify } from 'yaml';
4
- import { MANIFEST, sha } from './generate.js';
4
+ import { MANIFEST, SETTINGS_SCHEMA, sha } from './generate.js';
5
5
  import { workTreeReader } from './reader.js';
6
6
  export function readManifest(root, rd = workTreeReader(root)) {
7
7
  const text = rd.read(MANIFEST);
8
8
  if (text === undefined)
9
9
  return { schema: 'reins/generated@1', files: {} };
10
10
  const m = parse(text);
11
- return { schema: 'reins/generated@1', files: m?.files ?? {} };
11
+ return {
12
+ schema: 'reins/generated@1',
13
+ files: m?.files ?? {},
14
+ ...(m?.owned ? { owned: m.owned } : {}),
15
+ };
16
+ }
17
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
18
+ /**
19
+ * `.claude/settings.json` with reins' deny rules merged in (design §6). Only the rules reins wrote are
20
+ * its own: `was` (what it wrote last time) minus `now` leaves, `now` is appended where missing, and every
21
+ * other key and entry stays as the user has it, in order. Null when the text is not a settings object.
22
+ */
23
+ export function mergeSettings(text, now, was) {
24
+ let doc;
25
+ try {
26
+ doc = JSON.parse(text);
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ if (!isObj(doc))
32
+ return null;
33
+ // only an absent key gets a default: a `null` the user wrote is another shape, not ours to replace
34
+ const perms = 'permissions' in doc ? doc['permissions'] : {};
35
+ if (!isObj(perms))
36
+ return null;
37
+ const cur = 'deny' in perms ? perms['deny'] : [];
38
+ if (!Array.isArray(cur))
39
+ return null;
40
+ const gone = new Set(was.filter((r) => !now.includes(r)));
41
+ const kept = cur.filter((r) => !(typeof r === 'string' && gone.has(r)));
42
+ const deny = [...kept, ...now.filter((r) => !kept.includes(r))];
43
+ const out = '$schema' in doc ? { ...doc } : { $schema: SETTINGS_SCHEMA, ...doc };
44
+ const nextPerms = { ...perms, deny };
45
+ if (deny.length === 0 && !('deny' in perms))
46
+ delete nextPerms['deny'];
47
+ if ('permissions' in doc || Object.keys(nextPerms).length)
48
+ out['permissions'] = nextPerms;
49
+ return `${JSON.stringify(out, null, 2)}\n`;
50
+ }
51
+ /** The string rules in `permissions.deny` of a settings file; empty when it has none or cannot be read. */
52
+ function settingsDeny(text) {
53
+ try {
54
+ const doc = JSON.parse(text);
55
+ const d = doc?.permissions?.deny;
56
+ return Array.isArray(d) ? d.filter((r) => typeof r === 'string') : [];
57
+ }
58
+ catch {
59
+ return [];
60
+ }
12
61
  }
13
62
  /**
14
63
  * Write generated files without trampling anyone (design §6): reins overwrites only what it wrote and
15
64
  * nobody touched since; a hand-edited one is refused (listed) unless `force`; a file it never wrote is
16
- * always left alone.
65
+ * always left alone. `.claude/settings.json` is the exception: it is merged, never refused for holding
66
+ * the user's entries, and `force` changes nothing for it.
17
67
  */
18
68
  export function writeGenerated(root, gen, dryRun, force = false) {
19
69
  const res = {
@@ -22,12 +72,46 @@ export function writeGenerated(root, gen, dryRun, force = false) {
22
72
  unchanged: [],
23
73
  refused: [],
24
74
  };
25
- const before = readManifest(root).files;
75
+ const manifest = readManifest(root);
76
+ const before = manifest.files;
77
+ const ownedBefore = manifest.owned ?? {};
26
78
  const after = {};
79
+ const owned = {};
27
80
  const wanted = new Set(gen.writes.map((w) => w.path));
28
81
  for (const w of gen.writes) {
29
82
  const abs = join(root, w.path);
30
83
  const next = sha(w.content);
84
+ if (w.deny && existsSync(abs)) {
85
+ const text = readFileSync(abs, 'utf8');
86
+ // no list yet (0.3.0 or earlier): an untouched file is all reins', a touched one is only added to
87
+ const was = ownedBefore[w.path] ?? (before[w.path] === sha(text) ? settingsDeny(text) : []);
88
+ const merged = mergeSettings(text, w.deny, was);
89
+ if (merged === null) {
90
+ res.refused.push({
91
+ path: w.path,
92
+ why: 'not a settings object reins can merge into (invalid JSON, or `permissions` / `permissions.deny` of another shape) — left alone; fix it and run `reins update`',
93
+ });
94
+ const prior = before[w.path];
95
+ if (prior)
96
+ after[w.path] = prior;
97
+ const priorOwned = ownedBefore[w.path];
98
+ if (priorOwned)
99
+ owned[w.path] = priorOwned;
100
+ continue;
101
+ }
102
+ if (merged === text)
103
+ res.unchanged.push(w.path);
104
+ else {
105
+ if (!dryRun)
106
+ writeFileSync(abs, merged);
107
+ res.written.push(w.path);
108
+ }
109
+ after[w.path] = sha(merged);
110
+ owned[w.path] = w.deny;
111
+ continue;
112
+ }
113
+ if (w.deny)
114
+ owned[w.path] = w.deny;
31
115
  if (!existsSync(abs)) {
32
116
  if (!dryRun) {
33
117
  mkdirSync(dirname(abs), { recursive: true });
@@ -67,6 +151,26 @@ export function writeGenerated(root, gen, dryRun, force = false) {
67
151
  const abs = join(root, path);
68
152
  if (!existsSync(abs))
69
153
  continue;
154
+ const mine = ownedBefore[path];
155
+ if (mine) {
156
+ // a merged file is shared with the user and never deleted: take reins' rules out, leave the rest
157
+ const text = readFileSync(abs, 'utf8');
158
+ const rest = mergeSettings(text, [], mine);
159
+ if (rest === null) {
160
+ res.refused.push({
161
+ path,
162
+ why: 'no longer generated, but not a settings object reins can take its rules out of — left alone; fix it and run `reins update`',
163
+ });
164
+ after[path] = hash;
165
+ owned[path] = mine;
166
+ }
167
+ else if (rest !== text) {
168
+ if (!dryRun)
169
+ writeFileSync(abs, rest);
170
+ res.written.push(path);
171
+ }
172
+ continue;
173
+ }
70
174
  if (sha(readFileSync(abs, 'utf8')) === hash || force) {
71
175
  if (!dryRun)
72
176
  unlinkSync(abs);
@@ -80,10 +184,11 @@ export function writeGenerated(root, gen, dryRun, force = false) {
80
184
  after[path] = hash;
81
185
  }
82
186
  }
83
- const changed = JSON.stringify(after) !== JSON.stringify(before);
187
+ const changed = JSON.stringify(after) !== JSON.stringify(before) ||
188
+ JSON.stringify(owned) !== JSON.stringify(ownedBefore);
84
189
  if (changed && !dryRun) {
85
190
  mkdirSync(dirname(join(root, MANIFEST)), { recursive: true });
86
- writeFileSync(join(root, MANIFEST), `# vendor files generated by reins — do not edit; \`reins update\` rewrites it\n${stringify({ schema: 'reins/generated@1', files: after })}`);
191
+ writeFileSync(join(root, MANIFEST), `# vendor files generated by reins — do not edit; \`reins update\` rewrites it\n${stringify({ schema: 'reins/generated@1', files: after, ...(Object.keys(owned).length ? { owned } : {}) })}`);
87
192
  }
88
193
  return res;
89
194
  }