@sabaiway/agent-workflow-kit 14.38.0 → 14.40.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.
@@ -5,10 +5,11 @@
5
5
  // here. NOTHING in the read graph imports THIS module, so the advisor surfaces can ask about the
6
6
  // practice without ever reaching a writer (D-18).
7
7
  //
8
- // What --check judges: every in-scope file against the config's `defaults`, and every RECORDED size
9
- // against the ratchet instead — a record may not grow, may not sit above what the tree measures, and
10
- // may not outlive its file. Each declared root carries the same ratchet over its summed lines, so
11
- // splitting one big file into six buys no headroom.
8
+ // What --check judges: every in-scope file against the resolved limits with their bands, layout
9
+ // where it is recorded or the config is absent, and every RECORDED size against the ratchet — a
10
+ // record may not grow, and one above the tree or gone warns until the regeneration lowers or removes
11
+ // it. Each declared root carries the same exact ratchet over its summed lines, so splitting one big
12
+ // file into six buys no headroom. An absent config is judged under the kit's values.
12
13
  //
13
14
  // What --write-baseline does: regenerates the machine keys from the tree, and ONLY the machine keys.
14
15
  // The authored half is copied through with its VALUES and their ORDER preserved exactly; the file
@@ -21,7 +22,12 @@
21
22
  // What --adopt does: mints the record and declares the gate — the whole adoption as ONE consented
22
23
  // line, because the alternative is a two-step ceremony whose halves can be left half-done. It
23
24
  // composes the two writers it already has (this module's mint, the fill's consented apply restricted
24
- // to this one id) and owns no write of its own.
25
+ // to this one id) and owns no write of its own, but for the schema-1 move of a minted config, which
26
+ // carries both records verbatim.
27
+ //
28
+ // What --override does: once a regeneration under the current limits would raise nothing, writes or
29
+ // removes one reasoned override of a kit limit and regenerates the machine keys under the new limits
30
+ // in the same write. Every write here moves a schema-1 config to schema 2; --check stops on one.
25
31
  //
26
32
  // Exit codes: 0 green / 1 violation or refusal / 2 usage, config or enumeration error.
27
33
  // Dependency-free, Node >= 22. No side effects on import.
@@ -30,121 +36,147 @@ import { resolve } from 'node:path';
30
36
  import { assertDocsAiDeployment, writeDocsAiFileAtomic } from './atomic-write.mjs';
31
37
  import { isDirectRun, sameFile } from './direct-run.mjs';
32
38
  import {
33
- AUTHORED_KEYS,
39
+ KIT_LIMITS,
34
40
  SOURCE_SIZE_CONFIG_REL,
35
41
  SOURCE_SIZE_GATE_ID,
42
+ SOURCE_SIZE_SCHEMA,
43
+ applyOverride,
44
+ assertNoStoreRoot,
36
45
  loadSourceSizeConfig,
37
46
  matchesSourceSizeGate,
47
+ materialize,
48
+ migrateSchema1,
49
+ planRecord,
38
50
  reasonDefect,
39
51
  scopeFail,
52
+ serialize,
53
+ validateSourceSizeConfig,
40
54
  } from './source-size-core.mjs';
41
- import { changesFor, isRaise, judgeTree, ownEntry } from './source-size-judge.mjs';
55
+ import { bandWarningsOf, judgeTree, standingWarningsOf, stopsOf } from './source-size-judge.mjs';
42
56
  import { GATES_REL, loadDeclaration } from './gates-declaration.mjs';
43
57
  import { applyFill } from './gates-init.mjs';
44
58
  import {
59
+ HELP,
60
+ TEMPLATE_README,
61
+ TEMPLATE_READMES,
45
62
  absentRefusalLines,
46
63
  adoptAbsentRefusalLines,
47
64
  checkReportLines,
48
65
  gateAlreadyDeclaredLines,
49
66
  gateDeclaredLines,
50
67
  gateRefusedLines,
68
+ notJudgedLines,
69
+ overrideOutgrownLines,
70
+ overrideUnchangedLines,
71
+ overrideWrittenLines,
51
72
  reasonRequiredLines,
52
73
  recordNoLongerHoldsLines,
53
74
  recordRecognizedLines,
75
+ schema1MovedLines,
76
+ schema1StopLines,
77
+ statedLimitLines,
54
78
  unmintedRefusalLines,
79
+ warningLines,
55
80
  writtenLines,
56
81
  } from './source-size-report.mjs';
57
82
 
58
83
  const usageFail = (message) => Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: 2 });
59
84
  const RECORD_NOUN = 'the source-size record';
60
85
 
86
+ // What an absent config is judged as: schema 2 under the kit's values, layout over "." and the store.
87
+ const ABSENT = Object.freeze({ _README: TEMPLATE_README, schema: SOURCE_SIZE_SCHEMA });
88
+
89
+ // Every run returns the config it resolved, so the CLI states the limits that run judged, and the
90
+ // scope it judged, so the CLI says once what it did not.
61
91
  export const runCheck = ({ cwd, deps = {} }) => {
62
- const { state, config, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
63
- if (state === 'absent') return { code: 1, lines: absentRefusalLines(cwd) };
64
- if (state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys }) };
65
- const verdict = judgeTree(cwd, config, deps);
66
- return { code: verdict.findings.length === 0 ? 0 : 1, lines: checkReportLines({ cwd, config, verdict }) };
92
+ const { state, config: present, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
93
+ const absent = state === 'absent';
94
+ const config = absent ? validateSourceSizeConfig(ABSENT) : present;
95
+ if (config.schema === 1) return { code: 1, lines: schema1StopLines(cwd), config };
96
+ if (!absent && state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys }), config };
97
+ const judged = { absent, layout: absent || config.layout !== null };
98
+ const verdict = judgeTree(cwd, config, deps, judged);
99
+ return { code: stopsOf(verdict.findings).length === 0 ? 0 : 1, lines: checkReportLines({ cwd, config, verdict, absent }), config, judged };
67
100
  };
68
101
 
69
102
  // ── the writer ────────────────────────────────────────────────────────────────────────────────────
70
103
 
71
- // planRecord computes what the regeneration WOULD write, before any reason is applied — so a raise
72
- // can be refused without ever building an entry that carries no reason. It reads the JUDGE's
73
- // projection, never its own: the checker's verdict and the file the writer produces are then two
74
- // renderings of one computation, and neither can promise what the other would not do.
75
- const planRecord = ({ config, verdict }) => {
76
- const oldBaseline = config.baseline ?? {};
77
- const oldAggregate = config.aggregate ?? {};
78
- const files = verdict.scope.files.map((rel) => {
79
- const next = verdict.projected.get(rel);
80
- const recorded = ownEntry(oldBaseline, rel);
81
- return { rel, next, recorded, changes: changesFor(rel, next, recorded) };
82
- });
83
- const roots = config.roots.map((root) => ({
84
- root,
85
- lines: verdict.rootLines.get(root) ?? 0,
86
- recorded: ownEntry(oldAggregate, root),
87
- }));
88
- const deltas = [
89
- ...files.flatMap(({ changes }) => changes),
90
- // A record whose file left scope is REMOVED, never kept: that is what makes a split or a rename
91
- // visible in the delta instead of silently surviving as headroom.
92
- ...Object.entries(oldBaseline)
93
- .filter(([rel]) => !verdict.measured.has(rel))
94
- .flatMap(([rel, recorded]) => changesFor(rel, {}, recorded)),
95
- ...roots
96
- .filter(({ lines, recorded }) => (recorded ? recorded.lines : null) !== lines)
97
- .map(({ root, lines, recorded }) => ({ target: root, dimension: 'aggregate lines', from: recorded ? recorded.lines : null, to: lines })),
98
- ...Object.entries(oldAggregate)
99
- .filter(([root]) => !config.roots.includes(root))
100
- .map(([root, recorded]) => ({ target: root, dimension: 'aggregate lines', from: recorded.lines, to: null })),
101
- ];
102
- return { files, roots, deltas, raises: deltas.filter(isRaise) };
103
- };
104
+ // A schema-1 config is moved by the one transform, the kit's old template `_README` replaced by the
105
+ // new one; every write of this module goes through it, so no writer ever writes schema 1 back.
106
+ const schema2Of = (parsed) => (parsed.schema === 1 ? migrateSchema1(parsed, TEMPLATE_READMES) : parsed);
104
107
 
105
- // The reason of an entry the regeneration did NOT raise is the one already recorded — a tighten
106
- // rewrites a number, never the human sentence that justified it.
107
- const materialize = ({ files, roots }, reason) => ({
108
- baseline: Object.fromEntries(
109
- files
110
- .filter(({ next }) => Object.keys(next).length > 0)
111
- .map(({ rel, next, recorded, changes }) => [rel, {
112
- ...next,
113
- reason: changes.some(isRaise) ? reason : recorded.reason,
114
- }]),
115
- ),
116
- aggregate: Object.fromEntries(
117
- roots.map(({ root, lines, recorded }) => [root, {
118
- lines,
119
- reason: !recorded || lines > recorded.lines ? reason : recorded.reason,
120
- }]),
121
- ),
122
- });
108
+ // What a move says it did, read off the moved config itself.
109
+ const movedLines = (cwd, parsed) => (parsed.schema === 1 ? schema1MovedLines(cwd) : []);
123
110
 
124
- // The file is CANONICALLY serialized: the authored VALUES and the ORDER the human wrote them in are
125
- // preserved exactly, their formatting is not — this file is machine-maintained and the writer owns
126
- // half of it, so one deterministic rendering is what makes "regenerate an unchanged tree and get the
127
- // same bytes" true at all.
128
- const serialize = (parsed, machineKeys) => {
129
- const authored = Object.fromEntries(Object.keys(parsed).filter((key) => AUTHORED_KEYS.includes(key)).map((key) => [key, parsed[key]]));
130
- return `${JSON.stringify({ ...authored, ...machineKeys }, null, 2)}\n`;
111
+ const writeRecord = (cwd, body, deps) =>
112
+ writeDocsAiFileAtomic(cwd, SOURCE_SIZE_CONFIG_REL, body, deps, { stop: scopeFail, noun: RECORD_NOUN });
113
+
114
+ // A run that writes prints every warning its write leaves standing; a refused write prints only
115
+ // those standing today.
116
+ const judgeForWrite = (cwd, config, deps, judged) => {
117
+ const verdict = judgeTree(cwd, config, deps, judged);
118
+ const { findings } = verdict;
119
+ return { verdict, plan: planRecord({ config, verdict }), bandWarnings: warningLines(bandWarningsOf(findings)), warnings: warningLines(standingWarningsOf(findings)) };
131
120
  };
132
121
 
133
- export const runWriteBaseline = ({ cwd, reason, deps = {} }) => {
122
+ // Layout is regenerated wherever it is judged; --layout starts it on a present config with none, and
123
+ // changes nothing on one that records layout or is absent.
124
+ export const runWriteBaseline = ({ cwd, reason, layout = false, deps = {} }) => {
134
125
  // Checked BEFORE the config is read, so a project that was never deployed hears about the
135
126
  // deployment rather than about a file it has no place to put.
136
127
  assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
137
- const { state, config, parsed, text } = loadSourceSizeConfig(cwd, deps);
138
- if (state === 'absent') return { code: 1, lines: absentRefusalLines(cwd) };
139
- const verdict = judgeTree(cwd, config, deps);
140
- const plan = planRecord({ config, verdict });
141
- if (plan.raises.length > 0 && reason === undefined) return { code: 1, lines: reasonRequiredLines(cwd, plan.deltas) };
142
- const body = serialize(parsed, materialize(plan, reason));
128
+ const loaded = loadSourceSizeConfig(cwd, deps);
129
+ const absent = loaded.state === 'absent';
130
+ const parsed = absent ? ABSENT : loaded.parsed;
131
+ const config = absent ? validateSourceSizeConfig(parsed) : loaded.config;
132
+ if (layout && !absent && config.layout === null) assertNoStoreRoot(config.roots);
133
+ const judged = { absent, layout: absent || layout || config.layout !== null };
134
+ const { plan, bandWarnings, warnings } = judgeForWrite(cwd, config, deps, judged);
135
+ const starts = layout && !absent && config.layout === null;
136
+ if (plan.raises.length > 0 && reason === undefined) return { code: 1, lines: [...bandWarnings, ...reasonRequiredLines(cwd, plan.deltas, { layout: starts })], config, judged };
137
+ const body = serialize(schema2Of(parsed), materialize(plan, reason));
143
138
  // Whether anything was written is decided by the BYTES, not by the delta count: completing a
144
139
  // hand-edited half record changes the file while raising nothing at all.
145
- const changed = body !== text;
146
- if (changed) writeDocsAiFileAtomic(cwd, SOURCE_SIZE_CONFIG_REL, body, deps, { stop: scopeFail, noun: RECORD_NOUN });
147
- return { code: 0, lines: writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed }) };
140
+ const changed = body !== loaded.text;
141
+ if (changed) writeRecord(cwd, body, deps);
142
+ const written = writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed });
143
+ return { code: 0, lines: [...warnings, ...movedLines(cwd, parsed), ...written], config, judged };
144
+ };
145
+
146
+ // --override: the projection under the CURRENT limits comes first, so an override's reason never
147
+ // lands on drift it did not cause; only then is the override applied and the record regenerated
148
+ // under the new limits, in the same atomic write.
149
+ export const runOverride = ({ cwd, id, value, tolerance, kitDefault, reason, deps = {} }) => {
150
+ assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
151
+ const { state, config, parsed, text, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
152
+ if (state === 'absent') return { code: 1, lines: absentRefusalLines(cwd) };
153
+ if (state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys }), config };
154
+ const judged = { absent: false, layout: config.layout !== null };
155
+ const current = planRecord({ config, verdict: judgeTree(cwd, config, deps, judged) });
156
+ if (current.raises.length > 0) return { code: 1, lines: overrideOutgrownLines(cwd, current.deltas), config, judged };
157
+ const resolved = config.limits[id];
158
+ const filled = kitDefault ? null : { value: value ?? resolved.value, tolerance: tolerance ?? resolved.tolerance, reason };
159
+ const kit = KIT_LIMITS[id];
160
+ if (filled !== null && filled.tolerance === kit.tolerance && (kit.value === null || filled.value === kit.value)) {
161
+ throw usageFail(`--override ${id} equals the kit's own numbers — pass --kit-default to return to them; the writer never writes an override equal to the kit's`);
162
+ }
163
+ const next = applyOverride(schema2Of(parsed), id, filled);
164
+ const nextConfig = validateSourceSizeConfig(next);
165
+ const { plan, warnings } = judgeForWrite(cwd, nextConfig, deps, judged);
166
+ const body = serialize(next, materialize(plan, reason));
167
+ if (body === text) return { code: 0, lines: [...warnings, ...overrideUnchangedLines(cwd, id)], config: nextConfig, judged };
168
+ writeRecord(cwd, body, deps);
169
+ return {
170
+ code: 0,
171
+ judged,
172
+ lines: [
173
+ ...warnings,
174
+ ...overrideWrittenLines({ cwd, id, removed: kitDefault, reason }),
175
+ ...movedLines(cwd, parsed),
176
+ ...(plan.deltas.length === 0 ? [] : writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed: true })),
177
+ ],
178
+ config: nextConfig,
179
+ };
148
180
  };
149
181
 
150
182
  // ── the adoption verb (D-16) ──────────────────────────────────────────────────────────────────────
@@ -201,65 +233,55 @@ const recognizeRecord = ({ cwd, deps }) => {
201
233
  return { code: 0, lines: recordRecognizedLines(cwd) };
202
234
  };
203
235
 
236
+ // A MINTED schema-1 config is moved in its own write before adoption reads it as schema 2: the
237
+ // authored half transformed, both machine records carried verbatim, nothing regenerated — so the
238
+ // adoption reason can never ride a raise. An authored or incomplete one is moved by the mint itself.
239
+ const moveMinted = (cwd, parsed, deps) => {
240
+ writeRecord(cwd, serialize(schema2Of(parsed), { baseline: parsed.baseline, aggregate: parsed.aggregate }), deps);
241
+ return movedLines(cwd, parsed);
242
+ };
243
+
244
+ // A stop after the move still prints the move: the write happened, and no stop may hide it.
245
+ const reportingMove = (moved, run) => {
246
+ try {
247
+ return run();
248
+ } catch (err) {
249
+ throw Object.assign(err, { lines: [...moved, ...(err.lines ?? [])] });
250
+ }
251
+ };
252
+
204
253
  // --adopt = settle the record, then declare the gate. The order is not a preference: the fill offers
205
254
  // the gate ONLY over a minted config (declaring it earlier would declare a gate that refuses), so
206
255
  // the record is what makes the declaration offerable at all.
207
256
  export const runAdopt = ({ cwd, reason, deps = {} }) => {
208
- const { state } = loadSourceSizeConfig(cwd, deps);
257
+ const { state, config, parsed } = loadSourceSizeConfig(cwd, deps);
209
258
  if (state === 'absent') return { code: 1, lines: adoptAbsentRefusalLines(cwd) };
259
+ const moved = state === 'minted' && config.schema === 1 ? moveMinted(cwd, parsed, deps) : [];
210
260
  // ADOPTED is asked FIRST, and it is a question about the GATE alone. Idempotence cannot be made
211
261
  // conditional on the record still holding: a declared gate reports its own staleness on every run,
212
262
  // with the reasoned lane, and stopping here would tell a reader the gate was not declared while it
213
263
  // plainly is — which is exactly what re-running the advisor's one-liner on a drifted tree does.
214
264
  // Once the gate is there and the record is minted, nothing is left to adopt.
215
265
  const declared = gateIsDeclared(cwd, deps);
216
- if (declared && state === 'minted') return { code: 0, lines: gateAlreadyDeclaredLines(GATES_REL) };
266
+ if (declared && state === 'minted') return { code: 0, lines: [...moved, ...gateAlreadyDeclaredLines(GATES_REL)] };
217
267
  // Either half carries its OWN self-servable refusals (a raise with no reason, a project with no
218
268
  // docs/ai, a record the tree outgrew). They are returned unchanged: re-wording them here would be
219
269
  // the second practice this module exists to avoid, and each already names the step that clears it.
220
- const record = state === 'minted' ? recognizeRecord({ cwd, deps }) : runWriteBaseline({ cwd, reason, deps });
221
- if (record.code !== 0) return record;
222
- if (declared) return { code: 0, lines: [...record.lines, ...gateAlreadyDeclaredLines(GATES_REL)] };
270
+ const record = state === 'minted' ? reportingMove(moved, () => recognizeRecord({ cwd, deps })) : runWriteBaseline({ cwd, reason, deps });
271
+ if (record.code !== 0) return { code: record.code, lines: [...moved, ...record.lines] };
272
+ if (declared) return { code: 0, lines: [...moved, ...record.lines, ...gateAlreadyDeclaredLines(GATES_REL)] };
223
273
  const gate = declareGate(cwd, deps);
224
- return { code: gate.code, lines: [...record.lines, ...gate.lines] };
274
+ return { code: gate.code, lines: [...moved, ...record.lines, ...gate.lines] };
225
275
  };
226
276
 
227
277
  // ── CLI ───────────────────────────────────────────────────────────────────────────────────────────
228
278
 
229
- const MODES = Object.freeze(['--check', '--write-baseline', '--adopt']);
230
-
231
- const HELP = `source-size-check — the declared source-size practice (agent-workflow family).
232
-
233
- Usage:
234
- node source-size-check.mjs --check [--cwd <project-root>]
235
- node source-size-check.mjs --write-baseline [--reason "<text>"] [--cwd <project-root>]
236
- node source-size-check.mjs --adopt [--reason "<text>"] [--cwd <project-root>]
237
-
238
- Judges every in-scope file against ${SOURCE_SIZE_CONFIG_REL}: git-tracked files under a declared
239
- root carrying a declared extension, minus the excluded path-segment prefixes. Scope is DECLARED,
240
- never guessed — with the config absent the check REFUSES and prints the exact file to author.
241
- Symlinks and submodule gitlinks are skipped by kind; an unmerged index, a non-UTF-8 in-scope path,
242
- an unverifiable in-scope file and an empty declared scope are refusals, never silent greens.
243
-
244
- Counting: lines, and the longest line in BYTES. A terminator never counts (the CR of a CRLF
245
- included); a last line with no final newline still counts; an empty file is 0 lines.
246
-
247
- A file carrying a recorded baseline entry is recorded DEBT: it is judged against the record, which
248
- may not grow, may not sit above the measured size, and may not outlive its file. Each declared root
249
- carries the same ratchet over its summed lines.
250
-
251
- --write-baseline regenerates the machine keys (baseline, aggregate) from the tree. The authored keys
252
- keep their values and their order; the file is canonically serialized, so its formatting is the
253
- writer's. A regeneration that RAISES any recorded value needs --reason; the string is recorded in
254
- the entry it raised. A pure tighten needs none.
255
-
256
- --adopt is the ONE-line adoption: it mints the record and declares the source-size gate (and NOTHING
257
- else) in docs/ai/gates.json. It is idempotent on an already-adopted project. With the config absent
258
- it refuses with the exact file to author — that authoring is the practice's single manual step, and
259
- the refusal says so. A refused declaration exits nonzero and reports both halves: what was minted and
260
- what was not declared.
261
-
262
- Exit codes: 0 green; 1 violation or refusal; 2 usage, config or enumeration error.`;
279
+ const MODES = Object.freeze(['--check', '--write-baseline', '--adopt', '--override']);
280
+ const RUNS = Object.freeze({ '--check': runCheck, '--write-baseline': runWriteBaseline, '--adopt': runAdopt, '--override': runOverride });
281
+ // The modes whose run states the limits it judged; --adopt composes them and says what it did.
282
+ const STATES_LIMITS = Object.freeze(['--check', '--write-baseline', '--override']);
283
+ const KIT_DEFAULT = '--kit-default';
284
+ const LAYOUT = '--layout';
263
285
 
264
286
  const takeOption = (argv, flag) => {
265
287
  const at = argv.indexOf(flag);
@@ -268,33 +290,76 @@ const takeOption = (argv, flag) => {
268
290
  return { rest: [...argv.slice(0, at), ...argv.slice(at + 2)], value: argv[at + 1] };
269
291
  };
270
292
 
293
+ // A number on the command line is plain decimal digits, read inside its grammar or refused.
294
+ const numberOf = (flag, raw, min, max, what) => {
295
+ if (raw === undefined) return undefined;
296
+ const n = /^[0-9]+$/.test(raw) ? Number(raw) : NaN;
297
+ if (!Number.isSafeInteger(n) || n < min || n > max) throw usageFail(`${flag} must be ${what}, got ${JSON.stringify(raw)}`);
298
+ return n;
299
+ };
300
+
301
+ // Everything the argument list alone decides about --override: the id, the options' grammar and
302
+ // their combination. The state refusals and the equality stop come later, in the run.
303
+ const overrideOptions = ({ id, value, tolerance, kitDefault }) => {
304
+ if (!Object.hasOwn(KIT_LIMITS, id)) throw usageFail(`--override ${JSON.stringify(id)} names no kit limit — the kit's limits are ${Object.keys(KIT_LIMITS).join(', ')}`);
305
+ if (kitDefault && (value !== undefined || tolerance !== undefined)) throw usageFail(`${KIT_DEFAULT} returns to the kit's numbers, so it takes no --value or --tolerance`);
306
+ if (!kitDefault && value === undefined && tolerance === undefined) throw usageFail(`--override ${id} needs --value, --tolerance or ${KIT_DEFAULT}`);
307
+ if (value !== undefined && KIT_LIMITS[id].value === null) throw usageFail(`--override ${id} takes --tolerance only — its count is the one a project records`);
308
+ return {
309
+ id,
310
+ kitDefault,
311
+ value: numberOf('--value', value, 1, Number.MAX_SAFE_INTEGER, 'a positive integer'),
312
+ tolerance: numberOf('--tolerance', tolerance, 0, 100, 'an integer percent from 0 to 100'),
313
+ };
314
+ };
315
+
271
316
  export const main = (argv, ctx = {}) => {
272
317
  try {
273
318
  if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: HELP, stderr: '' };
274
319
  const cwdOption = takeOption(argv, '--cwd');
275
320
  const reasonOption = takeOption(cwdOption.rest, '--reason');
321
+ const valueOption = takeOption(reasonOption.rest, '--value');
322
+ const toleranceOption = takeOption(valueOption.rest, '--tolerance');
323
+ const kitDefault = toleranceOption.rest.includes(KIT_DEFAULT);
324
+ const layout = toleranceOption.rest.includes(LAYOUT);
325
+ const rest = toleranceOption.rest.filter((arg) => arg !== KIT_DEFAULT && arg !== LAYOUT);
276
326
  // Resolved BEFORE the run and before anything is rendered: every path this run names is then
277
327
  // meaningful from any directory, not only from the one that invoked it.
278
328
  const cwd = resolve(ctx.cwd ?? process.cwd(), cwdOption.value ?? '.');
279
329
  // Counted over the ARGUMENTS, not over the mode list: filtering the list collapses repeats, so
280
330
  // `--adopt --adopt` read as exactly one mode and a WRITE ran under an argument list this very
281
331
  // guard had just called invalid.
282
- const modes = reasonOption.rest.filter((arg) => MODES.includes(arg));
332
+ const modes = rest.filter((arg) => MODES.includes(arg));
283
333
  if (modes.length === 0) throw usageFail(`nothing to do — pass one of ${MODES.join(', ')} (see --help)`);
284
334
  if (modes.length > 1) throw usageFail(`pass exactly ONE mode, got: ${modes.join(', ')}`);
285
- const unknown = reasonOption.rest.filter((arg) => !MODES.includes(arg));
335
+ const [mode] = modes;
336
+ const idOption = mode === '--override' ? takeOption(rest, '--override') : { rest, value: undefined };
337
+ const unknown = idOption.rest.filter((arg) => !MODES.includes(arg));
286
338
  if (unknown.length > 0) throw usageFail(`unknown argument: ${unknown[0]}`);
339
+ if (mode !== '--override') {
340
+ const stray = [['--value', valueOption.value], ['--tolerance', toleranceOption.value], [KIT_DEFAULT, kitDefault || undefined]]
341
+ .find(([, given]) => given !== undefined);
342
+ if (stray) throw usageFail(`${stray[0]} belongs to --override`);
343
+ }
344
+ if (layout && mode !== '--write-baseline') throw usageFail(`${LAYOUT} belongs to --write-baseline — it starts the layout record`);
287
345
  if (reasonOption.value !== undefined) {
288
- if (modes[0] === '--check') throw usageFail('--reason belongs to --write-baseline and --adopt — a check records nothing');
346
+ if (mode === '--check') throw usageFail('--reason belongs to --write-baseline, --adopt and --override — a check records nothing');
289
347
  const defect = reasonDefect(reasonOption.value);
290
348
  if (defect) throw usageFail(defect);
349
+ } else if (mode === '--override') {
350
+ throw usageFail('--override needs --reason "<text>" — an override is a reasoned change of a kit number');
291
351
  }
352
+ const override = mode === '--override'
353
+ ? overrideOptions({ id: idOption.value, value: valueOption.value, tolerance: toleranceOption.value, kitDefault })
354
+ : {};
292
355
  const deps = ctx.deps ?? {};
293
- const run = { '--check': runCheck, '--write-baseline': runWriteBaseline, '--adopt': runAdopt }[modes[0]];
294
- const { code, lines } = run({ cwd, reason: reasonOption.value, deps });
295
- return { code, stdout: lines.join('\n'), stderr: '' };
356
+ const { code, lines, config, judged } = RUNS[mode]({ cwd, reason: reasonOption.value, layout, deps, ...override });
357
+ const states = STATES_LIMITS.includes(mode) && config;
358
+ const limits = states ? statedLimitLines(config) : [];
359
+ const notJudged = states && judged ? notJudgedLines(cwd, { ...judged, config }) : [];
360
+ return { code, stdout: [...limits, ...notJudged, ...lines].join('\n'), stderr: '' };
296
361
  } catch (err) {
297
- return { code: err.exitCode ?? 1, stdout: '', stderr: `source-size-check: ${err.message}` };
362
+ return { code: err.exitCode ?? 1, stdout: (err.lines ?? []).join('\n'), stderr: `source-size-check: ${err.message}` };
298
363
  }
299
364
  };
300
365
 
@@ -9,22 +9,34 @@
9
9
  // • A RECORDED size is debt, not permission: every entry carries a reason, and the reason lands
10
10
  // verbatim in the JSON, the commit message and the release CHANGELOG — so it is validated as the
11
11
  // single line those three surfaces can carry.
12
+ // • SCHEMAS — 2 is the shape: the kit's limits live in its code (tools/source-size/), the config
13
+ // holds the scope, the record and a project's reasoned overrides. 1 is still read strictly and
14
+ // resolved in memory by the very transform the writer moves it with; a read writes nothing.
12
15
  //
13
16
  // Dependency-free, Node >= 22. No side effects on import.
14
17
 
15
18
  import { readFileSync, lstatSync } from 'node:fs';
16
19
  import { isAbsolute } from 'node:path';
17
20
  import { SOURCE_SIZE_CONFIG_REL, configFail, configPathFor, isLineUnsafe } from './source-size-refusal.mjs';
21
+ import { KIT_LIMITS, SPEC_STORE_ROOT, layoutDefect, limitsDefect, migrateSchema1, resolveLimits } from './source-size/index.mjs';
18
22
 
19
- export const SOURCE_SIZE_SCHEMA = 1;
20
- export const SOURCE_SIZE_DEFAULTS = Object.freeze({ maxLines: 400, maxLineBytes: 1000 });
23
+ export const SOURCE_SIZE_SCHEMA = 2;
24
+ export const SOURCE_SIZE_DEFAULTS = Object.freeze({
25
+ maxLines: KIT_LIMITS['lines-per-file'].value,
26
+ maxLineBytes: KIT_LIMITS['bytes-per-line'].value,
27
+ });
21
28
  export const REASON_MAX_BYTES = 300;
22
29
  // The reason a FIRST mint records: every value is new, so every value is a raise, and "this is what
23
30
  // the tree already carried when the practice arrived" is the honest sentence for all of them.
24
31
  export const INITIAL_ADOPTION_REASON = 'initial adoption';
32
+ // The root an absent `roots` declares: every tracked path. Admitted only as the sole root.
33
+ export const WHOLE_TREE_ROOT = '.';
25
34
 
26
- export const AUTHORED_KEYS = Object.freeze(['_README', 'schema', 'defaults', 'roots', 'exclude', 'extensions']);
35
+ export const AUTHORED_KEYS = Object.freeze(['_README', 'schema', 'roots', 'exclude', 'extensions', 'limits']);
36
+ const SCHEMA1_AUTHORED_KEYS = Object.freeze(['_README', 'schema', 'defaults', 'roots', 'exclude', 'extensions']);
27
37
  export const MACHINE_KEYS = Object.freeze(['baseline', 'aggregate']);
38
+ // The layout record is a machine key of its own, and no part of the state: MINTED means the two above.
39
+ export const LAYOUT_KEY = 'layout';
28
40
  const ENTRY_KEYS = Object.freeze(['lines', 'maxLineBytes', 'reason']);
29
41
 
30
42
  const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -74,8 +86,9 @@ export const reasonDefect = (reason) => {
74
86
  return null;
75
87
  };
76
88
 
77
- // Whole-segment prefix containment: "a/b" contains "a/b" and "a/b/c", never "a/bc".
78
- export const segmentPrefixOf = (prefix, path) => path === prefix || path.startsWith(`${prefix}/`);
89
+ // Whole-segment prefix containment: "a/b" contains "a/b" and "a/b/c", never "a/bc"; the root "."
90
+ // contains every path.
91
+ export const segmentPrefixOf = (prefix, path) => prefix === WHOLE_TREE_ROOT || path === prefix || path.startsWith(`${prefix}/`);
79
92
 
80
93
  // practiceFacts(config) → the numbers every surface that SPEAKS for the practice states: the caps,
81
94
  // how much is declared, and how much is recorded. Derived in ONE place so the plan-time render and
@@ -119,18 +132,20 @@ const validateEntryMap = (map, what, requiredDimensions, extra) => {
119
132
  }
120
133
  };
121
134
 
122
- // validateSourceSizeConfig(parsed) → the normalized config. THROWS configFail (exit 2) on anything it
123
- // cannot judge — an unknown key included, because a typo'd key would otherwise disarm a rule.
124
- export const validateSourceSizeConfig = (parsed) => {
125
- if (!isPlainObject(parsed)) throw configFail(`${SOURCE_SIZE_CONFIG_REL} must contain a JSON object`);
126
- const known = new Set([...AUTHORED_KEYS, ...MACHINE_KEYS]);
127
- const unknown = Object.keys(parsed).filter((k) => !known.has(k));
128
- if (unknown.length > 0) {
129
- throw configFail(`${SOURCE_SIZE_CONFIG_REL} carries unknown key(s): ${unknown.join(', ')} — known keys are ${[...known].join(', ')}`);
130
- }
131
- if (parsed.schema !== SOURCE_SIZE_SCHEMA) {
132
- throw configFail(`"schema" must be ${SOURCE_SIZE_SCHEMA}, got ${JSON.stringify(parsed.schema)}`);
135
+ // Where layout is judged, the spec store is a root of its own, so a declared root at or inside it
136
+ // would count the same entries twice.
137
+ export const assertNoStoreRoot = (roots) => {
138
+ const inside = roots.find((root) => segmentPrefixOf(SPEC_STORE_ROOT, root));
139
+ if (inside !== undefined) {
140
+ throw configFail(`"roots" declares "${inside}", at or inside the spec store ${SPEC_STORE_ROOT} — where layout is judged the store is a root of its own, so declare a root outside it`);
133
141
  }
142
+ };
143
+
144
+ const emptyArrayFail = (key) =>
145
+ configFail(`"${key}" must be a non-empty array — scope is DECLARED, never guessed, so an empty "${key}" is a misdeclaration rather than an empty green`);
146
+
147
+ // Schema 1 is judged as it always was: its numbers under `defaults`, its scope declared in full.
148
+ const validateSchema1 = (parsed) => {
134
149
  if (!isPlainObject(parsed.defaults)) throw configFail('"defaults" must be an object carrying maxLines and maxLineBytes');
135
150
  const unknownDefaults = Object.keys(parsed.defaults).filter((k) => !['maxLines', 'maxLineBytes'].includes(k));
136
151
  if (unknownDefaults.length > 0) throw configFail(`"defaults" carries unknown key(s): ${unknownDefaults.join(', ')}`);
@@ -139,24 +154,61 @@ export const validateSourceSizeConfig = (parsed) => {
139
154
  if (defect) throw configFail(defect);
140
155
  }
141
156
  for (const key of ['roots', 'extensions']) {
142
- if (!Array.isArray(parsed[key]) || parsed[key].length === 0) {
143
- throw configFail(`"${key}" must be a non-empty array — scope is DECLARED, never guessed, so an empty "${key}" is a misdeclaration rather than an empty green`);
144
- }
145
- for (const value of parsed[key]) {
146
- const defect = key === 'roots' ? declaredPathDefect(value, 'a "roots" entry') : extensionDefect(value);
157
+ if (!Object.hasOwn(parsed, key)) throw emptyArrayFail(key);
158
+ }
159
+ };
160
+
161
+ // The keys each schema may carry. A key of the other schema is a stop named as such: a `defaults` on
162
+ // schema 2 would be a second home for a kit value, and a `limits` on schema 1 a shape no writer made.
163
+ const keysDefect = (parsed) => {
164
+ if (parsed.schema === 2 && Object.hasOwn(parsed, 'defaults')) {
165
+ return '"defaults" is a schema-1 key — the kit\'s limits live in the kit\'s code, and a project states its own number as a reasoned override under "limits"';
166
+ }
167
+ if (parsed.schema === 1 && Object.hasOwn(parsed, 'limits')) {
168
+ return '"limits" is a schema-2 key — a schema-1 config states its numbers under "defaults"; --write-baseline moves it to schema 2';
169
+ }
170
+ if (parsed.schema === 1 && Object.hasOwn(parsed, LAYOUT_KEY)) {
171
+ return '"layout" is a schema-2 key — a schema-1 config records no layout; --write-baseline moves it to schema 2';
172
+ }
173
+ const known = new Set([...(parsed.schema === 1 ? SCHEMA1_AUTHORED_KEYS : [...AUTHORED_KEYS, LAYOUT_KEY]), ...MACHINE_KEYS]);
174
+ const unknown = Object.keys(parsed).filter((k) => !known.has(k));
175
+ return unknown.length === 0 ? null : `${SOURCE_SIZE_CONFIG_REL} carries unknown key(s): ${unknown.join(', ')} — known keys are ${[...known].join(', ')}`;
176
+ };
177
+
178
+ // validateSourceSizeConfig(parsed) → the normalized config. THROWS configFail (exit 2) on anything it
179
+ // cannot judge — an unknown key included, because a typo'd key would otherwise disarm a rule.
180
+ export const validateSourceSizeConfig = (parsed) => {
181
+ if (!isPlainObject(parsed)) throw configFail(`${SOURCE_SIZE_CONFIG_REL} must contain a JSON object`);
182
+ if (parsed.schema !== 1 && parsed.schema !== SOURCE_SIZE_SCHEMA) {
183
+ throw configFail(`"schema" must be 1 or ${SOURCE_SIZE_SCHEMA}, got ${JSON.stringify(parsed.schema)}`);
184
+ }
185
+ const keys = keysDefect(parsed);
186
+ if (keys) throw configFail(keys);
187
+ if (parsed.schema === 1) validateSchema1(parsed);
188
+ // A schema-1 config is resolved in memory by the very transform the writer moves it with.
189
+ const shape = parsed.schema === 1 ? migrateSchema1(parsed) : parsed;
190
+ for (const key of ['roots', 'extensions']) {
191
+ if (!Object.hasOwn(shape, key)) continue;
192
+ if (!Array.isArray(shape[key]) || shape[key].length === 0) throw emptyArrayFail(key);
193
+ for (const value of shape[key]) {
194
+ const defect = key === 'extensions' ? extensionDefect(value) : value === WHOLE_TREE_ROOT ? null : declaredPathDefect(value, 'a "roots" entry');
147
195
  if (defect) throw configFail(defect);
148
196
  }
149
197
  }
198
+ const roots = shape.roots ?? [WHOLE_TREE_ROOT];
150
199
  // A root declared twice is not "overlapping itself" by the rule below (the rule compares distinct
151
200
  // values), yet it double-counts everywhere a root is ITERATED rather than keyed — the printed
152
201
  // delta most visibly, which is the durable record of a regeneration.
153
202
  const declaredRoots = new Set();
154
- for (const root of parsed.roots) {
203
+ for (const root of roots) {
155
204
  if (declaredRoots.has(root)) throw configFail(`"roots" declares "${root}" twice — a duplicated root double-counts its files wherever roots are iterated`);
156
205
  declaredRoots.add(root);
157
206
  }
158
- for (const outer of parsed.roots) {
159
- for (const inner of parsed.roots) {
207
+ if (roots.length > 1 && roots.includes(WHOLE_TREE_ROOT)) {
208
+ throw configFail(`"roots" declares "${WHOLE_TREE_ROOT}" beside another root — "${WHOLE_TREE_ROOT}" covers every tracked path, so it is admitted only as the sole root`);
209
+ }
210
+ for (const outer of roots) {
211
+ for (const inner of roots) {
160
212
  if (outer !== inner && segmentPrefixOf(outer, inner)) {
161
213
  throw configFail(`"roots" entries overlap: "${inner}" sits inside "${outer}" — an overlapping root double-counts its files in the aggregate`);
162
214
  }
@@ -169,6 +221,10 @@ export const validateSourceSizeConfig = (parsed) => {
169
221
  if (defect) throw configFail(defect);
170
222
  }
171
223
  }
224
+ if (Object.hasOwn(shape, 'limits')) {
225
+ const defect = limitsDefect(shape.limits, reasonDefect);
226
+ if (defect) throw configFail(defect);
227
+ }
172
228
  if (Object.hasOwn(parsed, 'baseline')) {
173
229
  validateEntryMap(parsed.baseline, 'baseline', 'any', (key) => {
174
230
  const defect = declaredPathDefect(key, 'a "baseline" key');
@@ -182,14 +238,23 @@ export const validateSourceSizeConfig = (parsed) => {
182
238
  }
183
239
  });
184
240
  }
241
+ if (Object.hasOwn(parsed, LAYOUT_KEY)) {
242
+ const defect = layoutDefect(parsed.layout, reasonDefect);
243
+ if (defect) throw configFail(defect);
244
+ assertNoStoreRoot(roots);
245
+ }
246
+ // `defaults` keeps the shape the judge, practiceFacts and the plan-time cap read, now resolved.
247
+ const { limits, defaults } = resolveLimits(shape.limits);
185
248
  return {
186
249
  schema: parsed.schema,
187
- defaults: { ...parsed.defaults },
188
- roots: [...parsed.roots],
250
+ defaults,
251
+ limits,
252
+ roots: [...roots],
189
253
  exclude: Object.hasOwn(parsed, 'exclude') ? [...parsed.exclude] : [],
190
- extensions: [...parsed.extensions],
254
+ extensions: Object.hasOwn(shape, 'extensions') ? [...shape.extensions] : [],
191
255
  baseline: Object.hasOwn(parsed, 'baseline') ? { ...parsed.baseline } : null,
192
256
  aggregate: Object.hasOwn(parsed, 'aggregate') ? { ...parsed.aggregate } : null,
257
+ layout: Object.hasOwn(parsed, LAYOUT_KEY) ? parsed.layout : null,
193
258
  };
194
259
  };
195
260