@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.
- package/README.md +90 -2
- package/manifest.json +1 -1
- package/package.json +1 -1
- package/scripts/doctor.js +17 -1
- package/scripts/install-apply.js +17 -8
- package/scripts/lib/cli-invocation.js +44 -0
- package/scripts/lib/manifest-file.js +2 -1
- package/scripts/lib/risk.js +6 -4
- package/scripts/rsc.js +39 -4
- package/skills/worktrees/SKILL.md +6 -0
- package/skills/worktrees/evals/cases.yaml +7 -0
- package/skills/worktrees/references/orca.md +64 -0
- package/targets/asdd-gate.mjs +401 -52
- package/targets/claude.js +1 -0
- package/targets/commands.js +2 -1
- package/targets/index.js +52 -3
- package/targets/risk-policy.mjs +424 -0
- package/targets/sello.mjs +35 -10
- package/targets/session-memory-adapter.mjs +7 -0
- package/targets/ship-guard.mjs +1 -1
- package/targets/worktree-reaper.mjs +42 -4
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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. ' +
|
package/targets/ship-guard.mjs
CHANGED
|
@@ -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
|
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
//
|
|
17
17
|
// Imported by `.rsc/session-start.mjs` (the sweep) and by `scripts/rsc.js` (`rsc worktrees`), so the
|
|
18
18
|
// rule exists once and both entry points cannot drift apart. Same shape as `sello.mjs`.
|
|
19
|
+
import { readPolicy } from './risk-policy.mjs';
|
|
19
20
|
import { existsSync, realpathSync, mkdirSync, readFileSync, readdirSync, writeFileSync, renameSync, chmodSync, copyFileSync } from 'node:fs';
|
|
20
21
|
import { join, resolve, dirname, basename, relative, sep } from 'node:path';
|
|
21
22
|
import { spawnSync } from 'node:child_process';
|
|
@@ -111,7 +112,8 @@ export function resolveMainRoot(cwd = process.cwd()) {
|
|
|
111
112
|
}
|
|
112
113
|
|
|
113
114
|
/** Is this ref one of the trunk names? Deleting one is never a side effect of a cleanup. */
|
|
114
|
-
export function isTrunkName(branch) {
|
|
115
|
+
export function isTrunkName(branch, root = null) {
|
|
116
|
+
if (root && resolveTrunk(root)?.replace(/^origin\//, '') === branch) return true;
|
|
115
117
|
return TRUNKS.some((t) => t === branch || t.endsWith(`/${branch}`));
|
|
116
118
|
}
|
|
117
119
|
|
|
@@ -122,7 +124,7 @@ export function isCleanupEnabled(root) {
|
|
|
122
124
|
|
|
123
125
|
/** The first trunk ref that actually exists, or null when there is nothing to compare against. */
|
|
124
126
|
export function resolveTrunk(root) {
|
|
125
|
-
return
|
|
127
|
+
return readPolicy(root).trunk;
|
|
126
128
|
}
|
|
127
129
|
|
|
128
130
|
/** Every working tree git knows about. The first entry is always the main one. */
|
|
@@ -181,7 +183,36 @@ export function atWorkspaceRoot(p, home) {
|
|
|
181
183
|
return home.startsWith(ws + sep) && home !== ws;
|
|
182
184
|
}
|
|
183
185
|
|
|
186
|
+
// External managers own more than Git's directory (setup/teardown hooks, submodules and their
|
|
187
|
+
// registry). A matching branch name never grants us their lifecycle. The committed setting is
|
|
188
|
+
// authoritative even when the manager's executable is absent, e.g. a clone on another machine.
|
|
189
|
+
function orcaOwnership(root, path) {
|
|
190
|
+
for (const dir of new Set([root, path])) {
|
|
191
|
+
const manifest = join(dir, '.rsc.json');
|
|
192
|
+
if (!existsSync(manifest)) continue;
|
|
193
|
+
try {
|
|
194
|
+
if (JSON.parse(readFileSync(manifest, 'utf8'))?.worktreeManager === 'orca') return 'orca';
|
|
195
|
+
} catch { return 'manager-unknown'; }
|
|
196
|
+
}
|
|
197
|
+
const r = spawnSync('orca', ['worktree', 'current', '--json'], {
|
|
198
|
+
cwd: path, encoding: 'utf8', windowsHide: true, timeout: 1500, killSignal: 'SIGKILL', maxBuffer: 256 * 1024,
|
|
199
|
+
});
|
|
200
|
+
if (r.error?.code === 'ENOENT') return null;
|
|
201
|
+
if (r.error || r.status !== 0) return 'manager-unknown';
|
|
202
|
+
try {
|
|
203
|
+
const result = JSON.parse(r.stdout)?.result;
|
|
204
|
+
// Only an explicit empty result is evidence this checkout is unmanaged. A malformed response,
|
|
205
|
+
// timeout or caller identity resolving a different checkout must not authorise plain Git removal.
|
|
206
|
+
if (result && Object.hasOwn(result, 'worktree') && result.worktree === null) return null;
|
|
207
|
+
const wt = result?.worktree;
|
|
208
|
+
return typeof wt?.id === 'string' && wt.id && typeof wt.path === 'string' && real(wt.path) === real(path)
|
|
209
|
+
? 'orca' : 'manager-unknown';
|
|
210
|
+
} catch { return 'manager-unknown'; }
|
|
211
|
+
}
|
|
212
|
+
|
|
184
213
|
export function provenanceOf(root, wt) {
|
|
214
|
+
const manager = orcaOwnership(root, wt.path);
|
|
215
|
+
if (manager) return manager;
|
|
185
216
|
const p = wt.path;
|
|
186
217
|
const home = real(root);
|
|
187
218
|
const inside = (dir) => p === dir || p.startsWith(dir + sep);
|
|
@@ -320,6 +351,7 @@ export function classifyWorktrees(root) {
|
|
|
320
351
|
|
|
321
352
|
const provenance = provenanceOf(root, wt);
|
|
322
353
|
if (provenance === 'foreign') return { ...base, reasons: ['foreign'] };
|
|
354
|
+
if (provenance === 'orca' || provenance === 'manager-unknown') return { ...base, reasons: [provenance] };
|
|
323
355
|
|
|
324
356
|
if (wt.locked) return { ...base, reasons: ['locked'] };
|
|
325
357
|
|
|
@@ -389,7 +421,7 @@ export function reapWorktree(root, targetPath, { confirmed = false } = {}) {
|
|
|
389
421
|
// `-d` refuses an unmerged branch, which is the recovery net — but it happily deletes the TRUNK,
|
|
390
422
|
// which is an ancestor of everything. A sibling checkout of `main` classified as ambiguous, the user
|
|
391
423
|
// confirmed removing a stray directory, and the trunk ref went with it.
|
|
392
|
-
const branchDeleted = candidate.branch && !isTrunkName(candidate.branch)
|
|
424
|
+
const branchDeleted = candidate.branch && !isTrunkName(candidate.branch, root)
|
|
393
425
|
? git(root, ['branch', '-d', candidate.branch]).ok
|
|
394
426
|
: false;
|
|
395
427
|
// No `git worktree prune` here. It has no expiry of its own, so running it while another worktree's
|
|
@@ -479,7 +511,7 @@ export function reapMergedBranches(root) {
|
|
|
479
511
|
for (const line of refs.out.split('\n').filter(Boolean)) {
|
|
480
512
|
const [branch, track = ''] = line.split('\0');
|
|
481
513
|
const keep = (reason) => out.kept.push({ branch, reason });
|
|
482
|
-
if (branch === defaultName || isTrunkName(branch) || KEEP_BRANCHES.includes(branch)) continue;
|
|
514
|
+
if (branch === defaultName || isTrunkName(branch, root) || KEEP_BRANCHES.includes(branch)) continue;
|
|
483
515
|
if (branch === current) { keep('current branch'); continue; }
|
|
484
516
|
if (checkedOut.has(branch)) { keep('checked out in a worktree'); continue; }
|
|
485
517
|
if (!git(root, ['merge-base', '--is-ancestor', `refs/heads/${branch}`, trunk]).ok) continue; // live work
|
|
@@ -651,6 +683,12 @@ export function refusal(candidate) {
|
|
|
651
683
|
const d = candidate.details || {};
|
|
652
684
|
const parts = (candidate.reasons || []).map((reason) => {
|
|
653
685
|
switch (reason) {
|
|
686
|
+
case 'orca':
|
|
687
|
+
return 'Orca manages this checkout, so rsc will not remove it through Git, even with --confirm. ' +
|
|
688
|
+
'After reviewing its state, use `orca worktree rm --worktree path:<checkout> --run-hooks --json` with its exact path so Orca runs teardown hooks.';
|
|
689
|
+
case 'manager-unknown':
|
|
690
|
+
return 'worktree-manager ownership could not be verified; nothing was removed. Check `.rsc.json` and run `orca worktree current --json` from that checkout. ' +
|
|
691
|
+
'If Orca owns it, remove it through `orca worktree rm --worktree path:<checkout> --run-hooks --json` after reviewing its state.';
|
|
654
692
|
case 'foreign':
|
|
655
693
|
return 'it was not created by rsc, so it is not ours to delete. Remove it yourself with `git worktree remove` if you want it gone.';
|
|
656
694
|
case 'not-integrated':
|