@ericrisco/rsc 4.1.2 → 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.
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.
@@ -0,0 +1,424 @@
1
+ // Versioned policy and repository selection shared by risk, ASDD and worktree cleanup.
2
+ // This module is copied beside the hooks; keep its imports limited to Node builtins.
3
+ import { existsSync, readFileSync, lstatSync } from 'node:fs';
4
+ import { join, resolve, relative } from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
7
+ export const POLICY_FILE = '.rsc-risk.json';
8
+ export function git(root, ...args) {
9
+ const r = spawnSync(
10
+ 'git',
11
+ ['-C', root, '-c', 'core.quotePath=false', ...args],
12
+ {
13
+ encoding: 'utf8',
14
+ windowsHide: true,
15
+ timeout: 10000,
16
+ maxBuffer: 64 * 1024 * 1024,
17
+ },
18
+ );
19
+ return r.status === 0 ? r.stdout : null;
20
+ }
21
+ export function policyRoot(root) {
22
+ let current =
23
+ (git(root, 'rev-parse', '--show-toplevel') || '').trim() || resolve(root);
24
+ for (let n = 0; n < 20; n++) {
25
+ const parent = (
26
+ git(current, 'rev-parse', '--show-superproject-working-tree') || ''
27
+ ).trim();
28
+ if (!parent || parent === current) break;
29
+ current = parent;
30
+ }
31
+ return current;
32
+ }
33
+ export function chooseTrunk(root, cfg = null, head = 'HEAD') {
34
+ const exists = (r) =>
35
+ typeof r === 'string' &&
36
+ !r.startsWith('-') &&
37
+ git(root, 'rev-parse', '--verify', '--quiet', `${r}^{commit}`) !== null;
38
+ const requested = [
39
+ cfg?.trunk,
40
+ ...(Array.isArray(cfg?.trunks) ? cfg.trunks : []),
41
+ ]
42
+ .filter((x) => typeof x === 'string' && x.length <= 1024)
43
+ .slice(0, 16);
44
+ const refs = [
45
+ ...new Set(requested.flatMap((r) => [r, `origin/${r}`]).filter(exists)),
46
+ ];
47
+ if (refs.length) {
48
+ const distance = (r) => {
49
+ const n = git(root, 'rev-list', '--count', `${r}..${head}`);
50
+ return n === null ? Infinity : Number(n);
51
+ };
52
+ return refs.reduce((best, r) => (distance(r) < distance(best) ? r : best));
53
+ }
54
+ const remote = (
55
+ git(
56
+ root,
57
+ 'symbolic-ref',
58
+ '--quiet',
59
+ '--short',
60
+ 'refs/remotes/origin/HEAD',
61
+ ) || ''
62
+ ).trim();
63
+ return (
64
+ [
65
+ remote,
66
+ 'origin/main',
67
+ 'origin/master',
68
+ 'main',
69
+ 'master',
70
+ 'origin/develop',
71
+ 'develop',
72
+ ].find(exists) || null
73
+ );
74
+ }
75
+ const isObject = (value) =>
76
+ value !== null && typeof value === 'object' && !Array.isArray(value);
77
+
78
+ function validateSettings(settings, location) {
79
+ if (!isObject(settings)) throw new Error(`${location} must be an object`);
80
+ if (settings.rules !== undefined && !Array.isArray(settings.rules))
81
+ throw new Error(`${location}.rules must be an array`);
82
+ if (settings.risk !== undefined && !isObject(settings.risk))
83
+ throw new Error(`${location}.risk must be an object`);
84
+ if (settings.risk?.rules !== undefined && !Array.isArray(settings.risk.rules))
85
+ throw new Error(`${location}.risk.rules must be an array`);
86
+ if (settings.trunk !== undefined && typeof settings.trunk !== 'string')
87
+ throw new Error(`${location}.trunk must be a ref string`);
88
+ if (
89
+ settings.trunks !== undefined &&
90
+ (!Array.isArray(settings.trunks) ||
91
+ settings.trunks.length > 16 ||
92
+ !settings.trunks.every((x) => typeof x === 'string'))
93
+ )
94
+ throw new Error(`${location}.trunks must be an array of at most 16 refs`);
95
+ if (
96
+ settings.testRepos !== undefined &&
97
+ (!Array.isArray(settings.testRepos) ||
98
+ !settings.testRepos.every((x) => typeof x === 'string'))
99
+ )
100
+ throw new Error(`${location}.testRepos must be an array of paths`);
101
+ if (settings.asddGate !== undefined && !isObject(settings.asddGate))
102
+ throw new Error(`${location}.asddGate must be an object`);
103
+ if (
104
+ settings.asddGate?.require !== undefined &&
105
+ !['spec', 'panel'].includes(settings.asddGate.require)
106
+ )
107
+ throw new Error(`${location}.asddGate.require must be spec or panel`);
108
+ if (
109
+ settings.asddGate?.exemptBranches !== undefined &&
110
+ (!Array.isArray(settings.asddGate.exemptBranches) ||
111
+ !settings.asddGate.exemptBranches.every((x) => typeof x === 'string'))
112
+ )
113
+ throw new Error(
114
+ `${location}.asddGate.exemptBranches must be an array of patterns`,
115
+ );
116
+ if (
117
+ settings.asddGate?.cherryPickSuffix !== undefined &&
118
+ typeof settings.asddGate.cherryPickSuffix !== 'string'
119
+ )
120
+ throw new Error(`${location}.asddGate.cherryPickSuffix must be a string`);
121
+ }
122
+
123
+ function parse(text) {
124
+ if (Buffer.byteLength(text) > 1024 * 1024)
125
+ throw new Error('policy exceeds 1 MiB');
126
+ const p = JSON.parse(text);
127
+ if (!isObject(p) || p.version !== 1)
128
+ throw new Error('expected a version: 1 policy object');
129
+ validateSettings(p, 'policy');
130
+ if (p.repositories !== undefined) {
131
+ if (!isObject(p.repositories))
132
+ throw new Error(
133
+ 'repositories must be an object keyed by relative repository path',
134
+ );
135
+ for (const [name, settings] of Object.entries(p.repositories))
136
+ validateSettings(settings, `repositories[${JSON.stringify(name)}]`);
137
+ }
138
+ return p;
139
+ }
140
+ /** Shipping uses the policy on the workspace trunk. A new policy only takes effect once landed. */
141
+ export function readPolicy(
142
+ root,
143
+ {
144
+ workspace = policyRoot(root),
145
+ preview = false,
146
+ localConfig = null,
147
+ tip = 'HEAD',
148
+ } = {},
149
+ ) {
150
+ root =
151
+ (git(root, 'rev-parse', '--show-toplevel') || '').trim() || resolve(root);
152
+ workspace =
153
+ (git(workspace, 'rev-parse', '--show-toplevel') || '').trim() ||
154
+ resolve(workspace);
155
+ if (!localConfig) {
156
+ try {
157
+ localConfig = JSON.parse(
158
+ readFileSync(join(workspace, '.rsc', 'sello-config.json'), 'utf8'),
159
+ );
160
+ } catch {
161
+ /* no local bootstrap */
162
+ }
163
+ }
164
+ const rel = relative(workspace, root).split('\\').join('/') || '.';
165
+ // Bootstrap from origin/HEAD or the historic names, not from the outgoing policy.
166
+ let anchor = chooseTrunk(workspace, localConfig);
167
+ let raw = preview
168
+ ? null
169
+ : anchor &&
170
+ git(workspace, 'show', '--no-textconv', `${anchor}:${POLICY_FILE}`);
171
+ let source = anchor || 'none';
172
+ if (preview) {
173
+ try {
174
+ if (!lstatSync(join(workspace, POLICY_FILE)).isSymbolicLink())
175
+ raw = readFileSync(join(workspace, POLICY_FILE), 'utf8');
176
+ } catch {
177
+ /* no proposed policy */
178
+ }
179
+ source = 'working-tree (preview)';
180
+ }
181
+ let policy = {};
182
+ let error = null;
183
+ if (raw !== null && raw !== undefined) {
184
+ try {
185
+ policy = parse(raw);
186
+ } catch (e) {
187
+ error = `${POLICY_FILE} at ${source}: ${e.message}. Recover: correct the versioned policy on the trunk.`;
188
+ }
189
+ } else if (!preview && existsSync(join(workspace, POLICY_FILE)))
190
+ source += ' (policy absent; proposed policy inactive)';
191
+ const repoCfg =
192
+ policy.repositories && Object.hasOwn(policy.repositories, rel)
193
+ ? policy.repositories[rel]
194
+ : {};
195
+ const config = {
196
+ ...policy,
197
+ ...repoCfg,
198
+ risk: {
199
+ ...(policy.risk || {}),
200
+ ...(repoCfg.risk || {}),
201
+ rules: [...(policy.rules || []), ...(repoCfg.rules || [])],
202
+ },
203
+ repo: rel,
204
+ testRepo: (policy.testRepos || []).includes(rel),
205
+ policySource: source,
206
+ policyError: error,
207
+ };
208
+ try {
209
+ policyRules(config);
210
+ } catch (e) {
211
+ error ||= `${POLICY_FILE} at ${source}: ${e.message}. Recover: correct the trunk policy.`;
212
+ config.policyError = error;
213
+ }
214
+ return {
215
+ workspace,
216
+ source,
217
+ config,
218
+ error,
219
+ active: raw !== null && raw !== undefined,
220
+ trunk: chooseTrunk(root, { ...localConfig, ...config }, tip),
221
+ };
222
+ }
223
+
224
+ export function mergePolicyConfig(local, policy) {
225
+ return {
226
+ ...(local || {}),
227
+ ...policy.config,
228
+ risk: {
229
+ ...(local?.risk || {}),
230
+ ...(policy.active ? policy.config.risk : {}),
231
+ },
232
+ };
233
+ }
234
+
235
+ // Policy regexes are intentionally a restricted subset: no lookarounds/backreferences or repeated
236
+ // groups. Bounded lines alone do not prevent catastrophic backtracking (even 2000 bytes is enough).
237
+ export function policyPattern(pattern) {
238
+ if (
239
+ typeof pattern !== 'string' ||
240
+ pattern.length > 200 ||
241
+ /\\[1-9]|\(\?[^:]|\)(?:[+*{])/.test(pattern)
242
+ )
243
+ throw new Error(
244
+ 'policy patterns must be <=200 characters without lookarounds, backreferences or repeated groups',
245
+ );
246
+ return new RegExp(pattern, 'i');
247
+ }
248
+ export function policyRules(cfg) {
249
+ const rows = cfg?.risk?.rules || [];
250
+ if (!Array.isArray(rows) || rows.length > 64)
251
+ throw new Error('risk.rules must be an array of at most 64 rules');
252
+ return rows.map((r) => {
253
+ if (
254
+ !r ||
255
+ ![0, 1, 2].includes(r.tier) ||
256
+ typeof r.class !== 'string' ||
257
+ !r.class
258
+ )
259
+ throw new Error('each risk rule needs class and tier 0, 1 or 2');
260
+ for (const key of ['path', 'added', 'removed', 'contains'])
261
+ if (r[key] !== undefined) policyPattern(r[key]);
262
+ for (const key of ['repos', 'jsonKeys'])
263
+ if (
264
+ r[key] !== undefined &&
265
+ (!Array.isArray(r[key]) || !r[key].every((x) => typeof x === 'string'))
266
+ )
267
+ throw new Error(`${key} must be an array of strings`);
268
+ return r;
269
+ });
270
+ }
271
+ const linesMatch = (lines, p) =>
272
+ (lines || []).some((l) => l.length <= 2000 && policyPattern(p).test(l));
273
+ export function ruleApplies(r, path, detail, cfg) {
274
+ if (r.repos && !r.repos.includes(cfg?.repo || '.')) return false;
275
+ if (r.productionOnly && cfg?.testRepo) return false;
276
+ if (
277
+ r.path &&
278
+ ![path, detail.oldPath]
279
+ .filter(Boolean)
280
+ .some((p) => p.length <= 2000 && policyPattern(r.path).test(p))
281
+ )
282
+ return false;
283
+ if (r.deleted && detail.status !== 'D') return false;
284
+ if (
285
+ r.contains &&
286
+ !linesMatch(
287
+ `${detail.before || ''}\n${detail.after || ''}`.split('\n'),
288
+ r.contains,
289
+ )
290
+ )
291
+ return false;
292
+ if (r.added && !linesMatch(detail.added, r.added)) return false;
293
+ if (r.removed && !linesMatch(detail.removed, r.removed)) return false;
294
+ if (r.jsonKeys) {
295
+ try {
296
+ const a = JSON.parse(detail.before || '{}');
297
+ const b = JSON.parse(detail.after || '{}');
298
+ if (
299
+ !r.jsonKeys.some(
300
+ (k) => JSON.stringify(a?.[k]) !== JSON.stringify(b?.[k]),
301
+ )
302
+ )
303
+ return false;
304
+ } catch {
305
+ return true;
306
+ } // unreadable JSON can change the contract
307
+ }
308
+ return true;
309
+ }
310
+ /** Both paths of renames are reported by callers (--no-renames); deletions keep their old text. */
311
+ export function changeDetails(root, base, paths, tip = null) {
312
+ const out = {};
313
+ for (const path of paths) {
314
+ let after = '';
315
+ let exists = false;
316
+ try {
317
+ const st = lstatSync(join(root, path));
318
+ if (st.isFile() && !st.isSymbolicLink() && st.size <= 1024 * 1024) {
319
+ after = readFileSync(join(root, path), 'utf8');
320
+ exists = true;
321
+ }
322
+ } catch {
323
+ /* deletion */
324
+ }
325
+ if (tip) {
326
+ const text = git(root, 'show', '--no-textconv', `${tip}:${path}`);
327
+ exists = text !== null;
328
+ after = text || '';
329
+ }
330
+ const before = base
331
+ ? git(root, 'show', '--no-textconv', `${base}:${path}`)
332
+ : null;
333
+ const detail = {
334
+ before: before || '',
335
+ after,
336
+ status: !exists ? 'D' : before === null ? 'A' : 'M',
337
+ added: [],
338
+ removed: [],
339
+ };
340
+ if (!base || before === null) detail.added = after.split('\n');
341
+ else {
342
+ const diff =
343
+ git(
344
+ root,
345
+ 'diff',
346
+ '-w',
347
+ '--no-ext-diff',
348
+ '--no-textconv',
349
+ '--no-renames',
350
+ '--no-color',
351
+ '-U0',
352
+ base,
353
+ ...(tip ? [tip] : []),
354
+ '--',
355
+ path,
356
+ ) || '';
357
+ let body = false;
358
+ for (const line of diff.split('\n')) {
359
+ if (line.startsWith('@@')) {
360
+ body = true;
361
+ continue;
362
+ }
363
+ if (!body) continue;
364
+ if (line.startsWith('+')) detail.added.push(line.slice(1));
365
+ if (line.startsWith('-')) detail.removed.push(line.slice(1));
366
+ }
367
+ }
368
+ out[path] = detail;
369
+ }
370
+ return out;
371
+ }
372
+
373
+ /** User regexes run in a disposable process with a hard time limit, including polynomial cases
374
+ * that a nested-group heuristic cannot reject. Timeout/oversize becomes tier 2, never a silent pass. */
375
+ export function matchPolicyRules(rows, paths, details, texts, cfg) {
376
+ if (!rows.length) return {};
377
+ const files = Object.fromEntries(
378
+ paths.map((p) => [
379
+ p,
380
+ details[p] || { added: (texts[p] || '').split('\n') },
381
+ ]),
382
+ );
383
+ const input = JSON.stringify({
384
+ rows,
385
+ files,
386
+ repo: cfg?.repo,
387
+ testRepo: cfg?.testRepo,
388
+ });
389
+ if (Buffer.byteLength(input) > 8 * 1024 * 1024)
390
+ throw new Error('policy evaluation exceeds the bounded 8 MiB input');
391
+ const r = spawnSync(
392
+ process.execPath,
393
+ [fileURLToPath(import.meta.url), '--match-rules'],
394
+ {
395
+ input,
396
+ encoding: 'utf8',
397
+ windowsHide: true,
398
+ timeout: 1000,
399
+ maxBuffer: 8 * 1024 * 1024,
400
+ },
401
+ );
402
+ if (r.status !== 0)
403
+ throw new Error('policy evaluation exceeded its bounded runtime or failed');
404
+ return JSON.parse(r.stdout);
405
+ }
406
+ if (
407
+ process.argv[1] === fileURLToPath(import.meta.url) &&
408
+ process.argv[2] === '--match-rules'
409
+ ) {
410
+ try {
411
+ const { rows, files, repo, testRepo } = JSON.parse(readFileSync(0, 'utf8'));
412
+ const out = Object.fromEntries(
413
+ Object.entries(files).map(([path, detail]) => [
414
+ path,
415
+ rows.flatMap((row, i) =>
416
+ ruleApplies(row, path, detail, { repo, testRepo }) ? [i] : [],
417
+ ),
418
+ ]),
419
+ );
420
+ process.stdout.write(JSON.stringify(out));
421
+ } catch {
422
+ process.exitCode = 1;
423
+ }
424
+ }
package/targets/sello.mjs CHANGED
@@ -28,6 +28,8 @@ import { join, dirname } from 'node:path';
28
28
  import { homedir } from 'node:os';
29
29
  import { createHash } from 'node:crypto';
30
30
  import { spawnSync } from 'node:child_process';
31
+ import { chooseTrunk, policyRules, matchPolicyRules, readPolicy, mergePolicyConfig, policyRoot, changeDetails } from './risk-policy.mjs';
32
+ export { readPolicy, mergePolicyConfig, policyRoot, changeDetails } from './risk-policy.mjs';
31
33
 
32
34
  // ---------------------------------------------------------------- paths & config
33
35
 
@@ -127,7 +129,7 @@ export const RISK_TABLE = [
127
129
  { class: 'ci', tier: 2, pattern: '(^|/)\\.github/workflows/|(^|/)\\.gitlab-ci\\.yml$|(^|/)Jenkinsfile$' },
128
130
  { class: 'migrations', tier: 2, pattern: '(^|/)migrations?/' },
129
131
  { class: 'billing', tier: 2, pattern: '(^|/)(billing|payments?|checkout|stripe)(/|\\.|-)' },
130
- { class: 'harness', tier: 2, pattern: '(^|/)\\.rsc/|(^|/)\\.claude/|(^|/)CLAUDE\\.md$' },
132
+ { class: 'harness', tier: 2, pattern: '(^|/)\\.rsc/|(^|/)\\.rsc-risk\\.json$|(^|/)\\.claude/|(^|/)CLAUDE\\.md$' },
131
133
  ];
132
134
  export const FLOOR_CLASSES = ['secrets', 'harness'];
133
135
  export const DEFAULT_TIER = 1;
@@ -264,7 +266,7 @@ export function changeText(rawRoot, base, paths) {
264
266
  // Path rows and content rows together. A path scores the higher of the two; `content` lists each
265
267
  // content hit (path, class, the matched text) so the reader can see why. Lowered classes apply to
266
268
  // content rows too; floor classes stay at tier 2.
267
- export function classifyChange(paths, texts = {}, cfg = null) {
269
+ export function classifyChange(paths, texts = {}, cfg = null, details = {}) {
268
270
  const byPath = classifyRisk(paths, cfg);
269
271
  const lowered = byPath.lowered || [];
270
272
  const content = [];
@@ -285,12 +287,39 @@ export function classifyChange(paths, texts = {}, cfg = null) {
285
287
  break;
286
288
  }
287
289
  }
288
- return { ...byPath, tier, classes, content };
290
+ const rules = [];
291
+ const policyTiers = {};
292
+ let configError = byPath.configError || cfg?.policyError || null;
293
+ try {
294
+ const configured = policyRules(cfg);
295
+ const matched = matchPolicyRules(configured, paths, details, texts, cfg);
296
+ for (const p of paths) {
297
+ const detail = details[p] || { added: (texts[p] || '').split('\n') };
298
+ const hits = (matched[p] || []).map(i => configured[i]);
299
+ if (!hits.length) continue;
300
+ const best = hits.reduce((a,b) => a.tier >= b.tier ? a : b);
301
+ const intrinsic = classifyRisk([p], cfg);
302
+ const contentTier = content.filter(h => h.path === p).reduce((n,h) => Math.max(n,rowTier(h.class)),0);
303
+ const floor = intrinsic.classes[p] === 'default' ? 0 : intrinsic.tier;
304
+ const effective = Math.max(best.tier, floor, contentTier);
305
+ if (effective === best.tier) classes[p] = best.class;
306
+ rules.push(...hits.map(r => ({ path:p, class:r.class, tier:r.tier, because:r.because || r.class })));
307
+ policyTiers[p] = effective;
308
+ }
309
+ // Recompute so an explicit level-zero rule can replace the ordinary-code default.
310
+ tier = paths.reduce((n,p) => Math.max(n, policyTiers[p] ?? Math.max(classifyRisk([p],cfg).tier, ...content.filter(h=>h.path===p).map(h=>rowTier(h.class)))),0);
311
+ } catch (e) { configError = `${e.message}. Recover: correct risk.rules in .rsc-risk.json.`; }
312
+ if (configError) tier = Math.max(tier, 2);
313
+ return { ...byPath, tier, classes, content, rules, configError };
314
+
289
315
  }
290
316
 
291
317
  export function classifyCandidate(rawRoot, candidate, cfg = null) {
292
318
  const paths = Object.keys(candidate.files);
293
- return classifyChange(paths, changeText(rawRoot, candidate.base, paths), cfg);
319
+ const root = resolveRoot(rawRoot);
320
+ const policy = readPolicy(root, { localConfig: cfg });
321
+ const effective = mergePolicyConfig(cfg, policy);
322
+ return classifyChange(paths, changeText(root, candidate.base, paths), effective, changeDetails(root, candidate.base, paths));
294
323
  }
295
324
 
296
325
  // How many lenses a tier requires (capped by an explicit config knob, floor 1).
@@ -315,11 +344,7 @@ function git(root, ...args) {
315
344
  const nulList = (out) => (out || '').split('\0').filter(Boolean);
316
345
 
317
346
  export function trunkRef(root, cfg = null) {
318
- const configured = typeof cfg?.trunk === 'string' ? [cfg.trunk, `origin/${cfg.trunk}`] : [];
319
- for (const ref of [...configured, 'origin/main', 'origin/master', 'main', 'master']) {
320
- if (git(root, 'rev-parse', '--verify', '--quiet', ref) !== null) return ref;
321
- }
322
- return null;
347
+ return chooseTrunk(root, cfg);
323
348
  }
324
349
 
325
350
  // The candidate is the change vs the trunk merge-base: every path that differs
@@ -329,7 +354,7 @@ export function trunkRef(root, cfg = null) {
329
354
  // read, and a link to a FIFO would hang the hook).
330
355
  export function computeCandidate(rawRoot, cfg = null) {
331
356
  const root = resolveRoot(rawRoot);
332
- const trunk = trunkRef(root, cfg);
357
+ const trunk = readPolicy(root, { localConfig: cfg }).trunk;
333
358
  if (!trunk) return null;
334
359
  const head = git(root, 'rev-parse', 'HEAD');
335
360
  const base = head ? (git(root, 'merge-base', 'HEAD', trunk) || '').trim() : null;
@@ -121,6 +121,13 @@ export function isolationContext({ project, here, sessionId, target, memoryRoot
121
121
  const others = otherActiveSessions({ cwd: project, worktreeCwd: here, sessionId, target, memoryRoot });
122
122
  if (!others.length) return '';
123
123
  const who = others.map((o) => `${o.target}${o.branch ? ` en «${o.branch}»` : ''}`).join(', ');
124
+ let orca = Boolean(process.env.ORCA_WORKTREE_ID || process.env.ORCA_WORKSPACE_ID);
125
+ try { orca ||= JSON.parse(readFileSync(join(project, '.rsc.json'), 'utf8'))?.worktreeManager === 'orca'; } catch { /* normal warning below */ }
126
+ if (orca) return `rsc · aislamiento: otra sesión está trabajando en esta misma carpeta (${who}). ` +
127
+ 'Orca gestiona este entorno: consulta `orca worktree current --json` y verifica las identidades de las sesiones antes de compartir el checkout. ' +
128
+ 'El parentesco entre worktrees no demuestra que las sesiones pertenezcan a la misma tarea; sin esa verificación se mantiene el aislamiento. ' +
129
+ 'Crea trabajo independiente con `orca worktree create --name <tarea> --no-parent --base-branch origin/<troncal> --json`, ' +
130
+ 'espera a que terminen sus hooks de preparación y trabaja en la ruta que devuelve Orca. No cambies de rama en esta carpeta.';
124
131
  return `rsc · aislamiento: otra sesión está trabajando en esta misma carpeta (${who}). ` +
125
132
  'Cualquier cambio de esta petición se hace en un worktree en `.worktrees/` de la raíz, nunca dentro de una carpeta de proyecto: ' +
126
133
  '`git worktree add .worktrees/<rama> -b <rama>` (si el proyecto está en una subcarpeta, `git -C <proyecto> worktree add <raíz>/.worktrees/<proyecto>-<rama> -b <rama>`, con la ruta absoluta) y se trabaja dentro. ' +
@@ -68,7 +68,7 @@ try {
68
68
  const sello = await import(new URL('./sello.mjs', import.meta.url));
69
69
  const { specCompleteness } = await import(new URL('./spec-completeness.mjs', import.meta.url));
70
70
  const { asddGate } = await import(new URL('./asdd-gate.mjs', import.meta.url));
71
- const verdict = asddGate(root, command, { sello, specCompleteness });
71
+ const verdict = asddGate(root, command, { sello, specCompleteness }, input.cwd || root);
72
72
  if (verdict) deny(verdict);
73
73
  } catch { /* sibling missing/unloadable → nothing to enforce, fail open */ }
74
74
 
@@ -182,7 +182,8 @@ function parseOpenPoints(lines) {
182
182
  * untyped: string[], unchecked: string[]}}
183
183
  */
184
184
  export function specCompleteness(markdown) {
185
- const lines = String(markdown ?? '').split('\n');
185
+ const text = String(markdown ?? '').replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
186
+ const lines = text.split('\n');
186
187
  const sections = new Map(); // family -> body lines
187
188
 
188
189
  let current = null;
@@ -197,7 +198,7 @@ export function specCompleteness(markdown) {
197
198
  if (current && sections.has(current)) sections.get(current).push(line);
198
199
  }
199
200
 
200
- const families = requiredFamilies(markdown);
201
+ const families = requiredFamilies(text);
201
202
  const missing = families.filter((f) => !sections.has(f));
202
203
  const empty = families.filter((f) => sections.has(f) && !hasSubstance(sections.get(f)));
203
204