@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,230 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { globProblem } from './glob.js';
4
+ import { FactoryError } from './io.js';
5
+
6
+ export const MANIFEST_FILE = 'factory.yaml';
7
+ export const DEFAULT_BASELINES_DIR = 'factory/baselines';
8
+ export const DEFAULT_CLI = 'factory';
9
+
10
+ export type Tier = 'fast' | 'full';
11
+ export const TIERS: readonly Tier[] = ['fast', 'full'];
12
+
13
+ export interface Gate { id: string; run: string; tier: Tier }
14
+
15
+ interface RatchetBase { id: string; why: string; include: string[]; exclude: string[] }
16
+ /** Counts lines matching `pattern` in the selected files; one key, `total`. */
17
+ export interface PatternRatchet extends RatchetBase { kind: 'pattern'; pattern: string }
18
+ /** Counts selected files longer than `max_lines` lines; one key, `total`. */
19
+ export interface MaxLinesRatchet extends RatchetBase { kind: 'max_lines'; max_lines: number }
20
+ /**
21
+ * Runs `run`; its stdout is a JSON object of non-negative integer counts. `show`, when set, is a
22
+ * command printed on failure that lists the occurrences; `{keys}` in it becomes the keys that rose.
23
+ */
24
+ export interface RunRatchet { kind: 'run'; id: string; why: string; run: string; show?: string }
25
+ export type Ratchet = PatternRatchet | MaxLinesRatchet | RunRatchet;
26
+
27
+ export interface Manifest {
28
+ version: 1;
29
+ pack?: string;
30
+ /** How a person invokes this CLI here, used in messages ("bun run factory"). */
31
+ cli: string;
32
+ baselines_dir: string;
33
+ gates: Gate[];
34
+ ratchets: Ratchet[];
35
+ risk_zones: Record<string, string[]>;
36
+ /** Ratchets removed on purpose; `ratchet --against` accepts their absence. */
37
+ retired: RetiredRatchet[];
38
+ /** Reviewed room to raise a baseline; `ratchet --against` reads them from the target's manifest. */
39
+ allowances: Allowance[];
40
+ }
41
+
42
+ export interface RetiredRatchet { id: string; why: string }
43
+ /** Lets a later change raise one key of a ratchet's baseline by `by`; that change deletes it. */
44
+ export interface Allowance { ratchet: string; key: string; by: number; why: string }
45
+ /** The key a pattern or max_lines ratchet counts under, and an allowance's default. */
46
+ export const TOTAL_KEY = 'total';
47
+
48
+ /** Key sets, exported so a test can compare them with factory.schema.json. */
49
+ export const MANIFEST_KEYS = ['version', 'pack', 'cli', 'baselines_dir', 'gates', 'ratchets', 'retired', 'allowances', 'risk_zones'] as const;
50
+ export const RETIRED_KEYS = ['id', 'why'] as const;
51
+ export const ALLOWANCE_KEYS = ['ratchet', 'key', 'by', 'why'] as const;
52
+ export const GATE_KEYS = ['id', 'run', 'tier'] as const;
53
+ export const RATCHET_KEYS = ['id', 'why', 'pattern', 'max_lines', 'run', 'show', 'include', 'exclude'] as const;
54
+
55
+ const ID_RE = /^[a-z0-9][a-z0-9_-]*$/;
56
+
57
+ type Obj = Record<string, unknown>;
58
+ const isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);
59
+ const show = (v: unknown) => (v === null ? 'null' : Array.isArray(v) ? 'a list' : typeof v === 'object' ? 'a mapping' : JSON.stringify(v));
60
+
61
+ /**
62
+ * Validates a parsed manifest. Returns every problem found, each as
63
+ * "<path>: <what was expected>", so one run lists everything to fix.
64
+ */
65
+ export function validateManifest(raw: unknown): { manifest?: Manifest; errors: string[] } {
66
+ const errors: string[] = [];
67
+ const err = (path: string, msg: string) => { errors.push(`${path}: ${msg}`); };
68
+ if (!isObj(raw)) return { errors: [`(top level): expected a mapping with at least "version: 1", got ${show(raw)}`] };
69
+
70
+ const unknownKeys = (obj: Obj, keys: readonly string[], path: string) => {
71
+ for (const k of Object.keys(obj)) {
72
+ if (!keys.includes(k)) err(path ? `${path}.${k}` : k, `unknown key (allowed: ${keys.join(', ')})`);
73
+ }
74
+ };
75
+ const str = (obj: Obj, key: string, path: string, required: boolean): string | undefined => {
76
+ const v = obj[key];
77
+ if (v === undefined) { if (required) err(`${path}.${key}`, 'required, expected a non-empty string'); return undefined; }
78
+ if (typeof v !== 'string' || v.trim() === '') { err(`${path}.${key}`, `expected a non-empty string, got ${show(v)}`); return undefined; }
79
+ return v;
80
+ };
81
+ const globs = (obj: Obj, key: string, path: string, required: boolean): string[] => {
82
+ const v = obj[key];
83
+ if (v === undefined) { if (required) err(`${path}.${key}`, 'required, expected a list of glob patterns'); return []; }
84
+ if (!Array.isArray(v) || (required && v.length === 0)) { err(`${path}.${key}`, `expected a non-empty list of glob patterns, got ${show(v)}`); return []; }
85
+ const out: string[] = [];
86
+ v.forEach((g, i) => {
87
+ if (typeof g !== 'string') { err(`${path}.${key}[${i}]`, `expected a glob string, got ${show(g)}`); return; }
88
+ const problem = globProblem(g);
89
+ if (problem) err(`${path}.${key}[${i}]`, `glob "${g}" ${problem}`);
90
+ else out.push(g);
91
+ });
92
+ return out;
93
+ };
94
+ const ids = new Set<string>();
95
+ const id = (obj: Obj, path: string, what: string): string | undefined => {
96
+ const v = str(obj, 'id', path, true);
97
+ if (v === undefined) return undefined;
98
+ if (!ID_RE.test(v)) { err(`${path}.id`, `"${v}" is not a valid id (lowercase letters, digits, "-" and "_", starting with a letter or digit)`); return undefined; }
99
+ if (ids.has(`${what}:${v}`)) err(`${path}.id`, `duplicate ${what} id "${v}"`);
100
+ ids.add(`${what}:${v}`);
101
+ return v;
102
+ };
103
+
104
+ unknownKeys(raw, MANIFEST_KEYS, '');
105
+ if (raw.version !== 1) err('version', `expected 1, got ${show(raw.version)}`);
106
+ const pack = str(raw, 'pack', '(top level)', false);
107
+ const cli = str(raw, 'cli', '(top level)', false) ?? DEFAULT_CLI;
108
+ const baselinesDir = str(raw, 'baselines_dir', '(top level)', false) ?? DEFAULT_BASELINES_DIR;
109
+ if (globProblem(baselinesDir) || /[*?[{]/.test(baselinesDir)) err('baselines_dir', `expected a plain relative directory path, got ${JSON.stringify(baselinesDir)}`);
110
+
111
+ const gates: Gate[] = [];
112
+ if (raw.gates !== undefined && !Array.isArray(raw.gates)) err('gates', `expected a list of gates, got ${show(raw.gates)}`);
113
+ (Array.isArray(raw.gates) ? raw.gates : []).forEach((g, i) => {
114
+ const path = `gates[${i}]`;
115
+ if (!isObj(g)) { err(path, `expected a mapping with id, run and tier, got ${show(g)}`); return; }
116
+ unknownKeys(g, GATE_KEYS, path);
117
+ const gid = id(g, path, 'gate');
118
+ const run = str(g, 'run', path, true);
119
+ const tier = g.tier;
120
+ if (tier === undefined) err(`${path}.tier`, `required, expected one of ${TIERS.join(' | ')}`);
121
+ else if (!TIERS.includes(tier as Tier)) err(`${path}.tier`, `expected one of ${TIERS.join(' | ')}, got ${show(tier)}`);
122
+ if (gid && run && TIERS.includes(tier as Tier)) gates.push({ id: gid, run, tier: tier as Tier });
123
+ });
124
+
125
+ const ratchets: Ratchet[] = [];
126
+ if (raw.ratchets !== undefined && !Array.isArray(raw.ratchets)) err('ratchets', `expected a list of ratchets, got ${show(raw.ratchets)}`);
127
+ (Array.isArray(raw.ratchets) ? raw.ratchets : []).forEach((r, i) => {
128
+ const path = `ratchets[${i}]`;
129
+ if (!isObj(r)) { err(path, `expected a mapping, got ${show(r)}`); return; }
130
+ unknownKeys(r, RATCHET_KEYS, path);
131
+ const rid = id(r, path, 'ratchet');
132
+ const why = str(r, 'why', path, true);
133
+ const kinds = (['pattern', 'max_lines', 'run'] as const).filter((k) => r[k] !== undefined);
134
+ const kind = kinds[0];
135
+ if (kinds.length !== 1 || kind === undefined) {
136
+ err(path, `expected exactly one counter: pattern (regex), max_lines (number) or run (command); got ${kinds.length ? kinds.join(' and ') : 'none'}`);
137
+ return;
138
+ }
139
+ if (kind === 'run') {
140
+ const run = str(r, 'run', path, true);
141
+ const showCmd = str(r, 'show', path, false);
142
+ for (const k of ['include', 'exclude']) if (r[k] !== undefined) err(`${path}.${k}`, 'not used by a run ratchet: the command chooses its own files');
143
+ if (rid && why && run) ratchets.push({ kind, id: rid, why, run, ...(showCmd !== undefined && { show: showCmd }) });
144
+ return;
145
+ }
146
+ if (r.show !== undefined) err(`${path}.show`, `only a run ratchet takes show; a ${kind} ratchet lists its occurrences itself`);
147
+ const include = globs(r, 'include', path, true);
148
+ const exclude = globs(r, 'exclude', path, false);
149
+ if (kind === 'pattern') {
150
+ const pattern = str(r, 'pattern', path, true);
151
+ if (pattern !== undefined) {
152
+ try { new RegExp(pattern); } catch (e) { err(`${path}.pattern`, `not a valid regular expression: ${(e as Error).message}`); return; }
153
+ }
154
+ if (rid && why && pattern !== undefined && include.length) ratchets.push({ kind, id: rid, why, pattern, include, exclude });
155
+ } else {
156
+ const max = r.max_lines;
157
+ if (typeof max !== 'number' || !Number.isInteger(max) || max < 1) { err(`${path}.max_lines`, `expected a positive integer, got ${show(max)}`); return; }
158
+ if (rid && why && include.length) ratchets.push({ kind, id: rid, why, max_lines: max, include, exclude });
159
+ }
160
+ });
161
+
162
+ const retired: RetiredRatchet[] = [];
163
+ if (raw.retired !== undefined && !Array.isArray(raw.retired)) err('retired', `expected a list of {id, why}, got ${show(raw.retired)}`);
164
+ (Array.isArray(raw.retired) ? raw.retired : []).forEach((r, i) => {
165
+ const path = `retired[${i}]`;
166
+ if (!isObj(r)) { err(path, `expected a mapping with id and why, got ${show(r)}`); return; }
167
+ unknownKeys(r, RETIRED_KEYS, path);
168
+ const rid = id(r, path, 'retired ratchet');
169
+ const why = str(r, 'why', path, true);
170
+ if (rid && ratchets.some((x) => x.id === rid)) err(`${path}.id`, `"${rid}" is both a ratchet and retired; remove it from one of the two lists`);
171
+ if (rid && why) retired.push({ id: rid, why });
172
+ });
173
+
174
+ const allowances: Allowance[] = [];
175
+ if (raw.allowances !== undefined && !Array.isArray(raw.allowances)) err('allowances', `expected a list of {ratchet, key, by, why}, got ${show(raw.allowances)}`);
176
+ (Array.isArray(raw.allowances) ? raw.allowances : []).forEach((a, i) => {
177
+ const path = `allowances[${i}]`;
178
+ if (!isObj(a)) { err(path, `expected a mapping with ratchet, by and why, got ${show(a)}`); return; }
179
+ unknownKeys(a, ALLOWANCE_KEYS, path);
180
+ const ratchet = str(a, 'ratchet', path, true);
181
+ const known = ratchet !== undefined && ids.has(`ratchet:${ratchet}`);
182
+ if (ratchet !== undefined && !known) err(`${path}.ratchet`, `"${ratchet}" is not a ratchet in ratchets`);
183
+ const key = str(a, 'key', path, false) ?? TOTAL_KEY;
184
+ const kind = ratchets.find((x) => x.id === ratchet)?.kind;
185
+ if (kind !== undefined && kind !== 'run' && key !== TOTAL_KEY) err(`${path}.key`, `a ${kind} ratchet has the single key "${TOTAL_KEY}", got ${JSON.stringify(key)}`);
186
+ const by = a.by;
187
+ const byOk = typeof by === 'number' && Number.isInteger(by) && by >= 1;
188
+ if (by === undefined) err(`${path}.by`, 'required, expected a positive integer');
189
+ else if (!byOk) err(`${path}.by`, `expected a positive integer, got ${show(by)}`);
190
+ const why = str(a, 'why', path, true);
191
+ if (known && byOk && why) allowances.push({ ratchet, key, by, why });
192
+ });
193
+
194
+ const zones: Record<string, string[]> = {};
195
+ if (raw.risk_zones !== undefined && !isObj(raw.risk_zones)) err('risk_zones', `expected a mapping of zone name to glob list, got ${show(raw.risk_zones)}`);
196
+ if (isObj(raw.risk_zones)) {
197
+ for (const name of Object.keys(raw.risk_zones)) {
198
+ if (!ID_RE.test(name)) err(`risk_zones.${name}`, 'is not a valid zone name (lowercase letters, digits, "-" and "_")');
199
+ zones[name] = globs(raw.risk_zones, name, 'risk_zones', true);
200
+ }
201
+ }
202
+
203
+ if (errors.length) return { errors };
204
+ return {
205
+ errors,
206
+ manifest: { version: 1, ...(pack !== undefined && { pack }), cli, baselines_dir: baselinesDir, gates, ratchets, risk_zones: zones, retired, allowances },
207
+ };
208
+ }
209
+
210
+ export function parseYaml(text: string, source: string): unknown {
211
+ try {
212
+ return Bun.YAML.parse(text);
213
+ } catch (e) {
214
+ throw new FactoryError(`${source} is not valid YAML: ${(e as Error).message}`);
215
+ }
216
+ }
217
+
218
+ export function parseManifest(text: string, source: string): Manifest {
219
+ const { manifest, errors } = validateManifest(parseYaml(text, source));
220
+ if (!manifest) {
221
+ throw new FactoryError(`${source} is not a valid factory manifest:\n${errors.map((e) => ` - ${e}`).join('\n')}\n(the format is factory.schema.json, next to the factory CLI)`);
222
+ }
223
+ return manifest;
224
+ }
225
+
226
+ export function loadManifest(root: string): Manifest {
227
+ const path = join(root, MANIFEST_FILE);
228
+ if (!existsSync(path)) throw new FactoryError(`no ${MANIFEST_FILE} at the repository root (${root})`);
229
+ return parseManifest(readFileSync(path, 'utf8'), MANIFEST_FILE);
230
+ }