rollcage-init 0.0.0-stage → 0.5.1

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/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "rollcage-init",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.1",
4
+ "description": "One-command Rollcage setup: adds PR risk gate, agent policy, DORA, secrets guard, SBOM triage and policy gates to a repository",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "rollcage-init": "rollcage-init.mjs"
9
+ },
10
+ "files": [
11
+ "rollcage-init.mjs"
12
+ ],
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/frankTurtle/rollcage.git",
19
+ "directory": "init"
20
+ },
21
+ "homepage": "https://github.com/frankTurtle/rollcage#readme",
22
+ "bugs": "https://github.com/frankTurtle/rollcage/issues",
23
+ "keywords": [
24
+ "devsecops",
25
+ "ai-agents",
26
+ "supply-chain",
27
+ "provenance",
28
+ "ci"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public",
32
+ "provenance": true
33
+ }
34
+ }
@@ -0,0 +1,767 @@
1
+ #!/usr/bin/env node
2
+ // One-command Rollcage setup for an existing repository.
3
+ //
4
+ // npx rollcage-init [options]
5
+ // (or) curl -fsSL https://raw.githubusercontent.com/frankTurtle/rollcage/main/init/rollcage-init.mjs | node - [options]
6
+ //
7
+ // It detects the repo, then writes the files for the production-proven pieces (01 PR risk gate,
8
+ // 02 agent policy, 03 DORA metrics, 04 secrets guard, 05 SBOM and CVE triage, 06 policy gates and a
9
+ // manual 10 provenance workflow), with every Rollcage reference pinned to a commit SHA.
10
+ // It never overwrites a file, never pushes, and never calls GitHub. Node 20+, git, and pnpm (only to
11
+ // build the piece 02 hook) are the only requirements.
12
+ import { execFileSync } from 'node:child_process';
13
+ import {
14
+ copyFileSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ mkdtempSync,
18
+ readdirSync,
19
+ readFileSync,
20
+ realpathSync,
21
+ rmSync,
22
+ writeFileSync,
23
+ } from 'node:fs';
24
+ import { tmpdir } from 'node:os';
25
+ import { dirname, join, resolve } from 'node:path';
26
+ import { fileURLToPath } from 'node:url';
27
+ import { parseArgs } from 'node:util';
28
+
29
+ const DEFAULT_REF = 'v0.5.0';
30
+ const REPO_URL = 'https://github.com/frankTurtle/rollcage';
31
+ export const DEFAULT_PIECES = ['01', '02', '03', '04', '05', '06', '10'];
32
+ const PIECE_NAMES = {
33
+ '01': 'PR risk gate',
34
+ '02': 'Agent policy',
35
+ '03': 'DORA metrics',
36
+ '04': 'Secrets guard',
37
+ '05': 'SBOM and CVE triage',
38
+ '06': 'Policy gates',
39
+ 10: 'Provenance (manual workflow)',
40
+ };
41
+
42
+ const CHECKOUT = 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1';
43
+ const PNPM = 'pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1';
44
+ const NODE = 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0';
45
+
46
+ class InitError extends Error {}
47
+
48
+ // ---------------------------------------------------------------- validation
49
+
50
+ // A leading dash would let a ref act as a git option.
51
+ const SAFE_REF = /^[A-Za-z0-9._][A-Za-z0-9._/-]{0,99}$/;
52
+ const SAFE_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
53
+ const SAFE_REPO = /^[A-Za-z0-9._-]{1,100}$/;
54
+
55
+ export function parsePieces(only, without) {
56
+ const list = (text) =>
57
+ String(text ?? '')
58
+ .split(',')
59
+ .map((s) => s.trim().padStart(2, '0'))
60
+ .filter((s) => s !== '00');
61
+ const chosen = only ? list(only) : [...DEFAULT_PIECES];
62
+ const bad = [...chosen, ...list(without)].filter((p) => !(p in PIECE_NAMES));
63
+ if (bad.length > 0) {
64
+ throw new InitError(
65
+ `unknown or not-yet-supported piece ${bad.join(', ')}; supported: ${Object.keys(PIECE_NAMES).join(', ')}`,
66
+ );
67
+ }
68
+ const drop = new Set(list(without));
69
+ return chosen.filter((p) => !drop.has(p));
70
+ }
71
+
72
+ // ----------------------------------------------------------------- detection
73
+
74
+ const git = (cwd, ...args) =>
75
+ execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
76
+
77
+ export function parseRemote(url) {
78
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url ?? '');
79
+ return m ? { owner: m[1], repo: m[2] } : null;
80
+ }
81
+
82
+ function readJson(path) {
83
+ try {
84
+ return JSON.parse(readFileSync(path, 'utf8'));
85
+ } catch {
86
+ return null;
87
+ }
88
+ }
89
+
90
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'vendor', '.terraform']);
91
+
92
+ function hasFileMatching(dir, test, depth = 3) {
93
+ if (depth < 0) return false;
94
+ let entries;
95
+ try {
96
+ entries = readdirSync(dir, { withFileTypes: true });
97
+ } catch {
98
+ return false;
99
+ }
100
+ return entries.some((e) => {
101
+ if (SKIP_DIRS.has(e.name)) return false;
102
+ return e.isDirectory() ? hasFileMatching(join(dir, e.name), test, depth - 1) : test(e.name);
103
+ });
104
+ }
105
+
106
+ /** What the repo is, so the output and next steps fit it. Pure reads, no writes. */
107
+ function detect(root) {
108
+ const pkg = readJson(join(root, 'package.json'));
109
+ const has = (name) => existsSync(join(root, name));
110
+ const languages = [
111
+ pkg && 'javascript/typescript',
112
+ (has('pyproject.toml') || has('requirements.txt')) && 'python',
113
+ has('go.mod') && 'go',
114
+ has('Cargo.toml') && 'rust',
115
+ (has('pom.xml') || has('build.gradle') || has('build.gradle.kts')) && 'java',
116
+ ].filter(Boolean);
117
+ let remote = null;
118
+ try {
119
+ remote = parseRemote(git(root, 'remote', 'get-url', 'origin'));
120
+ } catch {
121
+ // not a git repo, or no origin: owner falls back to --owner
122
+ }
123
+ const workflowsDir = join(root, '.github/workflows');
124
+ const ciWorkflows = existsSync(workflowsDir)
125
+ ? readdirSync(workflowsDir).filter((f) => /\.ya?ml$/.test(f))
126
+ : [];
127
+ const calledWorkflows = ciWorkflows
128
+ .filter((f) => f !== 'rollcage.yml')
129
+ .flatMap((f) =>
130
+ [
131
+ ...readFileSync(join(workflowsDir, f), 'utf8').matchAll(
132
+ /uses:\s*\.\/\.github\/workflows\/([\w.-]+\.ya?ml)/g,
133
+ ),
134
+ ].map((m) => m[1]),
135
+ );
136
+ return {
137
+ languages,
138
+ usesPnpm: typeof pkg?.packageManager === 'string' && pkg.packageManager.startsWith('pnpm@'),
139
+ terraform: hasFileMatching(root, (n) => n.endsWith('.tf')),
140
+ ciWorkflows,
141
+ calledWorkflows,
142
+ remote,
143
+ };
144
+ }
145
+
146
+ // ------------------------------------------------------------ source checkout
147
+
148
+ /** Shallow clone of the rollcage repo at `ref` into a new temp dir; returns its path and SHA. */
149
+ function fetchSource(ref, url = REPO_URL) {
150
+ if (!SAFE_REF.test(ref)) throw new InitError(`invalid --ref ${ref}`);
151
+ const dir = mkdtempSync(join(tmpdir(), 'rollcage-src-'));
152
+ const run = (...args) => execFileSync('git', args, { cwd: dir, stdio: 'ignore' });
153
+ try {
154
+ try {
155
+ execFileSync('git', ['clone', '--quiet', '--depth', '1', '--branch', ref, url, dir], {
156
+ stdio: 'ignore',
157
+ });
158
+ } catch {
159
+ // `ref` may be a commit SHA, which --branch cannot take.
160
+ run('init', '--quiet');
161
+ run('fetch', '--quiet', '--depth', '1', url, ref);
162
+ run('checkout', '--quiet', 'FETCH_HEAD');
163
+ }
164
+ } catch {
165
+ rmSync(dir, { recursive: true, force: true });
166
+ throw new InitError(`could not fetch ${url} at ${ref}; check the ref and your network`);
167
+ }
168
+ return { dir, sha: git(dir, 'rev-parse', 'HEAD'), temporary: true };
169
+ }
170
+
171
+ // ----------------------------------------------------------------- rendering
172
+
173
+ /** Pin line for a rollcage reference: `<sha> # <ref>` so Dependabot and humans can read it. */
174
+ function pinned(ctx) {
175
+ return `${ctx.sha} # ${ctx.ref}`;
176
+ }
177
+
178
+ const readSource = (ctx, rel) => readFileSync(join(ctx.source, rel), 'utf8');
179
+ const template12 = (ctx, name) =>
180
+ readSource(ctx, `pieces/12-golden-path-template/template/${name}`)
181
+ .replaceAll('__ROLLCAGE_REF__', pinned(ctx))
182
+ .replaceAll('__OWNER__', ctx.owner);
183
+
184
+ /** The piece actions install pnpm through corepack, so the caller only needs the step when its own
185
+ * package.json pins pnpm; without a pin, pnpm/action-setup fails on a non-pnpm repo. */
186
+ const dropPnpmSetup = (ctx, text) =>
187
+ ctx.detected.usesPnpm ? text : text.replace(/^\s*- uses: pnpm\/action-setup@.*\n/gm, '');
188
+
189
+ const ROLLCAGE_WORKFLOW_JOBS = {
190
+ '01': {
191
+ name: 'risk-gate',
192
+ file: 'gate-pr-risk.yml',
193
+ job: ` risk-gate:
194
+ if: github.event_name == 'pull_request'
195
+ permissions:
196
+ contents: read
197
+ pull-requests: write
198
+ uses: ./.github/workflows/gate-pr-risk.yml`,
199
+ },
200
+ '02': {
201
+ name: 'agent-policy',
202
+ file: 'agent-policy.yml',
203
+ job: ` agent-policy:
204
+ uses: ./.github/workflows/agent-policy.yml`,
205
+ },
206
+ '04': {
207
+ name: 'secrets',
208
+ file: 'secrets-scan.yml',
209
+ job: ` secrets:
210
+ permissions:
211
+ contents: read
212
+ pull-requests: read
213
+ uses: ./.github/workflows/secrets-scan.yml
214
+ secrets:
215
+ GITLEAKS_LICENSE: \${{ secrets.GITLEAKS_LICENSE }}`,
216
+ },
217
+ '05': {
218
+ name: 'sbom',
219
+ file: 'sbom-vuln.yml',
220
+ job: ` sbom:
221
+ uses: ./.github/workflows/sbom-vuln.yml
222
+ with:
223
+ path: .
224
+ fail-on: critical`,
225
+ },
226
+ '06': {
227
+ name: 'policy',
228
+ file: 'policy-gates.yml',
229
+ job: ` policy:
230
+ uses: ./.github/workflows/policy-gates.yml
231
+ with:
232
+ path: .`,
233
+ },
234
+ };
235
+
236
+ const agentPolicyWorkflow = (
237
+ ctx,
238
+ ) => `# Piece 02: fail the build if the policy file or guardrail settings are removed or weakened.
239
+ name: agent-policy
240
+
241
+ on:
242
+ workflow_call:
243
+
244
+ permissions:
245
+ contents: read
246
+
247
+ jobs:
248
+ check:
249
+ runs-on: ubuntu-latest
250
+ defaults:
251
+ run:
252
+ working-directory: rollcage
253
+ steps:
254
+ - uses: ${CHECKOUT}
255
+ with:
256
+ path: app
257
+ persist-credentials: false
258
+ - uses: ${CHECKOUT}
259
+ with:
260
+ repository: frankTurtle/rollcage
261
+ ref: ${pinned(ctx)}
262
+ path: rollcage
263
+ fetch-depth: 1
264
+ persist-credentials: false
265
+ - uses: ${PNPM}
266
+ with:
267
+ package_json_file: rollcage/package.json
268
+ - uses: ${NODE}
269
+ with:
270
+ node-version: 24
271
+ - run: pnpm install --frozen-lockfile --filter "@adl/agent-policy..."
272
+ - run: pnpm --filter @adl/agent-policy exec tsx src/bin.ts check --root "$GITHUB_WORKSPACE/app"
273
+ `;
274
+
275
+ const doraWorkflow = (
276
+ ctx,
277
+ ) => `# Piece 03: weekly delivery metrics, split at the date AI tools were rolled out.
278
+ name: dora-weekly
279
+
280
+ on:
281
+ schedule:
282
+ - cron: '0 6 * * 1'
283
+ workflow_dispatch:
284
+
285
+ permissions:
286
+ contents: read
287
+ actions: read
288
+ deployments: read
289
+ issues: read
290
+ pull-requests: read
291
+
292
+ jobs:
293
+ dora:
294
+ runs-on: ubuntu-latest
295
+ steps:
296
+ - uses: ${CHECKOUT}
297
+ with:
298
+ persist-credentials: false
299
+ ${ctx.detected.usesPnpm ? ` - uses: ${PNPM}\n` : ''} - uses: frankTurtle/rollcage/pieces/03-dora-metrics@${pinned(ctx)}
300
+ with:
301
+ compare-at: '${ctx.date}' # SET THIS: the day your team rolled out AI tools
302
+ `;
303
+
304
+ const provenanceWorkflow = (
305
+ ctx,
306
+ ) => `# Piece 10: attest a release artifact, then verify it the way a deploy would.
307
+ # Manual only: attestation writes a public Sigstore entry that names this repository, so it never
308
+ # runs on push or pull_request. EDIT the build step and artifact name for your project, then run it
309
+ # from the Actions tab. Only this job holds id-token and attestations write.
310
+ name: provenance
311
+
312
+ on:
313
+ workflow_dispatch:
314
+
315
+ permissions:
316
+ contents: read
317
+
318
+ jobs:
319
+ provenance:
320
+ runs-on: ubuntu-latest
321
+ permissions:
322
+ contents: read
323
+ id-token: write
324
+ attestations: write
325
+ steps:
326
+ - uses: ${CHECKOUT}
327
+ with:
328
+ persist-credentials: false
329
+ # TODO: build your release here, then pack it into ONE file (the gate verifies one file).
330
+ - run: tar -czf release.tgz --exclude=.git --exclude=release.tgz .
331
+ - uses: frankTurtle/rollcage/pieces/10-provenance-signing@${pinned(ctx)}
332
+ with:
333
+ artifact: release.tgz
334
+ mode: attest
335
+ # What a deploy job would run: block unless this workflow signed this exact file.
336
+ - uses: frankTurtle/rollcage/pieces/10-provenance-signing@${pinned(ctx)}
337
+ with:
338
+ artifact: release.tgz
339
+ mode: verify
340
+ signer-workflow: ${ctx.owner}/${ctx.repo}/.github/workflows/provenance.yml
341
+ `;
342
+
343
+ /** Jobs for the pieces that no existing workflow already calls (so a repo that has a ci.yml
344
+ * calling them is not run twice). */
345
+ const callerJobs = (ctx) =>
346
+ ctx.pieces
347
+ .map((p) => ROLLCAGE_WORKFLOW_JOBS[p])
348
+ .filter((j) => j && !ctx.detected.calledWorkflows.includes(j.file));
349
+
350
+ const callerWorkflow = (ctx) => {
351
+ const jobs = callerJobs(ctx)
352
+ .map((j) => j.job)
353
+ .join('\n\n');
354
+ return `# Rollcage: runs each enabled piece as a job. Your own build and test workflow stays separate.
355
+ # Each job calls a reusable workflow in this folder, which calls the piece at a pinned commit.
356
+ name: rollcage
357
+
358
+ on:
359
+ push:
360
+ branches: [main]
361
+ pull_request:
362
+
363
+ permissions:
364
+ contents: read
365
+
366
+ concurrency:
367
+ group: rollcage-\${{ github.ref }}
368
+ cancel-in-progress: true
369
+
370
+ jobs:
371
+ ${jobs}
372
+ `;
373
+ };
374
+
375
+ const branchProtection = (ctx) => {
376
+ const checks = ctx.pieces
377
+ .filter((p) => ROLLCAGE_WORKFLOW_JOBS[p])
378
+ .map((p) => ROLLCAGE_WORKFLOW_JOBS[p].name);
379
+ const bullets = checks.map((c) => `- \`${c}\``).join('\n');
380
+ return `# Branch protection
381
+
382
+ Rollcage's checks only bind once branch protection requires them. Until then a red check is advice.
383
+ Do this after the first pull request has run, so you can pick the exact check names.
384
+
385
+ Require these on \`main\` (Settings, Branches, or a ruleset):
386
+
387
+ - A pull request before merging, with review from Code Owners (\`.github/CODEOWNERS\`)
388
+ - These status checks, from \`.github/workflows/rollcage.yml\` (they show as \`<job> / <job>\`):
389
+
390
+ ${bullets}
391
+
392
+ - Dismiss stale approvals, no force pushes, no deletions
393
+
394
+ A single-maintainer repo cannot meet "one approving review" on its own pull requests. Add a second
395
+ reviewer or lower the count, and accept the weaker control.
396
+ `;
397
+ };
398
+
399
+ const preCommit = `# Install once: pip install pre-commit && pre-commit install --hook-type pre-commit --hook-type commit-msg
400
+ # Piece 04, layer 1: gitleaks blocks a commit that contains a secret, before the commit exists.
401
+ # gitleaks must be installed locally (brew install gitleaks). For the audited variant, see
402
+ # pieces/04-secrets-guard/templates/pre-commit-config.yaml in the rollcage repo.
403
+ repos:
404
+ - repo: local
405
+ hooks:
406
+ - id: gitleaks
407
+ name: gitleaks (staged changes)
408
+ entry: gitleaks git --pre-commit --staged --redact --verbose
409
+ language: system
410
+ pass_filenames: false
411
+ `;
412
+
413
+ const dependabot = `version: 2
414
+ updates:
415
+ # Keeps the commit SHAs in .github/workflows current, including the rollcage pins.
416
+ - package-ecosystem: github-actions
417
+ directory: /
418
+ schedule:
419
+ interval: weekly
420
+ `;
421
+
422
+ const riskGateConfig = `# Config for the PR risk gate (piece 01). Start in observe mode, tune, then switch to enforce.
423
+ # Every key is optional. See pieces/01-pr-risk-gate/risk-gate.example.yml in the rollcage repo.
424
+ mode: observe
425
+ `;
426
+
427
+ const doraConfig = `# Piece 03 config. Deployments are read from GitHub releases until you use the deployments API.
428
+ deployments:
429
+ source: releases
430
+ branch: main
431
+ incident_label: incident
432
+ hotfix_labels: [hotfix]
433
+ `;
434
+
435
+ // Placeholders in the piece 02 policy that have a sensible default; the rest are listed for a human.
436
+ const POLICY_FILL = (ctx) => ({
437
+ '<NAME OR TEAM>': ctx.owner,
438
+ '<DATE>': ctx.date,
439
+ '<N>': '6',
440
+ '<WEEKLY/MONTHLY>': 'weekly',
441
+ '<ROLE>': 'the repository owner',
442
+ '<LABEL>': 'ai-assisted',
443
+ '<LOCATION>': 'docs/policy-exceptions.md',
444
+ '<ALLOWED HOSTS>': 'see `.claude/agent-policy.yml`',
445
+ '<ALLOWED SCRATCH DIRECTORIES>': '`/tmp`',
446
+ '<PROTECTED PATHS>': 'see `.claude/agent-policy.yml`',
447
+ '<SECURITY CONTACT>': 'SECURITY.md',
448
+ });
449
+
450
+ const PROTECTED_PATHS = [
451
+ '.claude/settings.json',
452
+ '.claude/settings.local.json',
453
+ '.claude/agent-policy.yml',
454
+ '.claude/hooks/**',
455
+ 'policy/AI_CODING_AGENT_POLICY.md',
456
+ '.github/workflows/agent-policy.yml',
457
+ '.github/CODEOWNERS',
458
+ ];
459
+
460
+ /** String replace that fails loudly if the upstream template changed shape. */
461
+ function mustReplace(text, pattern, replacement) {
462
+ const out = text.replace(pattern, replacement);
463
+ if (out === text) throw new InitError(`template changed upstream: ${pattern} no longer matches`);
464
+ return out;
465
+ }
466
+
467
+ function agentPolicyConfig(ctx) {
468
+ const base = readSource(ctx, 'pieces/02-agent-policy/templates/agent-policy.yml');
469
+ // Replace the vendored-source entry in the template with this repo's real protected paths.
470
+ return mustReplace(
471
+ base,
472
+ /^(protected_paths:\n)(?:[ \t]+-.*\n?)+/m,
473
+ `$1${PROTECTED_PATHS.map((p) => ` - ${p}\n`).join('')}`,
474
+ );
475
+ }
476
+
477
+ function agentPolicyPolicy(ctx) {
478
+ const fill = POLICY_FILL(ctx);
479
+ let text = mustReplace(
480
+ readSource(ctx, 'pieces/02-agent-policy/policy/AI_CODING_AGENT_POLICY.md'),
481
+ 'Template. Replace every `<PLACEHOLDER>`. ',
482
+ '',
483
+ );
484
+ for (const [token, value] of Object.entries(fill)) text = text.replaceAll(token, value);
485
+ return text;
486
+ }
487
+
488
+ /** The files to write: `{ path, content }` for text, `{ path, hook: true }` for the built hook. */
489
+ function plan(ctx) {
490
+ const files = [];
491
+ const add = (path, content) => files.push({ path, content });
492
+ const wf = (name, content) => add(`.github/workflows/${name}`, content);
493
+ const on = (p) => ctx.pieces.includes(p);
494
+
495
+ if (on('01')) {
496
+ wf(
497
+ 'gate-pr-risk.yml',
498
+ dropPnpmSetup(ctx, template12(ctx, '.github/workflows/gate-pr-risk.yml')),
499
+ );
500
+ add('risk-gate.yml', riskGateConfig);
501
+ }
502
+ if (on('02')) {
503
+ wf('agent-policy.yml', agentPolicyWorkflow(ctx));
504
+ add('.claude/settings.json', readSource(ctx, 'pieces/02-agent-policy/templates/settings.json'));
505
+ add('.claude/agent-policy.yml', agentPolicyConfig(ctx));
506
+ add('policy/AI_CODING_AGENT_POLICY.md', agentPolicyPolicy(ctx));
507
+ add(
508
+ 'docs/policy-exceptions.md',
509
+ '# Policy exceptions\n\nRecord each exception: what, who approved it, and the end date.\n',
510
+ );
511
+ files.push({ path: '.claude/hooks/agent-policy-hook.mjs', hook: true });
512
+ }
513
+ if (on('03')) {
514
+ wf('dora-weekly.yml', doraWorkflow(ctx));
515
+ add('dora.yml', doraConfig);
516
+ }
517
+ if (on('04')) {
518
+ wf('secrets-scan.yml', template12(ctx, '.github/workflows/secrets-scan.yml'));
519
+ add('.pre-commit-config.yaml', preCommit);
520
+ }
521
+ if (on('05')) wf('sbom-vuln.yml', template12(ctx, '.github/workflows/sbom-vuln.yml'));
522
+ if (on('06')) wf('policy-gates.yml', template12(ctx, '.github/workflows/policy-gates.yml'));
523
+ if (on('10')) wf('provenance.yml', provenanceWorkflow(ctx));
524
+
525
+ if (callerJobs(ctx).length > 0) wf('rollcage.yml', callerWorkflow(ctx));
526
+ add('.github/CODEOWNERS', template12(ctx, '.github/CODEOWNERS'));
527
+ add('.github/pull_request_template.md', template12(ctx, '.github/pull_request_template.md'));
528
+ add('.github/dependabot.yml', dependabot);
529
+ add('SECURITY.md', template12(ctx, 'SECURITY.md'));
530
+ add('docs/branch-protection.md', branchProtection(ctx));
531
+ add(
532
+ '.rollcage.json',
533
+ `${JSON.stringify({ ref: ctx.ref, sha: ctx.sha, pieces: ctx.pieces, initialized: ctx.date }, null, 2)}\n`,
534
+ );
535
+ return files;
536
+ }
537
+
538
+ // ------------------------------------------------------------------ apply
539
+
540
+ function buildHook(ctx) {
541
+ const run = (cmd, args) =>
542
+ execFileSync(cmd, args, { cwd: ctx.source, stdio: 'ignore', env: { ...process.env, CI: '1' } });
543
+ run('pnpm', ['install', '--frozen-lockfile', '--filter', '@adl/agent-policy...']);
544
+ run('pnpm', ['--filter', '@adl/agent-policy', 'build']);
545
+ const out = join(ctx.source, 'pieces/02-agent-policy/dist/agent-policy-hook.mjs');
546
+ if (!existsSync(out)) throw new Error('build produced no hook');
547
+ return out;
548
+ }
549
+
550
+ /**
551
+ * Write the plan. Existing files are skipped, never overwritten. Returns what happened per path.
552
+ * With `dryRun` nothing is written and the hook is not built.
553
+ */
554
+ function apply(ctx, files, { dryRun = false, buildHooks = true } = {}) {
555
+ const results = [];
556
+ let hookBuild = null;
557
+ for (const file of files) {
558
+ const target = join(ctx.root, file.path);
559
+ if (existsSync(target)) {
560
+ results.push({ path: file.path, status: 'skipped', reason: 'already exists' });
561
+ continue;
562
+ }
563
+ if (file.hook) {
564
+ if (dryRun || !buildHooks) {
565
+ results.push({ path: file.path, status: dryRun ? 'would-write' : 'manual' });
566
+ continue;
567
+ }
568
+ try {
569
+ hookBuild ??= buildHook(ctx);
570
+ } catch {
571
+ results.push({ path: file.path, status: 'manual', reason: 'hook build failed' });
572
+ continue;
573
+ }
574
+ mkdirSync(dirname(target), { recursive: true });
575
+ copyFileSync(hookBuild, target);
576
+ results.push({ path: file.path, status: 'written' });
577
+ continue;
578
+ }
579
+ if (dryRun) {
580
+ results.push({ path: file.path, status: 'would-write' });
581
+ continue;
582
+ }
583
+ mkdirSync(dirname(target), { recursive: true });
584
+ writeFileSync(target, file.content, { flag: 'wx' });
585
+ results.push({ path: file.path, status: 'written' });
586
+ }
587
+ return results;
588
+ }
589
+
590
+ function nextSteps(ctx, results) {
591
+ const steps = [];
592
+ // Only tell people to configure files this run actually created.
593
+ const on = (p, file) =>
594
+ ctx.pieces.includes(p) && results.some((r) => r.path === file && r.status !== 'skipped');
595
+ const manualHook = results.find(
596
+ (r) => r.path.endsWith('agent-policy-hook.mjs') && r.status === 'manual',
597
+ );
598
+ if (manualHook) {
599
+ steps.push(
600
+ `Build the agent hook (needs pnpm and Node 24): in a clone of ${REPO_URL} at ${ctx.ref}, run ` +
601
+ '`pnpm install --frozen-lockfile --filter "@adl/agent-policy..." && pnpm --filter @adl/agent-policy build`, ' +
602
+ 'then copy `pieces/02-agent-policy/dist/agent-policy-hook.mjs` to `.claude/hooks/`.',
603
+ );
604
+ }
605
+ if (on('02', 'policy/AI_CODING_AGENT_POLICY.md')) {
606
+ steps.push(
607
+ 'Read `policy/AI_CODING_AGENT_POLICY.md`: defaults are filled in (owner, 6-month review, weekly log review). Change what your org needs and get it approved.',
608
+ 'Review `allowed_hosts` in `.claude/agent-policy.yml`. Keep every `protected_paths` entry.',
609
+ );
610
+ }
611
+ if (on('03', '.github/workflows/dora-weekly.yml'))
612
+ steps.push(
613
+ 'Set `compare-at` in `.github/workflows/dora-weekly.yml` to the day your team started using AI tools.',
614
+ );
615
+ if (on('04', '.pre-commit-config.yaml')) {
616
+ steps.push(
617
+ 'Install the commit hook: `pip install pre-commit && pre-commit install --hook-type pre-commit --hook-type commit-msg` (and `brew install gitleaks`).',
618
+ 'Organizations: add a `GITLEAKS_LICENSE` repository secret. Personal accounts need nothing.',
619
+ );
620
+ }
621
+ if (on('10', '.github/workflows/provenance.yml'))
622
+ steps.push(
623
+ 'Edit the build step in `.github/workflows/provenance.yml`; it runs by hand only and writes a public Sigstore entry.',
624
+ );
625
+ if (ctx.pieces.includes('06') && !ctx.detected.terraform) {
626
+ steps.push('Piece 06 found no Terraform here, so only the workflow-file rules apply.');
627
+ }
628
+ steps.push(
629
+ 'Review the diff, commit it on a branch, and open a pull request. The risk gate comments on it (observe mode).',
630
+ 'After that first PR has run, make the checks required: see `docs/branch-protection.md`.',
631
+ `To upgrade, rerun with a newer --ref on a clean branch, or bump the SHAs in .github/workflows (Dependabot proposes them).`,
632
+ );
633
+ return steps;
634
+ }
635
+
636
+ // -------------------------------------------------------------------- cli
637
+
638
+ const USAGE = `Usage: rollcage-init [options]
639
+
640
+ Set up Rollcage in the git repository in the current directory (or --dir).
641
+
642
+ --ref <ref> Rollcage tag, branch or commit to pin to (default ${DEFAULT_REF}). Resolved to a SHA.
643
+ --owner <login> GitHub owner for CODEOWNERS (default: from the origin remote).
644
+ --repo <name> GitHub repo name for the provenance signer (default: from the origin remote).
645
+ --pieces <list> Comma list of pieces to enable (default: ${DEFAULT_PIECES.join(',')}).
646
+ --without <list> Pieces to leave out of the default set.
647
+ --dir <path> Target repository (default: current directory).
648
+ --source <path> Use a local rollcage checkout instead of cloning (for testing).
649
+ --no-build Do not build the piece 02 hook; print how to build it instead.
650
+ --dry-run Print what would be written, change nothing.
651
+ --json Machine-readable output.
652
+ -h, --help This text.
653
+
654
+ Never overwrites an existing file. Exit codes: 0 ok, 1 failed, 2 usage error.`;
655
+
656
+ const OPTIONS = {
657
+ ref: { type: 'string' },
658
+ owner: { type: 'string' },
659
+ repo: { type: 'string' },
660
+ pieces: { type: 'string' },
661
+ without: { type: 'string' },
662
+ dir: { type: 'string' },
663
+ source: { type: 'string' },
664
+ 'no-build': { type: 'boolean' },
665
+ 'dry-run': { type: 'boolean' },
666
+ json: { type: 'boolean' },
667
+ help: { type: 'boolean', short: 'h' },
668
+ };
669
+
670
+ export function run(argv, io = { out: console.log, err: console.error }) {
671
+ let values;
672
+ try {
673
+ values = parseArgs({ args: argv, options: OPTIONS, strict: true }).values;
674
+ } catch (error) {
675
+ io.err(`${error.message}\n${USAGE}`);
676
+ return 2;
677
+ }
678
+ if (values.help) {
679
+ io.out(USAGE);
680
+ return 0;
681
+ }
682
+
683
+ let source;
684
+ try {
685
+ const root = resolve(values.dir ?? process.cwd());
686
+ if (!existsSync(join(root, '.git'))) {
687
+ throw new InitError(
688
+ `${root} is not the root of a git repository; run this from the repo root`,
689
+ );
690
+ }
691
+ const pieces = parsePieces(values.pieces, values.without);
692
+ const detected = detect(root);
693
+ const ref = values.ref ?? DEFAULT_REF;
694
+ const owner = values.owner ?? detected.remote?.owner;
695
+ const repo = values.repo ?? detected.remote?.repo ?? 'REPO';
696
+ if (!owner) throw new InitError('cannot tell the GitHub owner; pass --owner <login>');
697
+ if (!SAFE_OWNER.test(owner)) throw new InitError(`invalid --owner ${owner}`);
698
+ if (!SAFE_REPO.test(repo)) throw new InitError(`invalid --repo ${repo}`);
699
+
700
+ if (values.source) {
701
+ if (!SAFE_REF.test(ref)) throw new InitError(`invalid --ref ${ref}`);
702
+ source = {
703
+ dir: resolve(values.source),
704
+ sha: git(resolve(values.source), 'rev-parse', 'HEAD'),
705
+ };
706
+ } else {
707
+ source = fetchSource(ref);
708
+ }
709
+ const ctx = {
710
+ root,
711
+ source: source.dir,
712
+ ref,
713
+ sha: source.sha,
714
+ owner,
715
+ repo,
716
+ pieces,
717
+ detected,
718
+ date: new Date().toISOString().slice(0, 10),
719
+ };
720
+ const files = plan(ctx);
721
+ const results = apply(ctx, files, {
722
+ dryRun: values['dry-run'] === true,
723
+ buildHooks: values['no-build'] !== true,
724
+ });
725
+ const steps = nextSteps(ctx, results);
726
+
727
+ if (values.json) {
728
+ io.out(
729
+ JSON.stringify(
730
+ { ref, sha: ctx.sha, owner, repo, pieces, detected, results, steps },
731
+ null,
732
+ 2,
733
+ ),
734
+ );
735
+ return 0;
736
+ }
737
+ io.out(`Rollcage ${ref} (${ctx.sha.slice(0, 12)}) for ${owner}/${repo}`);
738
+ io.out(
739
+ `Detected: ${detected.languages.join(', ') || 'no known language'}; ` +
740
+ `${detected.ciWorkflows.length} existing workflow(s); terraform: ${detected.terraform ? 'yes' : 'no'}`,
741
+ );
742
+ io.out(`Pieces: ${pieces.map((p) => `${p} ${PIECE_NAMES[p]}`).join(', ')}`);
743
+ for (const r of results)
744
+ io.out(` ${r.status.padEnd(11)} ${r.path}${r.reason ? ` (${r.reason})` : ''}`);
745
+ io.out('\nNext steps:');
746
+ steps.forEach((s, i) => io.out(` ${i + 1}. ${s}`));
747
+ return 0;
748
+ } catch (error) {
749
+ if (error instanceof InitError) {
750
+ io.err(`rollcage-init: ${error.message}`);
751
+ return 1;
752
+ }
753
+ throw error;
754
+ } finally {
755
+ if (source?.temporary) rmSync(source.dir, { recursive: true, force: true });
756
+ }
757
+ }
758
+
759
+ // Run as a script, or piped to `node -` (no argv[1]); importing it for tests has no side effects.
760
+ const entry = process.argv[1];
761
+ if (
762
+ !entry ||
763
+ entry === '-' ||
764
+ realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))
765
+ ) {
766
+ process.exitCode = run(process.argv.slice(2));
767
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.