@bluenyang/reins 0.3.3 → 0.3.4-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.
package/README.md CHANGED
@@ -15,7 +15,7 @@ knowledge lost in gitignored space, copies that drift apart. The full list is in
15
15
 
16
16
  ## Status
17
17
 
18
- **0.3.3-rc.1 is the release candidate** (intent 023): `npx @bluenyang/reins@0.3.3-rc.1`. **0.3.2 is the latest release** (intents 019–022): `npx @bluenyang/reins install`. Up to 0.2.0, skills and hooks called `npx @bluenyang/reins` during work; 0.3 removes that, and `reins update` moves a 0.1.x or 0.2.0 install over. What changed in each version is in [CHANGELOG.md](CHANGELOG.md); what comes next is in the [roadmap](docs/ROADMAP.md).
18
+ **0.3.4-rc.2 is the release candidate** (intent 024): `npx @bluenyang/reins@0.3.4-rc.2`. **0.3.3 is the latest release** (intents 019–023): `npx @bluenyang/reins install`. Up to 0.2.0, skills and hooks called `npx @bluenyang/reins` during work; 0.3 removes that, and `reins update` moves a 0.1.x or 0.2.0 install over. What changed in each version is in [CHANGELOG.md](CHANGELOG.md); what comes next is in the [roadmap](docs/ROADMAP.md).
19
19
 
20
20
  ## How it works
21
21
 
@@ -68,7 +68,7 @@ To work on reins itself: `git clone https://github.com/bluenyang/reins.git`, the
68
68
  | `install` | places the harness, detects agent tools, confirms gates, writes the gate script `.agents/harness/run-gates.sh` (it runs the project's gate commands and keeps their output for the audit) and proposes the one hook line that calls it (`--hooks` adds it to husky), adds the onboarding note; `--mode manual\|auto`, `--dry-run`, `--json` |
69
69
  | `migrate` | moves an older harness or an `.ai/` workspace onto this layout and keeps the previous `AGENTS.md` aside for the PM to reconcile; `--legacy local\|committed`, `--dry-run` |
70
70
  | `update` | re-applies the packaged harness; asks before overwriting a generated file edited by hand (`--force`); moves a 0.1.x or 0.2.0 install to 0.3 and lists its old working files (`--yes` deletes them) |
71
- | `config` | a screen on a terminal: models and roles, agent tools, mode (single or multi), audit; `config bindings` and `config gates` take flags (`configure` is an alias). `config gates --refresh` finds the project's checks again, shows what differs from `gates.yaml` (new, changed, gone) and applies only what you pick (`--apply <name…|all>` without a terminal); the screen has a `gates` item for the same. A group or a role may name a fallback model (`config bindings --fallback <group>[.<role>]=<model>`): its call line goes into the delegation table, for when the first model cannot be called |
71
+ | `config` | a screen on a terminal: models and roles, agent tools, mode (single or multi), audit; `config bindings` and `config gates` take flags (`configure` is an alias). `config gates --refresh` finds the project's checks again (scripts by name and body, workspaces, CI), shows every gate and candidate with its state and reasons — applied, not applied, already run by another — leaves the same list in `.loctx/gates-refresh.md`, and changes `gates.yaml` only as you pick (`--apply <name…|all|remove:name>` without a terminal); it never calls a gate gone; the screen has a `gates` item for the same. A group or a role may name a fallback model (`config bindings --fallback <group>[.<role>]=<model>`): its call line goes into the delegation table, for when the first model cannot be called |
72
72
 
73
73
  ## Skills
74
74
 
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { applicable, formatGateDiff } from '../lib/gate-refresh.js';
3
+ import { actionsOf, formatGateRow } from '../lib/gate-refresh.js';
4
4
  import { GATE_SCRIPT } from '../lib/gate-script.js';
5
5
  import { BACK, EXIT } from '../lib/prompter.js';
6
- import { configureGates, fileGates, gateDiff } from './configure.js';
6
+ import { configureGates, fileGates, gateRows, REFRESH_LIST, writeRefreshList, } from './configure.js';
7
7
  import { hookTool } from './install.js';
8
8
  const GATES = '.agents/harness/gates.yaml';
9
9
  /** The gates as the project has them now: name, command, source, in order; and what runs them. */
@@ -20,26 +20,26 @@ export function formatGates(root) {
20
20
  return lines.join('\n');
21
21
  }
22
22
  /**
23
- * Run the discovery again and let the user pick which differences to apply (design §9). Nothing is
24
- * written unless something is picked. Returns `exit` when the user left with Ctrl-C.
23
+ * Run the discovery again, show every gate and candidate with its state (024 S-11), leave the same list in
24
+ * `.loctx/gates-refresh.md`, and let the user pick what to add, remove or replace (S-13). Nothing is written
25
+ * to gates.yaml unless something is picked. Returns `exit` when the user left with Ctrl-C.
25
26
  */
26
27
  export async function refreshGates(root, prompter) {
27
- const diff = gateDiff(root);
28
- if (!diff) {
28
+ const rows = gateRows(root);
29
+ if (!rows) {
29
30
  prompter.note('no gates.yaml — run `reins install`');
30
31
  return 'done';
31
32
  }
32
- const can = applicable(diff);
33
- const yours = diff.filter((d) => d.kind === 'yours');
34
- if (yours.length)
35
- prompter.note(yours.map(formatGateDiff).join('\n'));
36
- if (can.length === 0) {
37
- prompter.note('gates: up to date — the discovery finds what gates.yaml holds');
38
- return 'done';
39
- }
33
+ writeRefreshList(root, rows);
34
+ prompter.note([...rows.map(formatGateRow), `(the same list: ${REFRESH_LIST})`].join('\n'));
35
+ const options = rows.flatMap((r) => actionsOf(r).map((a) => ({
36
+ value: `${a}:${r.name}`,
37
+ label: `${a} ${r.name}`,
38
+ hint: a === 'replace' ? `${r.cmd} → ${r.found.cmd}` : r.cmd,
39
+ })));
40
40
  const picked = await prompter.multiselect({
41
- message: 'Differences to apply to gates.yaml (nothing is changed unless picked)',
42
- options: can.map((d) => ({ value: d.name, label: formatGateDiff(d) })),
41
+ message: 'What to apply to gates.yaml (nothing is changed unless picked)',
42
+ options,
43
43
  initial: [],
44
44
  });
45
45
  if (picked === EXIT)
@@ -48,10 +48,17 @@ export async function refreshGates(root, prompter) {
48
48
  prompter.note('gates: nothing changed');
49
49
  return 'done';
50
50
  }
51
- const r = configureGates({ cwd: root, refresh: true, apply: picked });
51
+ // remove and replace of one gate together: the removal wins
52
+ const names = new Map();
53
+ for (const p of picked) {
54
+ const name = p.slice(p.indexOf(':') + 1);
55
+ if (!names.has(name) || p.startsWith('remove:'))
56
+ names.set(name, p);
57
+ }
58
+ const r = configureGates({ cwd: root, refresh: true, apply: [...names.values()] });
52
59
  prompter.note(r.refused
53
60
  ? `not changed: ${r.refused}`
54
- : `gates: applied ${r.applied?.join(', ')} — gates.yaml and ${GATE_SCRIPT} written; commit them (the hook line stays as it is)`);
61
+ : `gates: ${r.applied?.join(', ')} — gates.yaml written; commit it (the gate script reads it, the hook line stays)`);
55
62
  return 'done';
56
63
  }
57
64
  /** The gates item of the config screen: see the gates, find them again, add subdirectory proposals. */
@@ -62,7 +69,11 @@ export async function gatesScreen(root, prompter) {
62
69
  message: 'Gates',
63
70
  options: [
64
71
  { value: 'back', label: '< Configuration' },
65
- { value: 'refresh', label: 'refresh', hint: 'find the gates again and pick what to apply' },
72
+ {
73
+ value: 'refresh',
74
+ label: 'refresh',
75
+ hint: 'find the gates again, see each state, pick what to apply',
76
+ },
66
77
  { value: 'add', label: 'add subdirectory proposals' },
67
78
  ],
68
79
  });
@@ -1,3 +1,4 @@
1
+ import { applyLocalForcePush, FORCE_WITH_LEASE_QUESTION, recordedForceWithLease, } from '../lib/local-settings.js';
1
2
  import { gatesScreen } from './config-gates.js';
2
3
  import { effectiveBindings, resolveRoles } from '../lib/bindings.js';
3
4
  import { newModelCache, vendors } from '../lib/detect.js';
@@ -5,7 +6,7 @@ import { repoRoot } from '../lib/git.js';
5
6
  import { groupLine, modelsScreen } from './config-models.js';
6
7
  import { configureBindings } from './configure.js';
7
8
  import { LOCAL_DELEGATION_NOTE } from '../lib/local-delegation.js';
8
- import { clackPrompter, isInteractive } from '../lib/prompter.js';
9
+ import { BACK, clackPrompter, EXIT, isInteractive } from '../lib/prompter.js';
9
10
  export const CONFIG_HINT = 'change with: reins config bindings --set <group|group.role>=<model> [--fallback <group|group.role>=<model|none>] [--local] (see: reins config bindings --help)';
10
11
  /** The effective settings as text: mode, audit, each role that is on. */
11
12
  export function formatBindings(doc) {
@@ -55,6 +56,7 @@ export async function runConfig(o = {}) {
55
56
  const detect = o.detectVendors ?? vendors;
56
57
  for (;;) {
57
58
  const doc = effectiveBindings(root);
59
+ const lease = recordedForceWithLease(root);
58
60
  const v = await prompter.select({
59
61
  message: 'Configuration',
60
62
  options: [
@@ -66,6 +68,11 @@ export async function runConfig(o = {}) {
66
68
  label: `audit: ${doc?.audit?.required === false ? 'off' : 'required'}`,
67
69
  },
68
70
  { value: 'gates', label: 'gates', hint: 'the project checks: see them, find them again' },
71
+ {
72
+ value: 'lease',
73
+ label: `force push with lease (this machine): ${lease === 'allow' ? 'not denied' : lease === 'deny' ? 'denied' : 'not asked yet'}`,
74
+ hint: 'local: .claude/settings.local.json',
75
+ },
69
76
  { value: 'exit', label: 'exit' },
70
77
  ],
71
78
  });
@@ -82,6 +89,19 @@ export async function runConfig(o = {}) {
82
89
  return 0;
83
90
  continue;
84
91
  }
92
+ if (v === 'lease') {
93
+ // personal, this machine only (024 S-26a)
94
+ const deny = await prompter.confirm({
95
+ message: FORCE_WITH_LEASE_QUESTION,
96
+ initial: lease !== 'allow',
97
+ });
98
+ if (deny === EXIT)
99
+ return 0;
100
+ if (deny === BACK)
101
+ continue;
102
+ prompter.note(applyLocalForcePush(root, deny ? 'deny' : 'allow').note);
103
+ continue;
104
+ }
85
105
  if (v === 'tools') {
86
106
  const found = detect();
87
107
  const picked = await prompter.multiselect({
@@ -1,8 +1,9 @@
1
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
3
  import { join } from 'node:path';
3
4
  import { isScalar, isSeq, parse, parseDocument } from 'yaml';
4
5
  import { discoverGates, subdirProposals, vendorOf, vendors, } from '../lib/detect.js';
5
- import { applicable, diffGates } from '../lib/gate-refresh.js';
6
+ import { actionsOf, formatGateRow, gateStatus, } from '../lib/gate-refresh.js';
6
7
  import { GROUP_ROLES, GROUPS, effectiveBindings, fallbackProblems, readLocalBindings, readTeam, resolveRoles, validateBindings, writeBindings, } from '../lib/bindings.js';
7
8
  import { modeChangedNote, placeNote, renderBlocks } from '../lib/agents-md.js';
8
9
  import { applyBlocks } from '../lib/blocks.js';
@@ -284,22 +285,49 @@ function appendOrder(doc, name) {
284
285
  const gates = doc.toJS()?.gates ?? {};
285
286
  doc.set('order', doc.createNode([...Object.keys(gates).filter((n) => n !== name), name]));
286
287
  }
287
- /** How gates.yaml differs from what the discovery of installation finds now (design §9). */
288
- export function gateDiff(root) {
288
+ /** The refresh rows of gates.yaml against the discovery (024 S-11), or null without gates.yaml. */
289
+ export function gateRows(root) {
289
290
  const path = join(root, GATES);
290
291
  if (!existsSync(path))
291
292
  return null;
292
- const found = discoverGates(root);
293
- return diffGates(root, fileGates(readFileSync(path, 'utf8')), [
294
- ...found.gates,
295
- ...found.proposals,
296
- ]);
293
+ return gateStatus(root, fileGates(readFileSync(path, 'utf8')), discoverGates(root).candidates);
294
+ }
295
+ /** Where a refresh leaves its rows for the agent who applies the user's picks (024 S-12). */
296
+ export const REFRESH_LIST = '.loctx/gates-refresh.md';
297
+ /** Write the rows to `.loctx/gates-refresh.md`, replacing the last list (024 S-12). */
298
+ export function writeRefreshList(root, rows) {
299
+ const text = readFileSync(join(root, GATES), 'utf8');
300
+ const body = [
301
+ '# gates refresh',
302
+ '',
303
+ `- made: ${new Date().toISOString()}`,
304
+ `- gates.yaml: sha256 ${createHash('sha256').update(text).digest('hex').slice(0, 16)}`,
305
+ '- The user picks from this list; an agent applies the picks to `.agents/harness/gates.yaml` in a commit of its own. The agent does not run reins.',
306
+ '',
307
+ ...rows.map((r) => `- ${formatGateRow(r)}`),
308
+ '',
309
+ ].join('\n');
310
+ mkdirSync(join(root, '.loctx'), { recursive: true });
311
+ writeFileSync(join(root, REFRESH_LIST), body);
312
+ }
313
+ /** The action a name passed to `--apply` asks for, or null when no row has it (024 S-13). */
314
+ function actionFor(rows, asked) {
315
+ const [verb, name] = asked.includes(':')
316
+ ? asked.split(/:(.*)/s)
317
+ : ['', asked];
318
+ const row = rows.find((r) => r.name === name);
319
+ if (!row)
320
+ return null;
321
+ const can = actionsOf(row);
322
+ if (verb === '')
323
+ return { action: can[0], row };
324
+ return can.includes(verb) ? { action: verb, row } : null;
297
325
  }
298
326
  /**
299
- * `reins config gates` (design §9). `--add <name>…` appends subdirectory proposals. `--refresh` runs the
300
- * discovery again and reports the differences; `--apply <name…|all>` applies the chosen ones: a new gate is
301
- * appended, a changed one gets its command and source, a gone one is removed. Comments and other keys stay,
302
- * a gate written by hand is never touched, and the gate script is rewritten when the file changes.
327
+ * `reins config gates` (design §9). `--add <name>…` appends offered candidates. `--refresh` runs the discovery
328
+ * again, writes every gate and candidate with its state to `.loctx/gates-refresh.md` (024 S-11, S-12) and, with
329
+ * `--apply <name…|all|remove:name>`, adds, removes or replaces only what is named (S-13). Comments and other keys
330
+ * stay; the gate script reads gates.yaml when it runs, so only gates.yaml changes (S-17).
303
331
  */
304
332
  export function configureGates(o = {}) {
305
333
  const root = repoRoot(o.cwd ?? process.cwd());
@@ -310,53 +338,61 @@ export function configureGates(o = {}) {
310
338
  const have = new Set(Object.keys(doc.toJS()?.gates ?? {}));
311
339
  const available = subdirProposals(root).filter((g) => !have.has(g.name));
312
340
  if (o.refresh || o.apply) {
313
- const diff = gateDiff(root) ?? [];
314
- const can = applicable(diff);
341
+ const rows = gateRows(root) ?? [];
342
+ writeRefreshList(root, rows);
315
343
  // every name is checked, `all` beside others too: one unknown name refuses the whole call
316
344
  const asked = [...new Set(o.apply ?? [])];
317
- const unknown = asked.filter((n) => n !== 'all' && !can.some((d) => d.name === n));
318
- const names = asked.includes('all') ? can.map((d) => d.name) : asked;
345
+ const unknown = asked.filter((n) => n !== 'all' && !actionFor(rows, n));
319
346
  if (unknown.length)
320
347
  return {
321
- refused: `nothing to apply under: ${unknown.join(', ')} — names: ${can.map((d) => d.name).join(', ') || 'none'}`,
348
+ refused: `nothing to apply under: ${unknown.join(', ')} — names: ${rows.map((r) => r.name).join(', ') || 'none'}`,
322
349
  code: 1,
323
350
  available,
324
351
  added: [],
325
- diff,
352
+ rows,
326
353
  applied: [],
327
354
  };
328
- for (const n of names) {
329
- const d = can.find((x) => x.name === n);
330
- if (d.kind === 'gone') {
331
- doc.deleteIn(['gates', d.name]);
355
+ const picks = asked.includes('all')
356
+ ? rows
357
+ .filter((r) => r.state === 'not applied')
358
+ .map((row) => ({ action: 'add', row }))
359
+ : [];
360
+ for (const n of asked.filter((x) => x !== 'all')) {
361
+ const p = actionFor(rows, n);
362
+ if (!picks.some((x) => x.row === p.row))
363
+ picks.push(p);
364
+ }
365
+ const applied = [];
366
+ for (const { action, row } of picks) {
367
+ if (action === 'remove') {
368
+ doc.deleteIn(['gates', row.name]);
332
369
  // every occurrence: a name left in `order` without its gate would dangle
333
370
  const order = doc.get('order');
334
371
  if (isSeq(order))
335
372
  for (let i = order.items.length - 1; i >= 0; i--) {
336
373
  const x = order.items[i];
337
- if ((isScalar(x) ? x.value : x) === d.name)
374
+ if ((isScalar(x) ? x.value : x) === row.name)
338
375
  order.delete(i);
339
376
  }
340
377
  }
341
- else if (d.kind === 'changed') {
342
- doc.setIn(['gates', d.name, 'cmd'], d.cmd);
343
- doc.setIn(['gates', d.name, 'from'], d.from);
378
+ else if (action === 'replace') {
379
+ doc.setIn(['gates', row.name, 'cmd'], row.found.cmd);
380
+ doc.setIn(['gates', row.name, 'from'], row.found.from);
344
381
  }
345
382
  else {
346
- doc.setIn(['gates', d.name], doc.createNode({ cmd: d.cmd, from: d.from, ...(d.optional ? { optional: true } : {}) }));
347
- appendOrder(doc, d.name);
383
+ doc.setIn(['gates', row.name], doc.createNode({
384
+ cmd: row.cmd,
385
+ from: row.from,
386
+ ...(row.optional ? { optional: true } : {}),
387
+ }));
388
+ appendOrder(doc, row.name);
348
389
  }
390
+ applied.push(`${action} ${row.name}`);
349
391
  }
350
- if (names.length) {
351
- writeFileSync(path, doc.toString());
352
- writeGenerated(root, generateVendorFiles(root), false);
353
- }
354
- return {
355
- available: available.filter((g) => !names.includes(g.name)),
356
- added: [],
357
- diff,
358
- applied: names,
359
- };
392
+ // the gate script reads gates.yaml when it runs, so only the file changes (024 S-17)
393
+ if (applied.length)
394
+ writeFileSync(path, doc.toString({ lineWidth: 0 }));
395
+ return { available, added: [], rows, applied };
360
396
  }
361
397
  const names = o.add ?? [];
362
398
  const unknown = names.filter((n) => !available.some((g) => g.name === n));
@@ -374,10 +410,7 @@ export function configureGates(o = {}) {
374
410
  appendOrder(doc, g.name);
375
411
  added.push(g.name);
376
412
  }
377
- if (added.length) {
378
- writeFileSync(path, doc.toString());
379
- // the gate script holds the commands of gates.yaml (design §6): it follows the file
380
- writeGenerated(root, generateVendorFiles(root), false);
381
- }
413
+ if (added.length)
414
+ writeFileSync(path, doc.toString({ lineWidth: 0 }));
382
415
  return { available: available.filter((g) => !added.includes(g.name)), added };
383
416
  }
@@ -9,12 +9,13 @@ import { apply, listFiles } from '../lib/fsx.js';
9
9
  import { repoRoot } from '../lib/git.js';
10
10
  import { harnessVersion, packageHarness, packageSkills, packageVersion } from '../lib/upstream.js';
11
11
  import { generateVendorFiles } from '../lib/generate.js';
12
- import { hookLine, requiredGates } from '../lib/gate-script.js';
12
+ import { GATE_SCRIPT, hookLine, requiredGates } from '../lib/gate-script.js';
13
13
  import { defaultBindings, readTeam } from '../lib/bindings.js';
14
14
  import { overlayReader, workTreeReader } from '../lib/reader.js';
15
15
  import { LOCAL_DELEGATION, ONBOARDING_PENDING, RECONCILE_PENDING, onboardingNote, placeNote, renderBlocks, tidyNote, } from '../lib/agents-md.js';
16
16
  import { syncLocalDelegation } from '../lib/local-delegation.js';
17
- import { writeGenerated } from '../lib/vendor-write.js';
17
+ import { readManifest, writeGenerated } from '../lib/vendor-write.js';
18
+ import { applyLocalForcePush, FORCE_WITH_LEASE_QUESTION, recordedForceWithLease, } from '../lib/local-settings.js';
18
19
  /** Upstream harness files installed into `.agents/harness/` (design §1): everything but seeds and the changelog. */
19
20
  export function harnessFiles(all) {
20
21
  return all.filter((f) => !f.startsWith('knowledge-seeds/') && f !== 'CHANGELOG.md');
@@ -59,7 +60,7 @@ export function buildGates(root, gates) {
59
60
  evidence: 'raw',
60
61
  };
61
62
  void root;
62
- return `# discovered by reins install — the loop reads only this file (design §5)\n${stringify(doc)}`;
63
+ return `# discovered by reins install — the loop reads only this file (design §5)\n${stringify(doc, { lineWidth: 0 })}`;
63
64
  }
64
65
  /** The stub install leaves; migrate may replace it with the project's real raw roadmap. */
65
66
  export const ROADMAP_STUB = '# ROADMAP (local)\n\n— 산발적 아이디어를 여기에. 확정되면 docs/ROADMAP.md\n';
@@ -80,6 +81,84 @@ const TOOL_NAMES = ['claude', 'openai', 'google', 'gemini', 'copilot', 'cursor']
80
81
  const HOOK_STAGES = ['pre-commit', 'pre-push'];
81
82
  /** A `reins:begin hooks` block in a hook file, with its body. */
82
83
  const HOOK_BLOCK = /# reins:begin hooks\n([\s\S]*?)# reins:end hooks/g;
84
+ /**
85
+ * Whether a hook file already runs the gate script for `stage` outside a reins block (024 S-19): a line
86
+ * that is not a comment and, trimmed, reads `sh <path> <stage>`, the path as written, with `./`, or quoted.
87
+ */
88
+ export function runsGateScript(text, stage) {
89
+ const paths = [GATE_SCRIPT, `./${GATE_SCRIPT}`].flatMap((p) => [p, `'${p}'`, `"${p}"`]);
90
+ return text
91
+ .split(/\r?\n/)
92
+ .map((l) => l.trim().replace(/\s+/g, ' '))
93
+ .some((l) => !l.startsWith('#') && paths.some((p) => l === `sh ${p} ${stage}`));
94
+ }
95
+ /** The parsed lefthook or pre-commit configuration files of the root; unreadable ones are left out. */
96
+ function hookConfigs(root, tool) {
97
+ const files = tool === 'lefthook'
98
+ ? ['lefthook.yml', 'lefthook.yaml', '.lefthook.yml', '.lefthook.yaml', 'lefthook-local.yml']
99
+ : ['.pre-commit-config.yaml'];
100
+ const out = [];
101
+ for (const f of files.filter((x) => existsSync(join(root, x))))
102
+ try {
103
+ out.push(parse(readFileSync(join(root, f), 'utf8')));
104
+ }
105
+ catch {
106
+ // unreadable: nothing in it counts, so the line is proposed
107
+ }
108
+ return out;
109
+ }
110
+ const obj = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : null;
111
+ /** Whether a command value is the gate script for `stage`: `sh <path> <stage>`, the path quoted or with `./`. */
112
+ export function isGateCommand(cmd, stage) {
113
+ if (typeof cmd !== 'string')
114
+ return false;
115
+ // only horizontal space is evened out: a newline is a command boundary for the shell (review 10)
116
+ const c = cmd.trim().replace(/[ \t]+/g, ' ');
117
+ return new RegExp(`^sh (['"]?)(\\./)?\\.agents/harness/run-gates\\.sh\\1 ${stage}$`).test(c);
118
+ }
119
+ /** The `run:` values lefthook runs at `stage`: its `commands`, `jobs` (and job `group`s) and `scripts`' runners. */
120
+ function lefthookRuns(doc, stage) {
121
+ const hook = obj(obj(doc)?.[stage]);
122
+ if (!hook)
123
+ return [];
124
+ const runs = [];
125
+ for (const c of Object.values(obj(hook['commands']) ?? {}))
126
+ runs.push(obj(c)?.['run']);
127
+ const jobs = (list) => {
128
+ if (!Array.isArray(list))
129
+ return;
130
+ for (const j of list) {
131
+ runs.push(obj(j)?.['run']);
132
+ jobs(obj(obj(j)?.['group'])?.['jobs']);
133
+ }
134
+ };
135
+ jobs(hook['jobs']);
136
+ return runs;
137
+ }
138
+ const PRE_COMMIT_STAGE = { commit: 'pre-commit', push: 'pre-push' };
139
+ /** The `entry` values pre-commit runs at `stage`: each hook's `stages`, else `default_stages`, else every stage. */
140
+ function preCommitEntries(doc, stage) {
141
+ const d = obj(doc);
142
+ const defaults = Array.isArray(d?.['default_stages']) ? d['default_stages'] : null;
143
+ const out = [];
144
+ for (const repo of Array.isArray(d?.['repos']) ? d['repos'] : [])
145
+ for (const h of Array.isArray(obj(repo)?.['hooks']) ? obj(repo)['hooks'] : []) {
146
+ const hook = obj(h);
147
+ const stages = Array.isArray(hook?.['stages']) ? hook['stages'] : defaults;
148
+ const runs = stages === null || stages.some((x) => (PRE_COMMIT_STAGE[String(x)] ?? String(x)) === stage);
149
+ if (runs)
150
+ out.push(hook?.['entry']);
151
+ }
152
+ return out;
153
+ }
154
+ /**
155
+ * Whether the lefthook or pre-commit configuration already runs the gate script for `stage` (A-20): a
156
+ * parsed `run:` (lefthook, under that hook) or `entry:` (pre-commit, for a hook that runs at that stage)
157
+ * whose value is the gate command. Comments, names and other fields never count.
158
+ */
159
+ export function configRunsGateScript(docs, tool, stage) {
160
+ return docs.some((d) => (tool === 'lefthook' ? lefthookRuns(d, stage) : preCommitEntries(d, stage)).some((c) => isGateCommand(c, stage)));
161
+ }
83
162
  /** A command that runs reins: what 0.x put into hooks and settings. */
84
163
  export const RUNS_REINS = /@bluenyang\/reins|reins\.js\b|(^|[\s;&|])reins\s+(check|hook|gate|status)\b/;
85
164
  /** `reins install` (design §9): place the harness, ask, propose hooks, mark onboarding. Never writes history. */
@@ -182,6 +261,7 @@ export async function runInstall(o) {
182
261
  }
183
262
  if (!hasGates) {
184
263
  const proposal = discoverGates(root);
264
+ const reasonsOf = (name) => proposal.candidates.find((c) => c.name === name)?.reasons ?? [];
185
265
  const gateList = proposal.gates.map((g) => `${g.name}=${g.cmd}`).join(', ') || 'none found';
186
266
  const gateQ = `gates found: ${gateList} — use them?`;
187
267
  const gateAns = await (screens ?? line).confirm({ message: gateQ, initial: true });
@@ -196,8 +276,12 @@ export async function runInstall(o) {
196
276
  let names;
197
277
  if (screens) {
198
278
  const picked = await screens.multiselect({
199
- message: 'Subdirectory gates to add',
200
- options: proposal.proposals.map((g) => ({ value: g.name, label: g.name, hint: g.cmd })),
279
+ message: 'Other gate candidates to add (not chosen by default)',
280
+ options: proposal.proposals.map((g) => ({
281
+ value: g.name,
282
+ label: g.name,
283
+ hint: [g.cmd, ...reasonsOf(g.name)].join(' — '),
284
+ })),
201
285
  initial: [],
202
286
  });
203
287
  if (isNav(picked))
@@ -226,6 +310,9 @@ export async function runInstall(o) {
226
310
  }
227
311
  for (const x of proposal.excluded)
228
312
  notes.push(`excluded from gates: ${x.name} (${x.why})`);
313
+ // what another script or gate already runs is shown, never chosen (024 S-9, S-10)
314
+ for (const c of proposal.candidates.filter((x) => x.status === 'covered'))
315
+ notes.push(`not a gate of its own: ${c.name} — ${c.reasons.join('; ')}`);
229
316
  add('.agents/harness/gates.yaml', buildGates(root, [...(gateAns ? proposal.gates : []), ...chosen]), 'declared gates');
230
317
  }
231
318
  // 3. settings: a new bindings file in single mode (an old one is converted by update)
@@ -278,7 +365,8 @@ export async function runInstall(o) {
278
365
  const p = join(root, '.husky', stage);
279
366
  return { stage, cur: existsSync(p) ? readFileSync(p, 'utf8') : '' };
280
367
  });
281
- const missing = files.filter((f) => !f.cur.includes('# reins:begin hooks'));
368
+ // a stage is hooked by a reins block or by the gate line written outside one (024 S-19)
369
+ const missing = files.filter((f) => !f.cur.includes('# reins:begin hooks') && !runsGateScript(f.cur, f.stage));
282
370
  let addHooks = !!o.hooks;
283
371
  if (missing.length && !addHooks && o.confirmHooks && !o.dryRun) {
284
372
  const yes = await o.confirmHooks.confirm({
@@ -306,16 +394,21 @@ export async function runInstall(o) {
306
394
  add(`.husky/${stage}`, next, 'hook: the gate script');
307
395
  notes.push(`.husky/${stage}: the reins hooks block now calls the gate script — it held: ${held.join(' && ')} (move a line of your own outside the block)`);
308
396
  }
309
- else if (addHooks)
397
+ else if (addHooks && !runsGateScript(cur, stage))
310
398
  add(`.husky/${stage}`, `${cur.replace(/\s*$/, '')}\n# reins:begin hooks\n${line}\n# reins:end hooks\n`.replace(/^\n/, ''), 'hook: the gate script');
311
399
  }
312
400
  if (missing.length && !addHooks)
313
401
  notes.push(`hook proposal (husky): add \`${hookLine('pre-commit')}\` to .husky/pre-commit and \`${hookLine('pre-push')}\` to .husky/pre-push; re-run with --hooks to add them`);
314
402
  }
315
- else if (gated && tool === 'lefthook')
316
- notes.push(`hook proposal (lefthook): under \`pre-commit: commands:\` add \`gates: { run: ${hookLine('pre-commit')} }\`, and the same under \`pre-push:\` with \`${hookLine('pre-push')}\` (reins proposes lefthook lines only; add them to its config yourself)`);
317
- else if (gated && tool === 'pre-commit')
318
- notes.push(`hook proposal (pre-commit): under \`repos:\` add \`- repo: local\` with a hook \`{ id: gates, name: project gates, entry: ${hookLine('pre-commit')}, language: system, pass_filenames: false }\`, and one with \`stages: [pre-push]\` and \`${hookLine('pre-push')}\` (reins proposes pre-commit lines only; add them to its config yourself)`);
403
+ else if (gated && (tool === 'lefthook' || tool === 'pre-commit')) {
404
+ // a config that already runs the gate script for a stage is not proposed it again (0.3.4-rc.2, A-20)
405
+ const docs = hookConfigs(root, tool);
406
+ const missing = HOOK_STAGES.filter((s) => !configRunsGateScript(docs, tool, s));
407
+ if (missing.length && tool === 'lefthook')
408
+ notes.push(`hook proposal (lefthook): ${missing.map((s) => `under \`${s}: commands:\` add \`gates: { run: ${hookLine(s)} }\``).join(', and ')} (reins proposes lefthook lines only; add them to its config yourself)`);
409
+ else if (missing.length)
410
+ notes.push(`hook proposal (pre-commit): under \`repos:\` add \`- repo: local\` with ${missing.map((s) => `a hook \`{ id: gates${s === 'pre-push' ? '-push' : ''}, name: project gates, entry: ${hookLine(s)}, language: system, pass_filenames: false, stages: [${s}] }\``).join(' and ')} (reins proposes pre-commit lines only; add them to its config yourself)`);
411
+ }
319
412
  else if (gated)
320
413
  notes.push(`no hook tool found — the PM asks which one to use during onboarding; whichever it is runs \`${hookLine('pre-commit')}\` and \`${hookLine('pre-push')}\``);
321
414
  // 6. AGENTS.md: managed blocks, the onboarding note; CLAUDE.md pointer
@@ -376,6 +469,8 @@ export async function runInstall(o) {
376
469
  const rd = o.dryRun
377
470
  ? overlayReader(workTreeReader(root), [...(o.pending ?? []), ...writes], [...retired, ...(o.pendingDeletes ?? [])])
378
471
  : workTreeReader(root);
472
+ // the 0.3.3 team rule this run takes out of .claude/settings.json (024 revision 1)
473
+ const hadTeamLease = (readManifest(root).owned?.['.claude/settings.json'] ?? []).includes('Bash(git push --force-with-lease *)');
379
474
  const generated = writeGenerated(root, generateVendorFiles(root, rd), !!o.dryRun, !!o.force);
380
475
  if (generated) {
381
476
  // a generated file that was there before this run is a changed one, not a new one (022 S-28)
@@ -396,5 +491,20 @@ export async function runInstall(o) {
396
491
  applied.removed.push(LOCAL_DELEGATION);
397
492
  else if (local)
398
493
  (hadLocal ? applied.changed : applied.created).push(LOCAL_DELEGATION);
494
+ // 10. force push with lease, per person (024 S-26a): asked once, kept in .loctx, written to settings.local.json
495
+ const recorded = recordedForceWithLease(root);
496
+ let lease = o.forceWithLease ?? recorded;
497
+ let answered = !!o.forceWithLease || !!recorded;
498
+ // only on a terminal (screens, or the hook confirmation); piped answers keep the unrecorded default (review 6)
499
+ const asks = o.confirmHooks ?? screens;
500
+ if (!lease && asks && !o.dryRun) {
501
+ const yes = await asks.confirm({ message: FORCE_WITH_LEASE_QUESTION, initial: true });
502
+ if (yes === EXIT)
503
+ return cancelled();
504
+ lease = yes === false ? 'allow' : 'deny';
505
+ answered = true;
506
+ }
507
+ const fp = applyLocalForcePush(root, lease ?? 'deny', !!o.dryRun, answered);
508
+ notes.push(hadTeamLease ? `${fp.note} — the team .claude/settings.json no longer denies it` : fp.note);
399
509
  return { root, generation: gen, applied, generated, notes };
400
510
  }