@ericrisco/rsc 4.1.3 → 4.1.4

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
  }
package/targets/claude.js CHANGED
@@ -134,6 +134,7 @@ export function wireHook(paths, sourceMd, policy = {}) {
134
134
  // Same reason: session-start imports the reaper for the landed-worktree sweep, so it travels as a
135
135
  // sibling too. Missing it does not break startup — the sweep is wrapped — it just goes silent.
136
136
  copyFileSync(join(HERE, 'worktree-reaper.mjs'), join(paths.projectRoot, '.rsc', 'worktree-reaper.mjs'));
137
+ copyFileSync(join(HERE, 'risk-policy.mjs'), join(paths.projectRoot, '.rsc', 'risk-policy.mjs'));
137
138
  // session-start imports the shared update check, so it travels as a sibling too.
138
139
  copyFileSync(join(HERE, 'auto-update.mjs'), join(paths.projectRoot, '.rsc', 'auto-update.mjs'));
139
140
  // 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
  }
package/targets/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, mkdirSync, rmSync, symlinkSync, cpSync, readFileSync } from 'node:fs';
1
+ import { existsSync, lstatSync, statSync, mkdirSync, rmSync, symlinkSync, cpSync, readFileSync } from 'node:fs';
2
2
  import { join, dirname, relative } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import * as claudeAdapter from './claude.js';
@@ -46,6 +46,8 @@ const SPEC = {
46
46
  opencode: { root: '.opencode/rsc', hook: 'AGENTS.md', adapter: 'md' },
47
47
  // DeepSeek Harness discovers <root>/.dsh/skills/<name>/SKILL.md natively.
48
48
  deepseek: { root: '.dsh/skills', hook: 'AGENTS.md', adapter: 'md' },
49
+ // Pi discovers skills natively; targetPaths follows its context-file precedence.
50
+ pi: { root: '.pi/skills', hook: 'AGENTS.md', adapter: 'md' },
49
51
  amp: { root: '.amp/rsc', hook: 'AGENTS.md', adapter: 'md' },
50
52
  jules: { root: '.jules/rsc', hook: 'AGENTS.md', adapter: 'md' },
51
53
  zed: { root: '.zed/rsc', hook: 'AGENTS.md', adapter: 'md' },
@@ -81,6 +83,7 @@ export const TARGETS = [
81
83
  { id: 'amp', label: 'Amp', hint: 'AGENTS.md' },
82
84
  { id: 'opencode', label: 'opencode', hint: 'AGENTS.md' },
83
85
  { id: 'deepseek', label: 'DeepSeek Harness', hint: '.dsh/skills/' },
86
+ { id: 'pi', label: 'Pi', hint: '.pi/skills/' },
84
87
  { id: 'jules', label: 'Jules', hint: 'AGENTS.md' },
85
88
  { id: 'junie', label: 'JetBrains Junie', hint: '.junie/guidelines.md' },
86
89
  { id: 'kiro', label: 'Kiro', hint: '.kiro/steering/' },
@@ -122,6 +125,7 @@ export function detectTarget(cwd = process.cwd()) {
122
125
  if (has('.zed')) return 'zed';
123
126
  if (has('.opencode')) return 'opencode';
124
127
  if (has('.dsh')) return 'deepseek';
128
+ if (has('.pi')) return 'pi';
125
129
  if (has('.amp')) return 'amp';
126
130
  if (has('.jules')) return 'jules';
127
131
  if (has('.antigravity')) return 'antigravity';
@@ -156,16 +160,41 @@ export function resolveTargets({ cwd = process.cwd(), flagValue } = {}) {
156
160
  return { ids: [detectTarget(cwd)], ambiguous: null, source: 'heuristic' };
157
161
  }
158
162
 
163
+ // Pi loads only the first readable context file in a directory. Creating AGENTS.md
164
+ // beside an existing CLAUDE.md would hide the user's instructions; an override
165
+ // would hide a block written into AGENTS.md. Match the native loader's order.
166
+ function fileIdentity(file) {
167
+ try { const { dev, ino } = statSync(file); return `${dev}:${ino}`; }
168
+ catch { return file; }
169
+ }
170
+
171
+ function piContextFiles(cwd) {
172
+ const seen = new Set();
173
+ return ['AGENTS.override.md', 'AGENTS.md', 'AGENTS.MD', 'CLAUDE.md', 'CLAUDE.MD']
174
+ .map((name) => join(cwd, name)).filter((file) => {
175
+ try {
176
+ if (!statSync(file).isFile()) return false;
177
+ readFileSync(file, 'utf8');
178
+ const identity = fileIdentity(file);
179
+ if (seen.has(identity)) return false;
180
+ seen.add(identity);
181
+ return true;
182
+ } catch { return false; } // Pi skips unreadable and non-file candidates too.
183
+ });
184
+ }
185
+
159
186
  export function targetPaths(target, home = homedir(), cwd = process.cwd()) {
160
187
  const s = SPEC[target];
161
188
  if (!s) throw new Error(`unknown target ${target}`);
162
189
  const rootAbs = join(cwd, ...s.root.split('/'));
190
+ const contextFiles = target === 'pi' ? piContextFiles(cwd) : null;
163
191
  return {
164
192
  root: rootAbs,
165
193
  projectRoot: cwd,
166
194
  skillDir: (id) => (s.skillExt ? join(rootAbs, `${id}${s.skillExt}`) : join(rootAbs, id)),
167
195
  stateFile: join(rootAbs, '.rsc-state.json'),
168
- hookTarget: join(cwd, ...s.hook.split('/')),
196
+ hookTarget: contextFiles ? contextFiles[0] || join(cwd, 'AGENTS.md') : join(cwd, ...s.hook.split('/')),
197
+ ...(contextFiles ? { contextFiles } : {}),
169
198
  };
170
199
  }
171
200
 
@@ -174,14 +203,34 @@ export function writeSkill(target, id, fromDir, toPath) {
174
203
  }
175
204
 
176
205
  export function wireHook(target, paths, sourceMd, policy) {
206
+ if (target === 'pi') {
207
+ // Sync migrates Pi's block when native precedence changes. Keep any old
208
+ // location still used by another target; the installer backs these up first.
209
+ const shared = sharedHookFiles(target, paths.projectRoot);
210
+ for (const file of paths.contextFiles || []) {
211
+ if (fileIdentity(file) !== fileIdentity(paths.hookTarget) && !shared.has(fileIdentity(file))) mdAdapter.unwireHook({ ...paths, hookTarget: file });
212
+ }
213
+ }
177
214
  return ADAPTER[SPEC[target].adapter].wireHook(paths, sourceMd, policy);
178
215
  }
179
216
 
217
+ function sharedHookFiles(target, cwd) {
218
+ return new Set(installedTargets(cwd).filter((other) => other !== target)
219
+ .map((other) => fileIdentity(targetPaths(other, undefined, cwd).hookTarget)));
220
+ }
221
+
180
222
  // Inverse of wireHook — remove rsc's always-on surface for a target (settings.json
181
223
  // hook entries / AGENTS-block / cursor rule file). Returns the paths it touched.
182
224
  export function unwireHook(target, paths) {
225
+ // AGENTS.md is shared by several targets. Removing one install must not remove
226
+ // the always-on instructions of another install that still reads this file.
227
+ const shared = sharedHookFiles(target, paths.projectRoot);
183
228
  const adapter = ADAPTER[SPEC[target].adapter];
184
- return adapter.unwireHook ? adapter.unwireHook(paths) : [];
229
+ // A new override can change Pi's selected context since installation. Remove
230
+ // its marked blocks from previous context files too; never the user's prose.
231
+ const files = target === 'pi' ? piContextFiles(paths.projectRoot) : [paths.hookTarget];
232
+ return files.filter((file) => !shared.has(fileIdentity(file))).flatMap((file) =>
233
+ adapter.unwireHook ? adapter.unwireHook({ ...paths, hookTarget: file }) : []);
185
234
  }
186
235
 
187
236
  // Every known target id — used by `purge` to sweep all assistants, installed or not.