@kainappsinc/factory 0.0.0-stage → 0.1.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.
@@ -0,0 +1,104 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { headSha } from './git.js';
4
+ import { EXIT_FAIL, EXIT_OK, FactoryError, type Io, table } from './io.js';
5
+ import { type Gate, MANIFEST_FILE, type Manifest, type Tier } from './manifest.js';
6
+
7
+ export interface CheckOptions {
8
+ tier?: Tier;
9
+ only?: string[];
10
+ /** Evidence file path, resolved against `cwd`. */
11
+ json?: string;
12
+ cwd?: string;
13
+ }
14
+
15
+ export interface GateEvidence { id: string; command: string; tier: Tier; exit_code: number; duration_ms: number }
16
+ export interface Evidence {
17
+ manifest_version: number;
18
+ head: string | null;
19
+ tier: Tier;
20
+ only: string[] | null;
21
+ started_at: string;
22
+ finished_at: string;
23
+ result: 'pass' | 'fail';
24
+ gates: GateEvidence[];
25
+ }
26
+
27
+ export function selectGates(manifest: Manifest, tier: Tier, only?: readonly string[]): Gate[] {
28
+ const inTier = manifest.gates.filter((g) => tier === 'full' || g.tier === 'fast');
29
+ if (!only) return inTier;
30
+ const all = new Map(manifest.gates.map((g) => [g.id, g]));
31
+ for (const id of only) {
32
+ const g = all.get(id);
33
+ if (!g) throw new FactoryError(`no gate "${id}" in ${MANIFEST_FILE} (gates: ${manifest.gates.map((x) => x.id).join(', ') || 'none'})`);
34
+ if (!inTier.includes(g)) throw new FactoryError(`gate "${id}" is tier ${g.tier}, so --tier ${tier} leaves it out; drop --tier or pick another gate`);
35
+ }
36
+ return inTier.filter((g) => only.includes(g.id));
37
+ }
38
+
39
+ async function pump(stream: ReadableStream<Uint8Array>, write: (s: string) => void): Promise<void> {
40
+ const decoder = new TextDecoder();
41
+ for await (const chunk of stream) write(decoder.decode(chunk, { stream: true }));
42
+ const rest = decoder.decode();
43
+ if (rest) write(rest);
44
+ }
45
+
46
+ async function runGate(root: string, gate: Gate, io: Io): Promise<number> {
47
+ if (io.inherit) {
48
+ const proc = Bun.spawn(['sh', '-c', gate.run], { cwd: root, stdin: 'inherit', stdout: 'inherit', stderr: 'inherit' });
49
+ return await proc.exited;
50
+ }
51
+ const proc = Bun.spawn(['sh', '-c', gate.run], { cwd: root, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
52
+ await Promise.all([pump(proc.stdout, (s) => io.out(s)), pump(proc.stderr, (s) => io.err(s))]);
53
+ return await proc.exited;
54
+ }
55
+
56
+ /**
57
+ * `factory check`: runs the selected gates in manifest order, streams their
58
+ * output, keeps going after a failure, prints a summary, exits 1 if any failed.
59
+ */
60
+ export async function runCheck(root: string, manifest: Manifest, opts: CheckOptions, io: Io): Promise<number> {
61
+ const tier = opts.tier ?? 'full';
62
+ const gates = selectGates(manifest, tier, opts.only);
63
+ if (!gates.length) throw new FactoryError(`no gates to run (tier ${tier}${opts.only ? `, --only ${opts.only.join(',')}` : ''})`);
64
+ const started = new Date();
65
+ const results: GateEvidence[] = [];
66
+ for (const [i, gate] of gates.entries()) {
67
+ io.out(`\n==> [${i + 1}/${gates.length}] ${gate.id}: ${gate.run}\n`);
68
+ const t0 = performance.now();
69
+ let code: number;
70
+ try { code = await runGate(root, gate, io); } catch (e) {
71
+ io.err(`could not start gate ${gate.id}: ${(e as Error).message}\n`);
72
+ code = 127;
73
+ }
74
+ const ms = Math.round(performance.now() - t0);
75
+ results.push({ id: gate.id, command: gate.run, tier: gate.tier, exit_code: code, duration_ms: ms });
76
+ io.out(`<== ${gate.id}: ${code === 0 ? 'pass' : `FAIL (exit ${code})`} in ${(ms / 1000).toFixed(1)} s\n`);
77
+ }
78
+ const failed = results.filter((r) => r.exit_code !== 0);
79
+ io.out(`\n${table([
80
+ ['gate', 'result', 'seconds'],
81
+ ...results.map((r) => [r.id, r.exit_code === 0 ? 'pass' : 'FAIL', (r.duration_ms / 1000).toFixed(1)]),
82
+ ])}`);
83
+ io.out(failed.length
84
+ ? `${failed.length} of ${results.length} gates failed: ${failed.map((r) => r.id).join(', ')}. Rerun one with --only <id>.\n`
85
+ : `All ${results.length} gates passed.\n`);
86
+
87
+ if (opts.json) {
88
+ const evidence: Evidence = {
89
+ manifest_version: manifest.version,
90
+ head: headSha(root),
91
+ tier,
92
+ only: opts.only ?? null,
93
+ started_at: started.toISOString(),
94
+ finished_at: new Date().toISOString(),
95
+ result: failed.length ? 'fail' : 'pass',
96
+ gates: results,
97
+ };
98
+ const path = resolve(opts.cwd ?? root, opts.json);
99
+ mkdirSync(dirname(path), { recursive: true });
100
+ writeFileSync(path, `${JSON.stringify(evidence, null, 2)}\n`);
101
+ io.out(`Evidence written to ${path}\n`);
102
+ }
103
+ return failed.length ? EXIT_FAIL : EXIT_OK;
104
+ }
@@ -0,0 +1,96 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "factory.schema.json",
4
+ "title": "factory.yaml",
5
+ "description": "Software factory manifest: gates that must pass, counts that may only go down, and paths that need human review. Validated by the factory CLI (manifest.ts); this schema is for editors.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": ["version"],
9
+ "properties": {
10
+ "version": { "const": 1, "description": "Manifest format version." },
11
+ "pack": { "type": "string", "minLength": 1, "description": "Stack pack name (for example ts-bun). Informational for now." },
12
+ "cli": { "type": "string", "minLength": 1, "default": "factory", "description": "How a person runs the CLI in this repository, used in messages (for example \"bun run factory\")." },
13
+ "baselines_dir": { "type": "string", "minLength": 1, "default": "factory/baselines", "description": "Directory of <ratchet-id>.json baseline files, relative to the repository root." },
14
+ "gates": {
15
+ "type": "array",
16
+ "description": "Ordered shell commands that must exit 0.",
17
+ "items": {
18
+ "type": "object",
19
+ "additionalProperties": false,
20
+ "required": ["id", "run", "tier"],
21
+ "properties": {
22
+ "id": { "$ref": "#/$defs/id" },
23
+ "run": { "type": "string", "minLength": 1, "description": "Shell command, run with sh -c at the repository root." },
24
+ "tier": { "enum": ["fast", "full"], "description": "fast gates run in `check --tier fast`; every gate runs in the full tier." }
25
+ }
26
+ }
27
+ },
28
+ "ratchets": {
29
+ "type": "array",
30
+ "description": "Counts that may only go down. Exactly one of pattern, max_lines or run.",
31
+ "items": {
32
+ "type": "object",
33
+ "additionalProperties": false,
34
+ "required": ["id", "why"],
35
+ "properties": {
36
+ "id": { "$ref": "#/$defs/id" },
37
+ "why": { "type": "string", "minLength": 1, "description": "One line: why this is counted and what to do instead. Printed on every failure." },
38
+ "pattern": { "type": "string", "minLength": 1, "description": "JavaScript regular expression; the count is the number of matching lines in the selected files (key: total)." },
39
+ "max_lines": { "type": "integer", "minimum": 1, "description": "The count is the number of selected files with more lines than this (key: total)." },
40
+ "run": { "type": "string", "minLength": 1, "description": "Shell command printing one JSON object {\"key\": count} on stdout." },
41
+ "show": { "type": "string", "minLength": 1, "description": "Run ratchets only: a command printed on failure that lists the occurrences (file:line); {keys} becomes the comma-separated keys that rose." },
42
+ "include": { "$ref": "#/$defs/globs" },
43
+ "exclude": { "type": "array", "items": { "type": "string", "minLength": 1 }, "description": "Globs removed from include." }
44
+ },
45
+ "oneOf": [
46
+ { "required": ["pattern", "include"], "not": { "anyOf": [{ "required": ["max_lines"] }, { "required": ["run"] }, { "required": ["show"] }] } },
47
+ { "required": ["max_lines", "include"], "not": { "anyOf": [{ "required": ["pattern"] }, { "required": ["run"] }, { "required": ["show"] }] } },
48
+ { "required": ["run"], "not": { "anyOf": [{ "required": ["pattern"] }, { "required": ["max_lines"] }, { "required": ["include"] }, { "required": ["exclude"] }] } }
49
+ ]
50
+ }
51
+ },
52
+ "retired": {
53
+ "type": "array",
54
+ "description": "Ratchets removed on purpose. `ratchet --against` fails when a ratchet at the target is missing here, unless its id is listed. An id may not also be in ratchets.",
55
+ "items": {
56
+ "type": "object",
57
+ "additionalProperties": false,
58
+ "required": ["id", "why"],
59
+ "properties": {
60
+ "id": { "$ref": "#/$defs/id" },
61
+ "why": { "type": "string", "minLength": 1, "description": "Why the ratchet was retired (printed by ratchet --against)." }
62
+ }
63
+ }
64
+ },
65
+ "allowances": {
66
+ "type": "array",
67
+ "description": "Reviewed room to raise one ratchet key's baseline. Add one in its own merge request (a person reviews it); it has no effect there. A later change may then raise that key's baseline by up to `by` and must delete the allowance in the same change. `ratchet --against` reads allowances from the target branch only.",
68
+ "items": {
69
+ "type": "object",
70
+ "additionalProperties": false,
71
+ "required": ["ratchet", "by", "why"],
72
+ "properties": {
73
+ "ratchet": { "$ref": "#/$defs/id", "description": "Id of a ratchet in ratchets." },
74
+ "key": { "type": "string", "minLength": 1, "default": "total", "description": "The count's key. Pattern and max_lines ratchets have the single key total; a run ratchet's keys are what its command prints (for example (suppressed))." },
75
+ "by": { "type": "integer", "minimum": 1, "description": "How much the baseline for this key may rise." },
76
+ "why": { "type": "string", "minLength": 1, "description": "Why the new occurrences are justified (printed when the allowance is used)." }
77
+ }
78
+ }
79
+ },
80
+ "risk_zones": {
81
+ "type": "object",
82
+ "description": "Zone name -> globs. A change touching a zone needs human review. Read from the base ref, never the working copy.",
83
+ "propertyNames": { "$ref": "#/$defs/id" },
84
+ "additionalProperties": { "$ref": "#/$defs/globs" }
85
+ }
86
+ },
87
+ "$defs": {
88
+ "id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]*$" },
89
+ "globs": {
90
+ "type": "array",
91
+ "minItems": 1,
92
+ "description": "Globs against repository-relative paths: * within a segment, ** any segments, ?, [abc], {a,b}. No leading !, ./ or /.",
93
+ "items": { "type": "string", "minLength": 1 }
94
+ }
95
+ }
96
+ }
package/src/cli/git.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { FactoryError } from './io.js';
2
+
3
+ export interface GitResult { code: number; stdout: string; stderr: string }
4
+
5
+ export function git(root: string, args: readonly string[]): GitResult {
6
+ const proc = Bun.spawnSync(['git', ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe' });
7
+ return { code: proc.exitCode ?? 1, stdout: proc.stdout.toString(), stderr: proc.stderr.toString() };
8
+ }
9
+
10
+ /** Splits `-z` output into paths. */
11
+ function splitNul(s: string): string[] {
12
+ return s.split('\0').filter(Boolean);
13
+ }
14
+
15
+ function gitOrThrow(root: string, args: readonly string[], what: string): string {
16
+ const r = git(root, args);
17
+ if (r.code !== 0) throw new FactoryError(`${what} failed: git ${args.join(' ')}: ${r.stderr.trim() || `exit ${r.code}`}`);
18
+ return r.stdout;
19
+ }
20
+
21
+ /** The repository root containing `cwd`. */
22
+ export function repoRoot(cwd: string): string {
23
+ const r = git(cwd, ['rev-parse', '--show-toplevel']);
24
+ if (r.code !== 0) throw new FactoryError(`factory must run inside a git repository (${cwd} is not in one)`);
25
+ return r.stdout.trim();
26
+ }
27
+
28
+ /**
29
+ * Files the repository knows about: tracked plus untracked-but-not-ignored, minus
30
+ * tracked files deleted in the working tree. Honours .gitignore and never walks
31
+ * node_modules, because git does the listing.
32
+ */
33
+ export function listFiles(root: string): string[] {
34
+ const all = splitNul(gitOrThrow(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], 'listing files'));
35
+ const deleted = new Set(splitNul(gitOrThrow(root, ['ls-files', '-z', '--deleted'], 'listing deleted files')));
36
+ return [...new Set(all)].filter((f) => !deleted.has(f)).sort();
37
+ }
38
+
39
+ /** Resolves a ref to a commit sha, or throws a readable error naming the ref. */
40
+ export function resolveCommit(root: string, ref: string): string {
41
+ const r = git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
42
+ if (r.code !== 0) {
43
+ throw new FactoryError(`git ref "${ref}" does not resolve to a commit here (in CI, fetch it first: git fetch origin <branch>)`);
44
+ }
45
+ return r.stdout.trim();
46
+ }
47
+
48
+ /** HEAD's sha, or null in a repository with no commits. */
49
+ export function headSha(root: string): string | null {
50
+ const r = git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']);
51
+ return r.code === 0 ? r.stdout.trim() : null;
52
+ }
53
+
54
+ /** A file's content at a commit, or null when the file does not exist there. */
55
+ export function showFile(root: string, commit: string, path: string): string | null {
56
+ const r = git(root, ['show', `${commit}:${path}`]);
57
+ return r.code === 0 ? r.stdout : null;
58
+ }
59
+
60
+ export function mergeBase(root: string, a: string, b: string): string {
61
+ return gitOrThrow(root, ['merge-base', a, b], `finding the merge base of ${a} and ${b}`).trim();
62
+ }
63
+
64
+ /**
65
+ * Paths changed since `from`: to the commit `to`, or to the working tree (tracked
66
+ * changes plus untracked files) when `to` is undefined. Renames count as a delete
67
+ * plus an add, so moving a file out of a zone still lists the old path.
68
+ */
69
+ export function changedFiles(root: string, from: string, to?: string): string[] {
70
+ const diff = splitNul(gitOrThrow(root, ['diff', '-z', '--name-only', '--no-renames', from, ...(to ? [to] : [])], 'listing changed files'));
71
+ const untracked = to ? [] : splitNul(gitOrThrow(root, ['ls-files', '-z', '--others', '--exclude-standard'], 'listing untracked files'));
72
+ return [...new Set([...diff, ...untracked])].sort();
73
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Glob semantics (one set, used by ratchet include/exclude and risk zones).
3
+ *
4
+ * A pattern is matched against a repository-relative path with forward slashes,
5
+ * as `git ls-files` prints it (no leading `./`, no trailing `/`).
6
+ * * any run of characters inside one path segment (never crosses `/`)
7
+ * ** any number of whole segments, including none: `a/**\/b` matches `a/b`
8
+ * ? one character inside a segment
9
+ * [abc] one character from the set
10
+ * {a,b} either alternative: `**\/*.{ts,tsx}`
11
+ * Dotfiles are not special: `*.yml` matches `.gitlab-ci.yml`.
12
+ * A path is selected when it matches at least one `include` pattern and no
13
+ * `exclude` pattern. There is no `!` negation inside a list: use `exclude`.
14
+ * Matching is done by Bun.Glob; this module only fixes the rules above.
15
+ */
16
+
17
+ export interface FileFilter {
18
+ include: readonly string[];
19
+ exclude?: readonly string[];
20
+ }
21
+
22
+ /** Why a pattern is not allowed, or null when it is. */
23
+ export function globProblem(pattern: string): string | null {
24
+ if (pattern === '') return 'is empty';
25
+ if (pattern.startsWith('!')) return 'starts with "!": negation is not supported, list the pattern under exclude';
26
+ if (pattern.startsWith('/')) return 'is absolute: patterns are relative to the repository root';
27
+ if (pattern.startsWith('./')) return 'starts with "./": write the path without it';
28
+ if (pattern.endsWith('/')) return 'ends with "/": to match a directory\'s contents write dir/**';
29
+ if (pattern.includes('\\')) return 'contains a backslash: use forward slashes';
30
+ return null;
31
+ }
32
+
33
+ export function compileGlobs(patterns: readonly string[]): (path: string) => boolean {
34
+ const globs = patterns.map((p) => new Bun.Glob(p));
35
+ return (path) => globs.some((g) => g.match(path));
36
+ }
37
+
38
+ export function compileFilter(filter: FileFilter): (path: string) => boolean {
39
+ const inc = compileGlobs(filter.include);
40
+ const exc = compileGlobs(filter.exclude ?? []);
41
+ return (path) => inc(path) && !exc(path);
42
+ }
43
+
44
+ export function selectFiles(files: readonly string[], filter: FileFilter): string[] {
45
+ return files.filter(compileFilter(filter));
46
+ }
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env bun
2
+ // The factory CLI (`factory <check|ratchet|risk|validate> ...`, the package bin).
3
+ // Generic: everything project-specific lives in the repository's factory.yaml.
4
+ import { processIo } from './io.js';
5
+ import { main } from './main.js';
6
+
7
+ process.exitCode = await main(process.argv.slice(2), process.cwd(), processIo);
package/src/cli/io.ts ADDED
@@ -0,0 +1,46 @@
1
+ /** Where a command writes. The real CLI writes to the process; tests capture. */
2
+ export interface Io {
3
+ out(text: string): void;
4
+ err(text: string): void;
5
+ /** True when child processes may inherit the terminal directly (keeps colours and TTY detection). */
6
+ inherit?: boolean;
7
+ }
8
+
9
+ export const processIo: Io = {
10
+ out: (text) => { process.stdout.write(text); },
11
+ err: (text) => { process.stderr.write(text); },
12
+ inherit: true,
13
+ };
14
+
15
+ /** An Io that records everything, for tests. */
16
+ export function memoryIo(): Io & { stdout: () => string; stderr: () => string } {
17
+ let out = '';
18
+ let err = '';
19
+ return {
20
+ out: (t) => { out += t; },
21
+ err: (t) => { err += t; },
22
+ stdout: () => out,
23
+ stderr: () => err,
24
+ };
25
+ }
26
+
27
+ /** Left-aligned text table; the last column is not padded. */
28
+ export function table(rows: readonly (readonly string[])[]): string {
29
+ const widths: number[] = [];
30
+ for (const row of rows) row.forEach((cell, i) => { widths[i] = Math.max(widths[i] ?? 0, cell.length); });
31
+ return rows
32
+ .map((row) => row.map((cell, i) => (i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0))).join(' '))
33
+ .join('\n') + '\n';
34
+ }
35
+
36
+ export const EXIT_OK = 0;
37
+ export const EXIT_FAIL = 1;
38
+ export const EXIT_USAGE = 2;
39
+ export const EXIT_RISK = 3;
40
+
41
+ /** A user-facing error: printed as-is, no stack, exits with `code`. */
42
+ export class FactoryError extends Error {
43
+ constructor(message: string, readonly code: number = EXIT_USAGE) {
44
+ super(message);
45
+ }
46
+ }
@@ -0,0 +1,99 @@
1
+ import { listFlag, parseFlags, stringFlag } from './args.js';
2
+ import { runCheck } from './check.js';
3
+ import { listFiles, repoRoot } from './git.js';
4
+ import { compileGlobs } from './glob.js';
5
+ import { EXIT_OK, EXIT_USAGE, FactoryError, type Io } from './io.js';
6
+ import { loadManifest, type Manifest, TIERS, type Tier } from './manifest.js';
7
+ import { runRatchet } from './ratchet.js';
8
+ import { runRisk } from './risk.js';
9
+
10
+ export const USAGE = `factory: mechanical gates for a repository, driven by factory.yaml at its root.
11
+
12
+ Commands:
13
+ check [--tier fast|full] [--only <id>,...] [--json <path>]
14
+ Run the gates in order (default tier full: all of them). Keeps going after
15
+ a failure; exits 1 if any failed. --json writes an evidence file.
16
+ ratchet [--update [--allow-increase]] [--against <git-ref>] [--only <id>]
17
+ Counts that may only go down. Fails when a count is above its baseline
18
+ (new debt) or below it (stale baseline). --update lowers baselines;
19
+ raising or creating one needs --allow-increase. --against fails when a
20
+ baseline here is higher than at the ref (an MR cannot raise its own).
21
+ risk --base <git-ref> [--head <ref>] [--json] [--fail-on-risk]
22
+ Files changed since merge-base(base, head), grouped by the risk zones in
23
+ factory.yaml AT THE BASE. Without --head: the working tree. Exit 0, or 3
24
+ with --fail-on-risk when a zone is touched.
25
+ validate
26
+ Check factory.yaml, print what it declares and any glob matching no file.
27
+
28
+ Exit codes: 0 ok, 1 a gate or ratchet failed, 2 usage or manifest error, 3 risk (--fail-on-risk).
29
+ `;
30
+
31
+ /** Include and risk-zone globs that match no file today: usually a typo or a moved file. */
32
+ export function deadGlobs(m: Manifest, files: readonly string[]): string[] {
33
+ const dead: string[] = [];
34
+ const check = (path: string, globs: readonly string[]) => globs.forEach((g, i) => {
35
+ if (!files.some(compileGlobs([g]))) dead.push(`${path}[${i}]: "${g}" matches no file`);
36
+ });
37
+ for (const r of m.ratchets) if (r.kind !== 'run') check(`ratchets.${r.id}.include`, r.include);
38
+ for (const [name, globs] of Object.entries(m.risk_zones)) check(`risk_zones.${name}`, globs);
39
+ return dead;
40
+ }
41
+
42
+ export async function main(argv: readonly string[], cwd: string, io: Io): Promise<number> {
43
+ const [command, ...rest] = argv;
44
+ try {
45
+ if (command === undefined || command === 'help' || command === '--help' || command === '-h') {
46
+ io.out(USAGE);
47
+ return command === undefined ? EXIT_USAGE : EXIT_OK;
48
+ }
49
+ const root = repoRoot(cwd);
50
+ switch (command) {
51
+ case 'check': {
52
+ const flags = parseFlags(command, rest, { tier: 'string', only: 'string', json: 'string' });
53
+ const tier = stringFlag(flags, 'tier');
54
+ if (tier !== undefined && !TIERS.includes(tier as Tier)) throw new FactoryError(`factory check: --tier must be ${TIERS.join(' or ')}, got "${tier}"`);
55
+ const only = listFlag(flags, 'only');
56
+ const json = stringFlag(flags, 'json');
57
+ return await runCheck(root, loadManifest(root), {
58
+ ...(tier !== undefined && { tier: tier as Tier }), ...(only && { only }), ...(json && { json }), cwd,
59
+ }, io);
60
+ }
61
+ case 'ratchet': {
62
+ const flags = parseFlags(command, rest, { update: 'boolean', 'allow-increase': 'boolean', against: 'string', only: 'string' });
63
+ const against = stringFlag(flags, 'against');
64
+ const only = stringFlag(flags, 'only');
65
+ return runRatchet(root, loadManifest(root), {
66
+ update: flags.update === true,
67
+ allowIncrease: flags['allow-increase'] === true,
68
+ ...(against !== undefined && { against }),
69
+ ...(only !== undefined && { only }),
70
+ }, io);
71
+ }
72
+ case 'risk': {
73
+ const flags = parseFlags(command, rest, { base: 'string', head: 'string', json: 'boolean', 'fail-on-risk': 'boolean' });
74
+ const base = stringFlag(flags, 'base');
75
+ if (!base) throw new FactoryError('factory risk: --base <git-ref> is required (the branch the change merges into)');
76
+ const head = stringFlag(flags, 'head');
77
+ return runRisk(root, {
78
+ base, ...(head !== undefined && { head }), json: flags.json === true, failOnRisk: flags['fail-on-risk'] === true,
79
+ }, io);
80
+ }
81
+ case 'validate': {
82
+ parseFlags(command, rest, {});
83
+ const m = loadManifest(root);
84
+ io.out(`factory.yaml is valid: version ${m.version}${m.pack ? `, pack ${m.pack}` : ''}; `
85
+ + `${m.gates.length} gates, ${m.ratchets.length} ratchets, ${Object.keys(m.risk_zones).length} risk zones.\n`);
86
+ for (const d of deadGlobs(m, listFiles(root))) io.out(`NOTE ${d}\n`);
87
+ return EXIT_OK;
88
+ }
89
+ default:
90
+ throw new FactoryError(`unknown command "${command}"\n\n${USAGE}`);
91
+ }
92
+ } catch (e) {
93
+ if (e instanceof FactoryError) {
94
+ io.err(`factory: ${e.message}\n`);
95
+ return e.code;
96
+ }
97
+ throw e;
98
+ }
99
+ }