@ericrisco/rsc 4.1.3 → 4.1.5

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.
@@ -13,56 +13,275 @@
13
13
  // A branch whose tier-2 paths are all harness configuration (an rsc install or upgrade, CLAUDE.md) is
14
14
  // not feature work and needs no spec — it still needs a human, as every tier 2 does.
15
15
  // Fail-open on any environment problem; opt out per project with `.rsc/.no-asdd-gate`.
16
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
17
- import { join } from 'node:path';
16
+ import { existsSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
17
+ import { join, resolve, relative } from 'node:path';
18
18
  import { spawnSync } from 'node:child_process';
19
- import { expand } from './shell-unwrap.mjs';
19
+ import {
20
+ expand,
21
+ segments,
22
+ words,
23
+ unwrap,
24
+ withoutHeredocs,
25
+ } from './shell-unwrap.mjs';
26
+ import {
27
+ readPolicy,
28
+ mergePolicyConfig,
29
+ changeDetails,
30
+ matchPolicyRules,
31
+ policyPattern,
32
+ } from './risk-policy.mjs';
20
33
 
21
34
  // Options that take a value must swallow it, or `gh -R owner/repo pr create` reads `owner/repo` as
22
35
  // the subcommand and slips past.
23
36
  const OPTS = String.raw`(?:(?:-[CcR]\s+\S+|--(?:repo|git-dir|work-tree)\s+\S+|--?\S+)\s+)*`;
24
- const PUSH_OR_PR = new RegExp(String.raw`\bgit\s+${OPTS}push(?![\w-])|\bgh\s+${OPTS}pr\s+${OPTS}(?:create|merge)(?![\w-])`);
37
+ const PUSH_OR_PR = new RegExp(
38
+ String.raw`\bgit\s+${OPTS}push(?![\w-])|\bgh\s+${OPTS}pr\s+${OPTS}(?:create|merge)(?![\w-])`,
39
+ );
25
40
  export const SPECS_DIR = join('02-DOCS', 'wiki', 'sdd', 'specs');
26
41
 
27
42
  // Quoted text is blanked so a mention is not a push; and the segments a shell really runs
28
43
  // (`bash -c "git push"`, `eval …`) are judged too — the same unwrapping the sello uses.
29
44
  export function isPushOrPr(command) {
30
45
  if (typeof command !== 'string' || !command) return false;
31
- const runs = (c) => PUSH_OR_PR.test(c.replace(/'[^']*'/g, "''").replace(/"[^"]*"/g, '""'));
46
+ const runs = (c) =>
47
+ PUSH_OR_PR.test(c.replace(/'[^']*'/g, "''").replace(/"[^"]*"/g, '""'));
32
48
  return runs(command) || expand(command).some(runs);
33
49
  }
34
50
 
35
51
  function git(root, ...args) {
36
- const r = spawnSync('git', ['-C', root, '-c', 'core.quotePath=false', ...args], { windowsHide: true, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
37
- return r.status === 0 ? (r.stdout || '') : null;
52
+ const r = spawnSync(
53
+ 'git',
54
+ ['-C', root, '-c', 'core.quotePath=false', ...args],
55
+ { windowsHide: true, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
56
+ );
57
+ return r.status === 0 ? r.stdout || '' : null;
38
58
  }
39
59
 
40
- const branchOf = (text) => (/^---\r?\n[\s\S]*?^branch:[ \t]*["']?([^"'\r\n]+?)["']?[ \t]*$[\s\S]*?^---/m.exec(text) || [])[1] || null;
41
-
42
- /** The specs linked to `branch`: `{ path, ok, missing, empty }` each. */
43
- export function linkedSpecs(root, branch, specCompleteness) {
44
- let files = [];
45
- try { files = readdirSync(join(root, SPECS_DIR)).filter((f) => f.endsWith('.md') && !f.endsWith('.plan.md')); } catch { return []; }
60
+ const normalize = (text) => text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
61
+ function values(text, key) {
62
+ const fm = /^---\n([\s\S]*?)\n---/.exec(normalize(text))?.[1] || '';
63
+ const match = new RegExp(`^${key}:[ \t]*(.*)$`, 'm').exec(fm);
64
+ if (!match) return [];
65
+ const clean = (v) => v.trim().replace(/^["']|["']$/g, '');
66
+ if (match[1].trim().startsWith('['))
67
+ return match[1].trim().slice(1, -1).split(',').map(clean).filter(Boolean);
68
+ if (match[1].trim()) return [clean(match[1])];
69
+ const tail = fm.slice(match.index + match[0].length).replace(/^\n/, '');
70
+ return (tail.match(/^(?:[ \t]*-[ \t]+[^\n]+\n?)+/)?.[0] || '')
71
+ .split('\n')
72
+ .map((l) => clean(l.replace(/^[ \t]*-[ \t]+/, '')))
73
+ .filter(Boolean);
74
+ }
75
+ function documents(root, directory) {
76
+ try {
77
+ return readdirSync(join(root, directory))
78
+ .filter((f) => f.endsWith('.md'))
79
+ .map((f) => ({
80
+ path: join(directory, f),
81
+ text: readFileSync(join(root, directory, f), 'utf8'),
82
+ }));
83
+ } catch {
84
+ return [];
85
+ }
86
+ }
87
+ /** Exact branch, branch list or a branch's FTD `spec:` reference. */
88
+ export function linkedSpecs(root, branch, specCompleteness, cfg = {}) {
46
89
  const norm = (x) => x.toLowerCase().replace(/_/g, '-');
47
- const last = norm(branch.split('/').pop());
48
- return files.flatMap((f) => {
49
- const text = readFileSync(join(root, SPECS_DIR, f), 'utf8');
50
- if (branchOf(text) !== branch && norm(f.slice(0, -3)) !== last) return [];
51
- const r = specCompleteness(text);
52
- return [{ path: join(SPECS_DIR, f).split('\\').join('/'), ok: r.ok, missing: r.missing, empty: r.empty }];
53
- });
90
+ const suffix = cfg.asddGate?.cherryPickSuffix;
91
+ const branches = [
92
+ branch,
93
+ ...(typeof suffix === 'string' && suffix && branch.endsWith(suffix)
94
+ ? [branch.slice(0, -suffix.length)]
95
+ : []),
96
+ ];
97
+ const ftds = documents(root, join('02-DOCS', 'wiki', 'ftd'));
98
+ return documents(root, SPECS_DIR)
99
+ .filter((f) => !f.path.endsWith('.plan.md'))
100
+ .flatMap((f) => {
101
+ const slug = f.path.split(/[\\/]/).pop().slice(0, -3);
102
+ const linked = branches.some(
103
+ (b) =>
104
+ [...values(f.text, 'branch'), ...values(f.text, 'branches')].includes(
105
+ b,
106
+ ) ||
107
+ norm(slug) === norm(b.split('/').pop()) ||
108
+ ftds.some(
109
+ (d) =>
110
+ [
111
+ ...values(d.text, 'branch'),
112
+ ...values(d.text, 'branches'),
113
+ ].includes(b) && values(d.text, 'spec').includes(slug),
114
+ ),
115
+ );
116
+ if (!linked) return [];
117
+ const r = specCompleteness(normalize(f.text));
118
+ return [
119
+ {
120
+ path: f.path.split('\\').join('/'),
121
+ ok: r.ok,
122
+ missing: r.missing,
123
+ empty: r.empty,
124
+ },
125
+ ];
126
+ });
127
+ }
128
+
129
+ // --show-toplevel alone is insufficient with --git-dir: Git may report the invocation cwd
130
+ // while HEAD and the pushed refs belong to another repository. Check the Git directory identity.
131
+ function resolvePushRepository(dir, options) {
132
+ const canonical = (path) => {
133
+ try {
134
+ return realpathSync(path);
135
+ } catch {
136
+ return resolve(path);
137
+ }
138
+ };
139
+ const gitDir = (
140
+ git(dir, ...options, 'rev-parse', '--absolute-git-dir') || ''
141
+ ).trim();
142
+ if (!gitDir) return { repo: null }; // invalid command/environment: no resolvable push
143
+ const identity = canonical(gitDir);
144
+ const matches = (path) => {
145
+ const candidate = (
146
+ git(path, 'rev-parse', '--absolute-git-dir') || ''
147
+ ).trim();
148
+ return (
149
+ candidate &&
150
+ canonical(candidate) === identity &&
151
+ (git(path, 'rev-parse', '--is-bare-repository') || '').trim() === 'false'
152
+ );
153
+ };
154
+ const top = (
155
+ git(dir, ...options, 'rev-parse', '--show-toplevel') || ''
156
+ ).trim();
157
+ if (top && matches(top)) return { repo: top };
158
+ const listed = (
159
+ git(dir, ...options, 'worktree', 'list', '--porcelain', '-z') || ''
160
+ ).split('\0');
161
+ for (const field of listed) {
162
+ if (!field.startsWith('worktree ')) continue;
163
+ const path = field.slice('worktree '.length);
164
+ if (matches(path)) return { repo: path };
165
+ }
166
+ return {
167
+ repo: null,
168
+ error: `Cannot inspect the worktree for Git directory "${gitDir}". Recover: check out this repository and run \`rsc spec gate --branch-check --repo <checkout>\` before pushing from that checkout.`,
169
+ };
170
+ }
171
+
172
+ // Resolve only commands we understand. Shell aliases/functions and arbitrary scripts cannot be
173
+ // inferred; callers can use the explicit branch-check CLI for those integrations.
174
+ export function reposWithPush(command, cwd, { onUnresolved = () => {} } = {}) {
175
+ const found = new Set();
176
+ function scan(text, start, depth = 0) {
177
+ if (depth > 8) return;
178
+ let dir = start;
179
+ const stack = [];
180
+ for (const segment of segments(withoutHeredocs(text))) {
181
+ const unwrapped = unwrap(
182
+ segment.trim().replace(/^(?:then|do|\{)\s+/, ''),
183
+ );
184
+ if (!unwrapped) continue;
185
+ if (unwrapped.inner) {
186
+ scan(unwrapped.inner, dir, depth + 1);
187
+ continue;
188
+ }
189
+ const tokens = words(unwrapped.rest).map((w) => w.text);
190
+ const name = (tokens[0] || '').replace(/^.*[\\/]/, '').toLowerCase();
191
+ if (/^(cd|pushd|set-location|sl)$/.test(name)) {
192
+ const path = tokens.filter(
193
+ (t) => !/^-(?:literalpath|path)$/i.test(t),
194
+ )[1];
195
+ if (path && !/[${}`]/.test(path)) {
196
+ if (name === 'pushd') stack.push(dir);
197
+ dir = resolve(dir, path);
198
+ }
199
+ continue;
200
+ }
201
+ if (name === 'popd') {
202
+ dir = stack.pop() || dir;
203
+ continue;
204
+ }
205
+ if (/^(cmd|cmd.exe)$/.test(name) && /^\/c$/i.test(tokens[1] || '')) {
206
+ scan(tokens.slice(2).join(' '), dir, depth + 1);
207
+ continue;
208
+ }
209
+ if (!/^(git|git.exe|gh|gh.exe)$/.test(name)) continue;
210
+ const isGit = name.startsWith('git');
211
+ const valued = isGit
212
+ ? new Set([
213
+ '-C',
214
+ '-c',
215
+ '--git-dir',
216
+ '--work-tree',
217
+ '--namespace',
218
+ '--config-env',
219
+ '--super-prefix',
220
+ ])
221
+ : new Set(['-R', '--repo', '--hostname']);
222
+ const skipOptions = (start) => {
223
+ let index = start;
224
+ while (tokens[index]?.startsWith('-')) {
225
+ const option = tokens[index++];
226
+ if (valued.has(option)) index++;
227
+ }
228
+ return index;
229
+ };
230
+ const commandIndex = skipOptions(1);
231
+ if (isGit && tokens[commandIndex] === 'push') {
232
+ // Let Git resolve all supported global selectors, in their actual order. Reconstructing
233
+ // only -C would silently ignore --git-dir/--work-tree and inspect the parent repository.
234
+ const options = tokens.slice(1, commandIndex);
235
+ const { repo, error } = resolvePushRepository(dir, options);
236
+ if (repo) found.add(repo);
237
+ else if (error) onUnresolved(error);
238
+ } else if (!isGit && tokens[commandIndex] === 'pr') {
239
+ const action = tokens[skipOptions(commandIndex + 1)];
240
+ if (['create', 'merge'].includes(action)) {
241
+ const repo = (git(dir, 'rev-parse', '--show-toplevel') || '').trim();
242
+ if (repo) found.add(repo);
243
+ }
244
+ }
245
+ }
246
+ }
247
+ scan(command, cwd);
248
+ return [...found];
54
249
  }
55
250
 
56
251
  // A panel still covers HEAD when its commit is an ancestor of HEAD and this branch's own commits since
57
252
  // changed no code. Not code, by the same rules the gate applies above: documentation, the harness's
58
253
  // own state (.rsc/ journals, nested worktrees) and harness configuration. Commits that came from the
59
254
  // trunk (a merge of main into the branch) are not this branch's work and are not counted.
60
- function reviewedStill(root, sha, trunk, sello, cfg) {
255
+ function reviewedStill(root, sha, trunk, sello, cfg, tip = 'HEAD') {
61
256
  if (!sha) return false;
62
- if (spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', sha, 'HEAD'], { windowsHide: true }).status !== 0) return false;
63
- const since = [...new Set((git(root, 'log', '--no-merges', '--no-renames', '--format=', '--name-only', `${sha}..HEAD`, `^${trunk}`) || '')
64
- .split('\n').map((l) => l.trim()).filter(Boolean))]
65
- .filter((n) => !sello.SELLO_STATE_PATHS.includes(n) && !sello.NESTED_WORKTREES.test(n));
257
+ if (
258
+ spawnSync('git', ['-C', root, 'merge-base', '--is-ancestor', sha, tip], {
259
+ windowsHide: true,
260
+ }).status !== 0
261
+ )
262
+ return false;
263
+ const since = [
264
+ ...new Set(
265
+ (
266
+ git(
267
+ root,
268
+ 'log',
269
+ '--no-merges',
270
+ '--no-renames',
271
+ '--format=',
272
+ '--name-only',
273
+ `${sha}..${tip}`,
274
+ `^${trunk}`,
275
+ ) || ''
276
+ )
277
+ .split('\n')
278
+ .map((l) => l.trim())
279
+ .filter(Boolean),
280
+ ),
281
+ ].filter(
282
+ (n) =>
283
+ !sello.SELLO_STATE_PATHS.includes(n) && !sello.NESTED_WORKTREES.test(n),
284
+ );
66
285
  const { classes } = sello.classifyRisk(since, cfg);
67
286
  return Object.values(classes).every((c) => c === 'docs' || c === 'harness');
68
287
  }
@@ -71,15 +290,39 @@ function reviewedStill(root, sha, trunk, sello, cfg) {
71
290
  // still covers HEAD.
72
291
  function panelSize(root, slugs, stillValid = () => true) {
73
292
  let text = '';
74
- try { text = readFileSync(join(root, '.rsc', 'review-ledger.jsonl'), 'utf8'); } catch { return 0; }
293
+ try {
294
+ text = readFileSync(join(root, '.rsc', 'review-ledger.jsonl'), 'utf8');
295
+ } catch {
296
+ return 0;
297
+ }
75
298
  let best = 0;
76
299
  for (const line of text.split('\n')) {
77
300
  let e;
78
- try { e = JSON.parse(line); } catch { continue; }
79
- if (e?.type !== 'panel' || typeof e.task !== 'string' || !Array.isArray(e.lenses)) continue;
80
- if (!slugs.some((s) => e.task.toLowerCase().replace(/_/g, '-').startsWith(`${s.toLowerCase().replace(/_/g, '-')}/`))) continue;
301
+ try {
302
+ e = JSON.parse(line);
303
+ } catch {
304
+ continue;
305
+ }
306
+ if (
307
+ e?.type !== 'panel' ||
308
+ typeof e.task !== 'string' ||
309
+ !Array.isArray(e.lenses)
310
+ )
311
+ continue;
312
+ if (
313
+ !slugs.some((s) =>
314
+ e.task
315
+ .toLowerCase()
316
+ .replace(/_/g, '-')
317
+ .startsWith(`${s.toLowerCase().replace(/_/g, '-')}/`),
318
+ )
319
+ )
320
+ continue;
81
321
  if (!stillValid(e.sha)) continue;
82
- best = Math.max(best, new Set(e.lenses.map((l) => String(l).toLowerCase())).size);
322
+ best = Math.max(
323
+ best,
324
+ new Set(e.lenses.map((l) => String(l).toLowerCase())).size,
325
+ );
83
326
  }
84
327
  return best;
85
328
  }
@@ -88,47 +331,153 @@ function panelSize(root, slugs, stillValid = () => true) {
88
331
  * null when the command may go ahead; the denial text (with its way out, P6) when it may not.
89
332
  * `lib` carries the sibling modules so tests and the hook load them the same way.
90
333
  */
91
- export function asddGate(root, command, { sello, specCompleteness }) {
92
- if (!isPushOrPr(command)) return null;
334
+ export function branchCheck(
335
+ root,
336
+ repo,
337
+ { sello, specCompleteness },
338
+ options = {},
339
+ ) {
93
340
  if (existsSync(join(root, '.rsc', '.no-asdd-gate'))) return null;
94
- const branch = (git(root, 'rev-parse', '--abbrev-ref', 'HEAD') || '').trim();
95
- if (!branch || branch === 'HEAD' || branch === 'main' || branch === 'master') return null;
96
- const cfg = sello.readEffectiveConfig(root);
97
- const trunk = sello.trunkRef(root, cfg);
98
- if (!trunk) return null;
99
- const base = (git(root, 'merge-base', 'HEAD', trunk) || '').trim();
100
- if (!base) return null;
101
- const paths = [...new Set([
102
- ...(git(root, 'diff', '--name-only', '--no-renames', '-z', base) || '').split('\0'),
103
- ...(git(root, 'ls-files', '--others', '--exclude-standard', '-z') || '').split('\0').filter((n) => !sello.NESTED_WORKTREES.test(n)),
104
- ].filter(Boolean))].filter((n) => !sello.SELLO_STATE_PATHS.includes(n));
105
- const { tier, classes } = sello.classifyChange(paths, sello.changeText(root, base, paths), cfg);
341
+ const current = (git(repo, 'rev-parse', '--abbrev-ref', 'HEAD') || '').trim();
342
+ const branch = options.branch || current;
343
+ const tip =
344
+ options.branch && options.branch !== current ? options.branch : null;
345
+ if (!branch || branch === 'HEAD' || branch === 'main' || branch === 'master')
346
+ return null;
347
+ const local = sello.readEffectiveConfig(root);
348
+ const policy = readPolicy(repo, {
349
+ workspace: root,
350
+ localConfig: local,
351
+ tip: tip || 'HEAD',
352
+ });
353
+ const cfg = mergePolicyConfig(local, policy);
354
+ if (policy.error) return policy.error;
355
+ const trunk = policy.trunk;
356
+ if (!trunk) {
357
+ if (options.strict)
358
+ throw new Error(
359
+ 'No trunk found. Recover: set origin/HEAD or configure trunk in .rsc/sello-config.json.',
360
+ );
361
+ return null;
362
+ }
363
+ if (branch === trunk.replace(/^origin\//, '')) return null;
364
+ try {
365
+ const exemptions = (cfg.asddGate?.exemptBranches || []).map((path) => {
366
+ policyPattern(path);
367
+ return { path, class: 'exempt', tier: 0 };
368
+ });
369
+ if (exemptions.length > 64)
370
+ throw new Error('at most 64 exemptions are supported');
371
+ if (matchPolicyRules(exemptions, [branch], {}, {}, {})[branch]?.length)
372
+ return null;
373
+ } catch (e) {
374
+ return `Invalid branch exemption: ${e.message}. Recover: correct the trunk policy.`;
375
+ }
376
+ const base = (git(repo, 'merge-base', tip || 'HEAD', trunk) || '').trim();
377
+ if (!base) {
378
+ if (options.strict)
379
+ throw new Error(
380
+ 'No common ancestor with the trunk. Recover: pass a branch with shared history.',
381
+ );
382
+ return null;
383
+ }
384
+ const paths = [
385
+ ...new Set(
386
+ [
387
+ ...(
388
+ git(
389
+ repo,
390
+ 'diff',
391
+ '--name-only',
392
+ '--no-renames',
393
+ '-z',
394
+ base,
395
+ ...(tip ? [tip] : []),
396
+ ) || ''
397
+ ).split('\0'),
398
+ ...(tip
399
+ ? []
400
+ : (
401
+ git(repo, 'ls-files', '--others', '--exclude-standard', '-z') ||
402
+ ''
403
+ )
404
+ .split('\0')
405
+ .filter((n) => !sello.NESTED_WORKTREES.test(n))),
406
+ ].filter(Boolean),
407
+ ),
408
+ ].filter((n) => !sello.SELLO_STATE_PATHS.includes(n));
409
+ const details = changeDetails(repo, base, paths, tip);
410
+ const texts = tip
411
+ ? Object.fromEntries(
412
+ Object.entries(details).map(([p, d]) => [p, d.added.join('\n')]),
413
+ )
414
+ : sello.changeText(repo, base, paths);
415
+ const { tier, classes, rules, configError } = sello.classifyChange(
416
+ paths,
417
+ texts,
418
+ cfg,
419
+ details,
420
+ );
421
+ if (configError) return configError;
106
422
  if (tier < 2) return null;
107
- const tierTwo = [...new Set(Object.values(classes))].filter((c) => c !== 'default' && c !== 'docs');
423
+ const tierTwo = [...new Set(Object.values(classes))].filter(
424
+ (c) => c !== 'default' && c !== 'docs',
425
+ );
108
426
  if (tierTwo.length && tierTwo.every((c) => c === 'harness')) return null;
109
- const specs = linkedSpecs(root, branch, specCompleteness);
427
+ const specs = linkedSpecs(root, branch, specCompleteness, cfg);
110
428
  const passing = specs.filter((s) => s.ok);
111
429
  if (passing.length) {
430
+ if (cfg.asddGate?.require === 'spec') return null;
112
431
  // The spec exists; now the review it requires. A tier-2 change gets the full panel (three lenses
113
432
  // by default), recorded against one of its linked specs in the review ledger.
114
433
  const required = sello.lensesRequired(2, cfg);
115
434
  const slugs = passing.map((s) => s.path.split('/').pop().slice(0, -3));
116
- const best = panelSize(root, slugs, (sha) => reviewedStill(root, sha, trunk, sello, cfg));
435
+ const best = panelSize(root, slugs, (sha) =>
436
+ reviewedStill(repo, sha, trunk, sello, cfg, tip || 'HEAD'),
437
+ );
117
438
  if (best >= required) return null;
118
- return `Branch "${branch}" is risk tier 2 and its spec passes, but no review panel of ${required} lens(es) is recorded for it` +
439
+ return (
440
+ `Branch "${branch}" is risk tier 2 and its spec passes, but no review panel of ${required} lens(es) is recorded for it` +
119
441
  `${best ? ` (largest still valid: ${best})` : ''}. Tier 2 is reviewed by the full panel, not by one reviewer, and a panel covers ` +
120
442
  'the commit it was recorded on: code committed after it needs the panel again (the record is self-attested, like the sello). ' +
121
443
  `Recover: run the ${required} fresh-context refuters (correctness, security, tests) on the branch, then record it — ` +
122
444
  `\`npx @ericrisco/rsc review ledger panel ${slugs[0]}/closing --lenses correctness,security,tests\` — and push again. ` +
123
- 'To turn this gate off for the project: create `.rsc/.no-asdd-gate`.';
445
+ 'To turn this gate off for the project: create `.rsc/.no-asdd-gate`.'
446
+ );
124
447
  }
125
- const why = [...new Set(Object.values(classes).filter((c) => c !== 'default' && c !== 'docs'))].join(', ');
448
+ const why = [
449
+ ...new Set([
450
+ ...Object.values(classes).filter((c) => c !== 'default' && c !== 'docs'),
451
+ ...(rules || []).map((r) => r.because),
452
+ ]),
453
+ ].join(', ');
126
454
  const found = specs.length
127
455
  ? `The linked spec does not pass the gate: ${specs.map((s) => `${s.path} (missing: ${[...s.missing, ...s.empty].join(', ') || '—'})`).join('; ')}. `
128
456
  : `No spec in ${SPECS_DIR.split('\\').join('/')}/ is linked to "${branch}". `;
129
- return `Branch "${branch}" is risk tier 2 (${why || 'tier 2'}): tier 2 is ASDD work, and it does not leave this machine without an approved spec. ` +
457
+ return (
458
+ `Branch "${branch}" is risk tier 2 (${why || 'tier 2'}): tier 2 is ASDD work, and it does not leave this machine without an approved spec. ` +
130
459
  found +
131
460
  'Recover: write the spec with the `specify` skill (the four questions: what the user can do, what result they get, what it must respect, how it proves it; ' +
132
461
  `plus out of scope), put \`branch: ${branch}\` in its frontmatter, check it with \`npx @ericrisco/rsc spec gate <spec>\`, and push again. ` +
133
- 'Anything decided without the person goes to the decision queue as review-after. To turn this gate off for the project: create `.rsc/.no-asdd-gate`.';
462
+ 'Anything decided without the person goes to the decision queue as review-after. To turn this gate off for the project: create `.rsc/.no-asdd-gate`.'
463
+ );
464
+ }
465
+
466
+ /** One judgement per actual repository, with workspace specs and trusted policy. */
467
+ export function asddGate(root, command, lib, cwd = root) {
468
+ root = (git(root, 'rev-parse', '--show-toplevel') || '').trim() || root;
469
+ if (existsSync(join(root, '.rsc', '.no-asdd-gate'))) return null;
470
+ const unresolved = [];
471
+ const denials = reposWithPush(command, cwd, {
472
+ onUnresolved: (reason) => unresolved.push(reason),
473
+ })
474
+ .map((repo) => {
475
+ const why = branchCheck(root, repo, lib);
476
+ return (
477
+ why && `${repo === root ? '' : `[${relative(root, repo)}] `}${why}`
478
+ );
479
+ })
480
+ .filter(Boolean);
481
+ const reasons = [...unresolved, ...denials];
482
+ return reasons.length ? reasons.join('\n\n') : null;
134
483
  }
@@ -0,0 +1,34 @@
1
+ // Local lifecycle settings can be inherited by a worktree whose ignored runtime is
2
+ // absent. Use the same portable bootstrap as Claude's committed hook settings.
3
+ import { copyFileSync, mkdirSync, existsSync, readFileSync, rmSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const HERE = dirname(fileURLToPath(import.meta.url));
8
+ export const claudeBootstrapPath = (cwd) => join(cwd, '.claude', 'rsc-bootstrap.mjs');
9
+
10
+ export function ensureClaudeBootstrap(cwd) {
11
+ const dest = claudeBootstrapPath(cwd);
12
+ mkdirSync(dirname(dest), { recursive: true });
13
+ copyFileSync(join(HERE, 'clone-bootstrap.mjs'), dest);
14
+ }
15
+
16
+ // script and args are internal lifecycle identifiers, never caller-provided shell text.
17
+ export function claudeLifecycleCommand(script, ...args) {
18
+ return `node "\${CLAUDE_PROJECT_DIR}/.claude/rsc-bootstrap.mjs" "quiet" "\${CLAUDE_PROJECT_DIR}" "\${CLAUDE_PROJECT_DIR}/.rsc/${script}" ${args.join(' ')}`;
19
+ }
20
+
21
+ // The committed hooks and the local lifecycle hooks share this file. Retire it
22
+ // only after both settings surfaces stop referencing it; unreadable settings retain it.
23
+ export function pruneClaudeBootstrap(cwd) {
24
+ for (const name of ['settings.json', 'settings.local.json']) {
25
+ const file = join(cwd, '.claude', name);
26
+ if (!existsSync(file)) continue;
27
+ try {
28
+ const config = JSON.parse(readFileSync(file, 'utf8'));
29
+ if (!config || typeof config !== 'object' || Array.isArray(config)) return;
30
+ if (JSON.stringify(config.hooks || {}).replace(/\\\\/g, '/').includes('.claude/rsc-bootstrap.mjs')) return;
31
+ } catch { return; }
32
+ }
33
+ try { rmSync(claudeBootstrapPath(cwd), { force: true }); } catch { /* cleanup must not break uninstall */ }
34
+ }
package/targets/claude.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { pruneClaudeBootstrap } from './claude-lifecycle.js';
1
2
  import { readFileSync, writeFileSync, existsSync, mkdirSync, copyFileSync, rmSync } from 'node:fs';
2
3
  import { dirname, join, relative, sep } from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
@@ -48,12 +49,7 @@ export function hookWiringOf(entry) {
48
49
  const ATTRIBUTION_MARKER = '.rsc/attribution-default';
49
50
 
50
51
  export function unwireHook(paths) {
51
- // The bootstrap lives in the COMMITTED tree, so leaving it behind does not just orphan a file the
52
- // way a stray `.rsc/` entry would — it leaves an executable in something the user pushes. Nothing
53
- // else removes it: uninstall and purge only ever knew about `.rsc/`.
54
- try {
55
- rmSync(join(paths.projectRoot, '.claude', 'rsc-bootstrap.mjs'), { force: true });
56
- } catch { /* never let cleanup be the thing that fails */ }
52
+ const finish = (removed) => { pruneClaudeBootstrap(paths.projectRoot); return removed; };
57
53
 
58
54
  // The shadow CLAUDE.md exists only to keep the hook from being doubled by a natively-read
59
55
  // AGENTS.md. Unwiring the hook removes the reason for it. Only ever takes back an untouched one.
@@ -61,9 +57,9 @@ export function unwireHook(paths) {
61
57
  const removed = shadow ? [shadow] : [];
62
58
 
63
59
  const file = paths.hookTarget;
64
- if (!existsSync(file)) return removed;
60
+ if (!existsSync(file)) return finish(removed);
65
61
  let settings;
66
- try { settings = JSON.parse(readFileSync(file, 'utf8')); } catch { return removed; }
62
+ try { settings = JSON.parse(readFileSync(file, 'utf8')); } catch { return finish(removed); }
67
63
  // wireHook's attribution default goes back out with it — only when wireHook wrote it (the marker)
68
64
  // and it is still untouched. The same value set by the person before rsc stays theirs.
69
65
  const marker = join(paths.projectRoot, ATTRIBUTION_MARKER);
@@ -72,9 +68,9 @@ export function unwireHook(paths) {
72
68
  if (ours) delete settings.attribution;
73
69
  try { rmSync(marker, { force: true }); } catch { /* cleanup never fails the uninstall */ }
74
70
  if (!settings.hooks) {
75
- if (!ours) return removed;
71
+ if (!ours) return finish(removed);
76
72
  writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
77
- return [...removed, file];
73
+ return finish([...removed, file]);
78
74
  }
79
75
  for (const event of Object.keys(settings.hooks)) {
80
76
  settings.hooks[event] = (settings.hooks[event] || []).filter((e) => {
@@ -85,7 +81,7 @@ export function unwireHook(paths) {
85
81
  }
86
82
  if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
87
83
  writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
88
- return [...removed, file];
84
+ return finish([...removed, file]);
89
85
  }
90
86
 
91
87
  // SessionStart runs a project-local session-start.mjs via `node`: it prints
@@ -134,6 +130,7 @@ export function wireHook(paths, sourceMd, policy = {}) {
134
130
  // Same reason: session-start imports the reaper for the landed-worktree sweep, so it travels as a
135
131
  // sibling too. Missing it does not break startup — the sweep is wrapped — it just goes silent.
136
132
  copyFileSync(join(HERE, 'worktree-reaper.mjs'), join(paths.projectRoot, '.rsc', 'worktree-reaper.mjs'));
133
+ copyFileSync(join(HERE, 'risk-policy.mjs'), join(paths.projectRoot, '.rsc', 'risk-policy.mjs'));
137
134
  // session-start imports the shared update check, so it travels as a sibling too.
138
135
  copyFileSync(join(HERE, 'auto-update.mjs'), join(paths.projectRoot, '.rsc', 'auto-update.mjs'));
139
136
  // session-start imports the optional MemSlop offer lazily, so it travels as a sibling too.
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
2
2
  import { join, dirname } from 'node:path';
3
3
  import { agentByName, allAgentNames } from './agents.js';
4
+ import { cliInstructions } from '../scripts/lib/cli-invocation.js';
4
5
 
5
6
  const COMMAND_TARGETS = Object.freeze({
6
7
  claude: { dir: '.claude/commands', ext: '.md', format: 'claude', skillsAreCommands: true },
@@ -195,7 +196,7 @@ export function reconcileCommands(target, cwd, previousNames = [], desiredComman
195
196
  continue;
196
197
  }
197
198
  mkdirSync(dirname(path), { recursive: true });
198
- writeFileSync(path, render(command, target));
199
+ writeFileSync(path, cliInstructions(render(command, target)));
199
200
  written.push(path);
200
201
  names.push(command.name);
201
202
  }