@kainappsinc/factory 0.0.0-stage → 0.1.0

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 CHANGED
@@ -1,3 +1,318 @@
1
- # Temporary Holding Version
1
+ # @kainappsinc/factory
2
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.
3
+ Mechanical gates that make a repository safe for agents (and people) to change at volume: every
4
+ change passes the same checks, debt counts can only go down, and changes to sensitive paths are
5
+ flagged for a person. A repository declares all of it in `factory.yaml` at its root; this package
6
+ runs it.
7
+
8
+ What is in the package:
9
+
10
+ - **The `factory` CLI**: `check` (run the gates), `ratchet` (counts that may only go down),
11
+ `risk` (which risk zones a change touches), `validate`. Bun built-ins only.
12
+ - **The ts-bun pack**: the ESLint and dependency-cruiser counters a `run` ratchet calls
13
+ (`factory-eslint-counts`, `factory-depcruise-counts`) and the TypeScript 7 shim
14
+ (`classic-typescript`).
15
+ - **Shared ESLint rules and config** (`@kainappsinc/factory/eslint`, `…/eslint/config`): rules each
16
+ repository would otherwise copy, with configurable messages, and the flat-config boilerplate.
17
+ - **dependency-cruiser rule shapes** (`@kainappsinc/factory/depcruise`): layer ordering, no test
18
+ imports in production, no value-import cycles.
19
+ - **The manifest's JSON schema** (`@kainappsinc/factory/schema.json`), for editors.
20
+
21
+ It ships TypeScript source and runs on **Bun** (1.3 or later); there is no build step.
22
+
23
+ ## Adopting it
24
+
25
+ 1. Add the dependency and a script. The counters use the repository's own ESLint,
26
+ dependency-cruiser and TypeScript (optional peer dependencies), so install the ones your
27
+ ratchets and lint config use:
28
+
29
+ ```sh
30
+ bun add -d @kainappsinc/factory eslint @eslint/js typescript-eslint \
31
+ @eslint-community/eslint-plugin-eslint-comments dependency-cruiser
32
+ ```
33
+
34
+ ```json
35
+ "scripts": { "factory": "factory", "lint": "bun --bun eslint" }
36
+ ```
37
+
38
+ If the repository's `typescript` is 7.0 (no JavaScript compiler API), also add the classic
39
+ compiler under an alias for typescript-eslint and dependency-cruiser:
40
+ `"typescript-classic": "npm:typescript@~6.0.3"` (see "TypeScript 7" below). With TypeScript 6
41
+ or earlier it is not needed.
42
+
43
+ 2. Write `factory.yaml` at the root (format: `schema.json`; for editor completion add
44
+ `# yaml-language-server: $schema=node_modules/@kainappsinc/factory/src/cli/factory.schema.json`):
45
+
46
+ ```yaml
47
+ version: 1
48
+ pack: ts-bun
49
+ cli: bun run factory # how people run it here; used in messages
50
+ gates:
51
+ - { id: ratchet, run: bun run factory ratchet, tier: fast }
52
+ - { id: typecheck, run: bun run typecheck, tier: fast }
53
+ - { id: test, run: bun test, tier: full }
54
+ ratchets:
55
+ - id: eslint
56
+ why: "Lint findings may only go down: fix the code the rule flags."
57
+ run: bun run factory-eslint-counts
58
+ show: bun run factory-eslint-counts --show {keys}
59
+ - id: boundaries
60
+ why: "An import crosses a module boundary; --show gives each rule's fix."
61
+ run: bun run factory-depcruise-counts src
62
+ show: bun run factory-depcruise-counts --show {keys} src
63
+ - id: long-files
64
+ why: "Files over 1000 lines are hard to review; split them."
65
+ max_lines: 1000
66
+ include: ["src/**/*.ts"]
67
+ exclude: ["**/__tests__/**"]
68
+ risk_zones:
69
+ factory: [factory.yaml, eslint.config.js, .dependency-cruiser.cjs, .gitlab-ci.yml]
70
+ ```
71
+
72
+ Then seed the baselines: `bun run factory ratchet --update --allow-increase`, and commit
73
+ `factory/baselines/`.
74
+
75
+ 3. `eslint.config.js` (runs on Bun only, since it imports TypeScript):
76
+
77
+ ```js
78
+ import { defineConfig, globalIgnores } from 'eslint/config';
79
+ import { baseConfig, testConfig } from '@kainappsinc/factory/eslint/config';
80
+ import factory from '@kainappsinc/factory/eslint';
81
+
82
+ const TESTS = ['**/__tests__/**', '**/*.test.ts'];
83
+
84
+ export default defineConfig([
85
+ globalIgnores(['dist/', '**/node_modules/']),
86
+ await baseConfig({
87
+ files: ['src/**/*.ts'],
88
+ plugins: { factory },
89
+ rules: {
90
+ 'factory/import-suffix': ['error', { suffix: 'js' }],
91
+ 'factory/no-json-parse-cast': 'error',
92
+ 'factory/no-untracked-todo': 'error',
93
+ },
94
+ }),
95
+ testConfig({ files: TESTS, rules: { 'factory/no-json-parse-cast': 'off' } }),
96
+ ]);
97
+ ```
98
+
99
+ To keep existing rule ids (and so the `eslint` ratchet's keys), register the shared rules under
100
+ the repository's own plugin instead, next to its own rules:
101
+ `plugins: { myrepo: { meta: { name: 'myrepo' }, rules: { ...ownRules, 'import-js-suffix': importSuffix, 'no-untracked-todo': noUntrackedTodo } } }`
102
+ (`import { importSuffix, noUntrackedTodo } from '@kainappsinc/factory/eslint'`).
103
+
104
+ 4. `.dependency-cruiser.cjs`, if the repository has one, can build its rules from the shared
105
+ shapes (below).
106
+
107
+ 5. CI (GitLab): the `kainapps/ci-templates` components run the ratchet and risk jobs with the
108
+ repository's `bun run factory`:
109
+
110
+ ```yaml
111
+ include:
112
+ - component: $CI_SERVER_FQDN/kainapps/ci-templates/factory-gates@1.2.1
113
+ inputs: { stage: check, install: bun install --frozen-lockfile }
114
+ - component: $CI_SERVER_FQDN/kainapps/ci-templates/factory-risk@1.2.1
115
+ inputs: { stage: check, install: bun install --frozen-lockfile }
116
+ ```
117
+
118
+ `factory:ratchet` runs `ratchet --against origin/<target branch>` on a branch and plain
119
+ `ratchet` on the default branch; `factory:risk` runs `risk --base origin/<target branch>` and
120
+ writes `factory-risk.json` and `FACTORY_RISK_ZONES`. Both need the installed package (the CLI
121
+ lives in `node_modules`), so neither may set `install: ""`.
122
+
123
+ ## Commands
124
+
125
+ ```sh
126
+ factory check [--tier fast|full] [--only id,...] [--json evidence.json]
127
+ factory ratchet [--update [--allow-increase]] [--against <git-ref>] [--only <id>]
128
+ factory risk --base origin/main [--head <ref>] [--json] [--fail-on-risk]
129
+ factory validate
130
+ ```
131
+
132
+ - `check` runs the gates in order and keeps going after a failure; `--tier fast` runs only the
133
+ fast gates (the inner loop), the full tier runs all.
134
+ - `ratchet` counts each ratchet and compares it with `<baselines_dir>/<id>.json`
135
+ (default `factory/baselines`).
136
+ - `risk` lists the files a change touches by risk zone. Zones come from `factory.yaml` at the base
137
+ ref, so a change cannot remove itself from a zone. Without `--head` it includes uncommitted and
138
+ untracked files.
139
+ - `validate` checks the manifest and notes globs that match no file.
140
+
141
+ Exit codes: 0 ok, 1 a gate or ratchet failed, 2 usage or manifest error, 3 risk (`--fail-on-risk`).
142
+
143
+ ### When a ratchet fails
144
+
145
+ - **Over** (`FAIL as-any: 6 -> 7 (+1)`): an occurrence was added. The message says why the rule
146
+ exists and lists the matches, changed files first. Fix the code; do not raise the baseline.
147
+ - **Stale** (`6 -> 5 (-1): ... the baseline is stale`): one was removed. Run
148
+ `ratchet --update` and commit the baseline, so the slack cannot be spent again.
149
+ - **Raised against the target**: a branch may not raise its own baseline, even if the count
150
+ matches. Restore the file from the target and bring the count down, or get an allowance first.
151
+ - **Removed ratchet**: put it back, or retire it on purpose under `retired:` (`id`, `why`).
152
+
153
+ Under `--against`, the target branch's definitions and baselines judge the change: a ratchet
154
+ whose regex or globs changed is also counted with the target's definition (`CHANGED`).
155
+ `--update` only ever lowers baselines; `--allow-increase` (raise or create) seeds a new ratchet,
156
+ or raises a baseline that an allowance covers.
157
+
158
+ ### Raising a baseline (allowances)
159
+
160
+ A merge request cannot raise its own baseline, so the permission comes from the target branch, in
161
+ two steps:
162
+
163
+ 1. A merge request that only adds an allowance to `factory.yaml` (it changes no count; keep
164
+ `factory.yaml` in a risk zone so a person reviews it):
165
+
166
+ ```yaml
167
+ allowances:
168
+ - ratchet: eslint # a ratchet id
169
+ key: (suppressed) # optional; default total (pattern and max_lines ratchets have only total)
170
+ by: 1 # how much the baseline may rise
171
+ why: "src/x.ts must read process.env before config loads; see #123"
172
+ ```
173
+
174
+ 2. After it is merged, the change that adds the occurrence runs
175
+ `ratchet --update --allow-increase --only <id>` and deletes the allowance in the same merge
176
+ request. `ratchet --against` prints `ALLOWED <id>: …` for the rise.
177
+
178
+ A rise of n on a key passes only if the target's allowances for that ratchet and key add up to at
179
+ least n, and the branch holds at most (that sum − n) for the key: a used allowance must be deleted
180
+ (or lowered by what was used), so it cannot be spent twice.
181
+
182
+ ### Adding a ratchet
183
+
184
+ 1. Add an entry under `ratchets:` with an `id`, a one-line `why` (printed on every failure) and
185
+ one counter:
186
+ - `pattern`: a JavaScript regex; the count is matching lines in `include` minus `exclude`.
187
+ - `max_lines: N`: the count is files in `include` minus `exclude` longer than N lines.
188
+ - `run`: a command printing `{"key": count, ...}`. Optional `show`: a command printed on
189
+ failure that lists the occurrences; `{keys}` in it becomes the keys that rose.
190
+ 2. Run `factory ratchet --only <id>`: with no baseline yet it lists every match. Tighten the regex
191
+ until there are no false positives.
192
+ 3. Seed it: `factory ratchet --update --allow-increase --only <id>`; commit the baseline.
193
+
194
+ Globs: `*` stays inside a path segment, `**` spans any number of segments (including none), `?`,
195
+ `[abc]` and `{a,b}` work, dotfiles are not special, no `!` (use `exclude`). Paths come from
196
+ `git ls-files` (tracked plus untracked, minus ignored), so `.gitignore` is honoured.
197
+
198
+ ## The ts-bun counters
199
+
200
+ ```sh
201
+ factory-eslint-counts [--cwd <dir>] [--config <file>] [--show <keys>] [<pattern>...]
202
+ factory-depcruise-counts [--config <file>] [--show <rules>] [<path>...]
203
+ ```
204
+
205
+ - `factory-eslint-counts` prints every enabled rule with its count, 0 included (so a rule's first
206
+ violation is a rise on a known key), plus `(parse-error)`, `(unused-directive)` and
207
+ `(suppressed)`: an inline `eslint-disable` still counts. It uses the ESLint installed for
208
+ `--cwd`.
209
+ - `factory-depcruise-counts` prints every `forbidden` rule of `.dependency-cruiser.cjs` (or
210
+ `--config`) with its violation count, 0 included, plus `(unresolved)`: imports that resolve to
211
+ no file, so a broken alias cannot hide edges.
212
+ - `--show` prints the occurrences of the given keys (the ratchet's `show:` command).
213
+
214
+ Both exit 1 when the tool fails (bad config, no files), so a broken counter never reads as zero.
215
+ From a `factory.yaml`, call them as `bun run factory-eslint-counts …` (package bins are on the
216
+ path only through `bun run`).
217
+
218
+ ## ESLint rules
219
+
220
+ `@kainappsinc/factory/eslint` exports the plugin (default; rules under the `factory/` prefix when
221
+ registered as `factory`), the `rules` record, and each rule. Every rule takes a `messages` option
222
+ (message id → text, `{{name}}` placeholders filled from the report) so a repository can name its
223
+ own replacement.
224
+
225
+ | Rule | Flags | Options |
226
+ |---|---|---|
227
+ | `import-suffix` | relative imports without the convention's suffix (`missing`), or with the other one (`wrong`) | `suffix`: `'js'` (default: `./x.js` names `x.ts`; `.js`, `.mjs`, `.cjs`, `.json` allowed) or `'ts'` (the source by its own name; `.ts`, `.tsx`, `.mjs`, `.cjs`, `.json` allowed); `messages: { missing, wrong }` (`{{spec}}` available) |
228
+ | `no-json-parse-cast` | `JSON.parse(s) as T`, `<T>JSON.parse(s)`, `const x: T = JSON.parse(s)` (`unknown` and `as const` pass) | `messages: { cast }` |
229
+ | `no-raw-request-json` | `req.json()`, `request.json()`, `ctx.req.json()`: a request body read without a bound or validation | `requestNames` (default `['req', 'request']`); `messages: { raw }` |
230
+ | `no-untracked-todo` | `TODO`/`FIXME`/`HACK`/`XXX` comments without `#123`, `group/repo#123` or a URL | `messages: { untracked }` (`{{marker}}` available) |
231
+
232
+ Example: `'factory/no-raw-request-json': ['error', { messages: { raw: 'Use parseBody(req, schema) from src/http.ts, which validates and answers 400.' } }]`.
233
+
234
+ `@kainappsinc/factory/eslint/config` has `baseConfig({ files, plugins, rules })` (eslint,
235
+ typescript-eslint and eslint-comments recommended, unused disable directives as errors,
236
+ `BASE_RULES`), `testConfig({ files, plugins, rules })` (`TEST_RULES`: `any`, `require`,
237
+ generators without `yield` and directives without a reason allowed) and `loadTypeScriptEslint()`.
238
+ Not type-aware: typed linting costs gigabytes of memory under Bun.
239
+
240
+ For rule authors: `@kainappsinc/factory/eslint/ast` (defensive AST accessors that see the
241
+ TypeScript nodes too) and `@kainappsinc/factory/eslint/tester` (a TypeScript-parsing `RuleTester`
242
+ wired to `bun:test`; needs `@typescript-eslint/parser`).
243
+
244
+ ## dependency-cruiser rule shapes
245
+
246
+ ```js
247
+ const { layerRules, noTestImportsInProduction, noValueCycles, TYPE_EDGES } = require('@kainappsinc/factory/depcruise');
248
+ const TESTS = '(^|/)__tests__/|\\.test\\.ts$';
249
+ const LAYERS = [ // lowest first
250
+ { name: 'infra', path: '^src/infra/', fix: 'move the shared piece down, or inject it' },
251
+ { name: 'domain', path: '^src/domain/', fix: 'depend on an interface and inject it' },
252
+ { name: 'app', path: '^src/main\\.ts$', fix: '' },
253
+ ];
254
+ module.exports = {
255
+ forbidden: [
256
+ ...layerRules(LAYERS, { tests: TESTS }),
257
+ noTestImportsInProduction({ from: '^src/', tests: TESTS }),
258
+ noValueCycles({ from: '^src/', tests: TESTS }),
259
+ ],
260
+ options: { tsPreCompilationDeps: true, tsConfig: { fileName: 'tsconfig.json' } },
261
+ };
262
+ ```
263
+
264
+ - `layerRules(layers, { tests, typeImportsUpTo, doc })`: one rule `layer-<name>` per layer: no
265
+ import into a higher layer (or into the layer's own `to` paths). With
266
+ `typeImportsUpTo: '<layer>'`, `import type` may reach upward into the layers below that one.
267
+ `doc` (default `factory/BOUNDARIES.md`) is named in the comment.
268
+ - `noTestImportsInProduction({ from, tests, describe })` and `noValueCycles({ from, tests })`.
269
+
270
+ The module is plain CommonJS, so the `depcruise` CLI can load the config under Node too.
271
+
272
+ ## TypeScript 7
273
+
274
+ TypeScript 7.0's npm package has no JavaScript compiler API. typescript-eslint and
275
+ dependency-cruiser need one, so when the installed `typescript` lacks it, the counters, the ESLint
276
+ config helper and the rule tester load the classic compiler from the `typescript-classic` alias
277
+ for their own process (`@kainappsinc/factory/ts-bun/classic-typescript`; `tsc` keeps running 7.x).
278
+ Under Bun a runtime plugin covers `require('typescript')` and `import 'typescript'`; not covered:
279
+ `typescript/lib/tsserverlibrary` (type-aware linting). With TypeScript 6 or earlier installed,
280
+ nothing is replaced and the alias is not needed.
281
+
282
+ ## Developing
283
+
284
+ ```sh
285
+ bun install
286
+ bun test # never as root: some tests rely on file modes
287
+ bun run typecheck
288
+ bun run lint
289
+ bun run factory check # this package gates itself (factory.yaml)
290
+ ```
291
+
292
+ ## Releasing
293
+
294
+ 1. Bump `version` in `package.json` in a merge request; merge it.
295
+ 2. Tag the merge commit `vX.Y.Z` (the same version) and push the tag. The `publish` job checks
296
+ that the tag matches `package.json` and that the version is not on npm yet, then publishes.
297
+
298
+ The job authenticates one of two ways:
299
+
300
+ - **`NPM_TOKEN`** (works today): a CI/CD variable, masked and protected, holding a granular npm
301
+ access token with read and write access to `@kainappsinc/factory`. Protect the `v*` tags
302
+ (Settings → Repository → Protected tags) so the protected variable reaches the tag pipeline.
303
+ No provenance is published on this path.
304
+ - **Trusted publishing (OIDC)**, used when `NPM_TOKEN` is unset: npm exchanges the job's
305
+ `NPM_ID_TOKEN` (audience `npm:registry.npmjs.org`) for a short-lived publish credential and
306
+ publishes provenance. npm documents this for GitLab.com shared runners only ("Self-hosted
307
+ runners are not currently supported"), so the `publish` job is tagged for a GitLab.com hosted
308
+ runner and shared runners are enabled on this project. To use it: on npmjs.com, package settings
309
+ → Trusted publisher → GitLab CI/CD, namespace `kainapps`, project `factory`, top-level CI file
310
+ `.gitlab-ci.yml`, allow `npm publish`; publish once within two days
311
+ (an unused configuration expires); then delete `NPM_TOKEN` and set Publishing access to "Require
312
+ two-factor authentication and disallow tokens".
313
+
314
+ **The first publish** cannot use trusted publishing: a trusted publisher is configured in the
315
+ settings of a package that already exists. Publish 0.1.0 once by hand from a clean checkout of the
316
+ `v0.1.0` tag, logged in as an owner of the `@kainappsinc` scope (`npm login`, then
317
+ `npm publish --access public`, with the one-time password), or set `NPM_TOKEN` to a granular token
318
+ allowed to publish in the scope and push the tag. Later releases go through the `publish` job.
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "@kainappsinc/factory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Software factory kit: a gate runner, debt ratchets that only go down, risk zones, shared ESLint rules and the ts-bun stack pack. Runs on Bun.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://gitlab.com/kainapps/factory.git"
10
+ },
11
+ "homepage": "https://gitlab.com/kainapps/factory#readme",
12
+ "bugs": "https://gitlab.com/kainapps/factory/-/issues",
13
+ "keywords": ["ratchet", "quality-gates", "eslint", "dependency-cruiser", "bun", "ci"],
14
+ "engines": {
15
+ "bun": ">=1.3.0"
16
+ },
17
+ "bin": {
18
+ "factory": "./src/cli/index.ts",
19
+ "factory-eslint-counts": "./src/packs/ts-bun/eslint-counts.ts",
20
+ "factory-depcruise-counts": "./src/packs/ts-bun/depcruise-counts.ts"
21
+ },
22
+ "exports": {
23
+ "./cli": "./src/cli/main.ts",
24
+ "./schema.json": "./src/cli/factory.schema.json",
25
+ "./ts-bun/classic-typescript": "./src/packs/ts-bun/classic-typescript.ts",
26
+ "./ts-bun/counter-cli": "./src/packs/ts-bun/counter-cli.ts",
27
+ "./ts-bun/eslint-counts": "./src/packs/ts-bun/eslint-counts.ts",
28
+ "./ts-bun/depcruise-counts": "./src/packs/ts-bun/depcruise-counts.ts",
29
+ "./eslint": "./src/eslint/index.ts",
30
+ "./eslint/config": "./src/eslint/config.ts",
31
+ "./eslint/ast": "./src/eslint/ast.ts",
32
+ "./eslint/tester": "./src/eslint/tester.ts",
33
+ "./depcruise": {
34
+ "types": "./src/depcruise/index.d.cts",
35
+ "default": "./src/depcruise/index.cjs"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "src/",
41
+ "!src/**/__tests__/",
42
+ "README.md"
43
+ ],
44
+ "scripts": {
45
+ "factory": "bun src/cli/index.ts",
46
+ "typecheck": "tsc --noEmit",
47
+ "lint": "bun --bun eslint",
48
+ "test": "bun test"
49
+ },
50
+ "peerDependencies": {
51
+ "@eslint-community/eslint-plugin-eslint-comments": "^4.8.1",
52
+ "@eslint/js": "^9.39.5",
53
+ "@typescript-eslint/parser": "^8.73.0",
54
+ "dependency-cruiser": "^18.8.0",
55
+ "eslint": "^9.39.5",
56
+ "typescript": ">=5.0.0",
57
+ "typescript-eslint": "^8.73.0"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "@eslint-community/eslint-plugin-eslint-comments": { "optional": true },
61
+ "@eslint/js": { "optional": true },
62
+ "@typescript-eslint/parser": { "optional": true },
63
+ "dependency-cruiser": { "optional": true },
64
+ "eslint": { "optional": true },
65
+ "typescript": { "optional": true },
66
+ "typescript-eslint": { "optional": true }
67
+ },
68
+ "devDependencies": {
69
+ "@eslint-community/eslint-plugin-eslint-comments": "^4.8.1",
70
+ "@eslint/js": "^9.39.5",
71
+ "@types/bun": "^1.3.11",
72
+ "@typescript-eslint/parser": "^8.73.0",
73
+ "dependency-cruiser": "^18.8.0",
74
+ "eslint": "^9.39.5",
75
+ "typescript": "7.0.2",
76
+ "typescript-classic": "npm:typescript@~6.0.3",
77
+ "typescript-eslint": "^8.73.0"
78
+ }
79
+ }
@@ -0,0 +1,48 @@
1
+ import { FactoryError } from './io.js';
2
+
3
+ export type FlagSpec = Record<string, 'string' | 'boolean'>;
4
+ export type Flags = Record<string, string | boolean | undefined>;
5
+
6
+ /**
7
+ * Parses `--name value`, `--name=value` and boolean `--name`. Unknown flags and
8
+ * positional arguments are usage errors: a typo must not silently change what runs.
9
+ */
10
+ export function parseFlags(command: string, argv: readonly string[], spec: FlagSpec): Flags {
11
+ const flags: Flags = {};
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const arg = argv[i] ?? '';
14
+ if (!arg.startsWith('--')) {
15
+ throw new FactoryError(`factory ${command}: unexpected argument "${arg}" (flags start with --; see factory help)`);
16
+ }
17
+ const eq = arg.indexOf('=');
18
+ const name = arg.slice(2, eq === -1 ? undefined : eq);
19
+ const kind = spec[name];
20
+ if (!kind) {
21
+ const known = Object.keys(spec).map((k) => `--${k}`).join(', ') || 'none';
22
+ throw new FactoryError(`factory ${command}: unknown flag --${name} (known: ${known})`);
23
+ }
24
+ if (kind === 'boolean') {
25
+ if (eq !== -1) throw new FactoryError(`factory ${command}: --${name} takes no value`);
26
+ flags[name] = true;
27
+ continue;
28
+ }
29
+ // `--name=value`, or `--name value` (which consumes the next argument)
30
+ const value = eq !== -1 ? arg.slice(eq + 1) : argv[++i];
31
+ if (value === undefined || value === '' || value.startsWith('--')) {
32
+ throw new FactoryError(`factory ${command}: --${name} needs a value`);
33
+ }
34
+ flags[name] = value;
35
+ }
36
+ return flags;
37
+ }
38
+
39
+ export function stringFlag(flags: Flags, name: string): string | undefined {
40
+ const v = flags[name];
41
+ return typeof v === 'string' ? v : undefined;
42
+ }
43
+
44
+ /** `a,b , c` -> ['a','b','c'] */
45
+ export function listFlag(flags: Flags, name: string): string[] | undefined {
46
+ const v = stringFlag(flags, name);
47
+ return v === undefined ? undefined : v.split(',').map((s) => s.trim()).filter(Boolean);
48
+ }
@@ -0,0 +1,57 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ export type Counts = Record<string, number>;
5
+ export interface Baseline { id: string; counts: Counts }
6
+
7
+ /** A count is a non-negative integer. */
8
+ export function isCount(v: unknown): v is number {
9
+ return typeof v === 'number' && Number.isInteger(v) && v >= 0;
10
+ }
11
+
12
+ export function baselinePath(baselinesDir: string, id: string): string {
13
+ return `${baselinesDir}/${id}.json`;
14
+ }
15
+
16
+ /** Stable text: two-space JSON, keys sorted, trailing newline. */
17
+ export function formatBaseline(id: string, counts: Counts): string {
18
+ const sorted: Counts = {};
19
+ for (const k of Object.keys(counts).sort()) sorted[k] = counts[k] ?? 0;
20
+ return `${JSON.stringify({ id, counts: sorted }, null, 2)}\n`;
21
+ }
22
+
23
+ /** Parses baseline text; returns an error string instead of throwing. */
24
+ export function parseBaseline(text: string, id: string, source: string): Baseline | string {
25
+ let raw: unknown;
26
+ try { raw = JSON.parse(text); } catch (e) { return `${source} is not valid JSON: ${(e as Error).message}`; }
27
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return `${source}: expected {"id": "${id}", "counts": {...}}`;
28
+ const obj = raw as Record<string, unknown>;
29
+ if (obj.id !== id) return `${source}: "id" is ${JSON.stringify(obj.id)}, expected "${id}" (the file name and the id must agree)`;
30
+ const counts = obj.counts;
31
+ if (typeof counts !== 'object' || counts === null || Array.isArray(counts)) return `${source}: "counts" must be an object of key -> count`;
32
+ const out: Counts = {};
33
+ for (const [k, v] of Object.entries(counts)) {
34
+ if (!isCount(v)) return `${source}: counts.${k} must be a non-negative integer, got ${JSON.stringify(v)}`;
35
+ out[k] = v;
36
+ }
37
+ return { id, counts: out };
38
+ }
39
+
40
+ export function readBaseline(root: string, baselinesDir: string, id: string): Baseline | string | null {
41
+ const rel = baselinePath(baselinesDir, id);
42
+ const abs = join(root, rel);
43
+ if (!existsSync(abs)) return null;
44
+ return parseBaseline(readFileSync(abs, 'utf8'), id, rel);
45
+ }
46
+
47
+ export function writeBaseline(root: string, baselinesDir: string, id: string, counts: Counts): void {
48
+ mkdirSync(join(root, baselinesDir), { recursive: true });
49
+ writeFileSync(join(root, baselinePath(baselinesDir, id)), formatBaseline(id, counts));
50
+ }
51
+
52
+ /** Ids of baseline files present on disk. */
53
+ export function baselineIds(root: string, baselinesDir: string): string[] {
54
+ const dir = join(root, baselinesDir);
55
+ if (!existsSync(dir)) return [];
56
+ return readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)).sort();
57
+ }
@@ -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
+ }