@sabaiway/agent-workflow-kit 14.39.0 → 14.41.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,151 @@ 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,
45
+ checkTargetOf,
46
+ isRaise,
36
47
  loadSourceSizeConfig,
37
48
  matchesSourceSizeGate,
49
+ materialize,
50
+ migrateSchema1,
51
+ planRecord,
38
52
  reasonDefect,
39
53
  scopeFail,
54
+ serialize,
55
+ validateSourceSizeConfig,
40
56
  } from './source-size-core.mjs';
41
- import { changesFor, isRaise, judgeTree, ownEntry } from './source-size-judge.mjs';
57
+ import { bandWarningsOf, judgeTree, standingWarningsOf, stopsOf } from './source-size-judge.mjs';
42
58
  import { GATES_REL, loadDeclaration } from './gates-declaration.mjs';
43
59
  import { applyFill } from './gates-init.mjs';
44
60
  import {
61
+ HELP,
62
+ TEMPLATE_README,
63
+ TEMPLATE_READMES,
45
64
  absentRefusalLines,
46
65
  adoptAbsentRefusalLines,
47
66
  checkReportLines,
48
67
  gateAlreadyDeclaredLines,
49
68
  gateDeclaredLines,
50
69
  gateRefusedLines,
70
+ notJudgedLines,
71
+ overrideOutgrownLines,
72
+ overrideUnchangedLines,
73
+ overrideWrittenLines,
51
74
  reasonRequiredLines,
52
75
  recordNoLongerHoldsLines,
53
76
  recordRecognizedLines,
77
+ schema1MovedLines,
78
+ schema1StopLines,
79
+ statedLimitLines,
54
80
  unmintedRefusalLines,
81
+ warningLines,
55
82
  writtenLines,
56
83
  } from './source-size-report.mjs';
57
84
 
58
85
  const usageFail = (message) => Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: 2 });
59
86
  const RECORD_NOUN = 'the source-size record';
87
+ const LAYOUT_GROWTH_LEAD = 'source-size: --layout REFUSED — it starts the layout record and raises nothing else, but the record no longer holds for this tree, so that growth takes --write-baseline --reason first; nothing was written.';
88
+
89
+ // What an absent config is judged as: schema 2 under the kit's values, layout over "." and the store.
90
+ const ABSENT = Object.freeze({ _README: TEMPLATE_README, schema: SOURCE_SIZE_SCHEMA });
60
91
 
92
+ // Every run returns the config it resolved, so the CLI states the limits that run judged, and the
93
+ // scope it judged, so the CLI says once what it did not.
61
94
  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 }) };
95
+ const target = checkTargetOf({ loaded: loadSourceSizeConfig(cwd, deps), absentConfig: validateSourceSizeConfig(ABSENT) });
96
+ const { config, judged } = target;
97
+ if (target.stop === 'schema-1') return { code: 1, lines: schema1StopLines(cwd), config };
98
+ if (target.stop === 'unminted') return { code: 1, lines: unmintedRefusalLines(cwd, { state: target.state, missing: target.missing }), config };
99
+ const verdict = judgeTree(cwd, config, deps, judged);
100
+ return { code: stopsOf(verdict.findings).length === 0 ? 0 : 1, lines: checkReportLines({ cwd, config, verdict, absent: judged.absent }), config, judged };
67
101
  };
68
102
 
69
103
  // ── the writer ────────────────────────────────────────────────────────────────────────────────────
70
104
 
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
- };
105
+ // A schema-1 config is moved by the one transform, the kit's old template `_README` replaced by the
106
+ // new one; every write of this module goes through it, so no writer ever writes schema 1 back.
107
+ const schema2Of = (parsed) => (parsed.schema === 1 ? migrateSchema1(parsed, TEMPLATE_READMES) : parsed);
104
108
 
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
- });
109
+ // What a move says it did, read off the moved config itself.
110
+ const movedLines = (cwd, parsed) => (parsed.schema === 1 ? schema1MovedLines(cwd) : []);
123
111
 
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`;
112
+ const writeRecord = (cwd, body, deps) =>
113
+ writeDocsAiFileAtomic(cwd, SOURCE_SIZE_CONFIG_REL, body, deps, { stop: scopeFail, noun: RECORD_NOUN });
114
+
115
+ // A run that writes prints every warning its write leaves standing; a refused write prints only
116
+ // those standing today.
117
+ const judgeForWrite = (cwd, config, deps, judged) => {
118
+ const verdict = judgeTree(cwd, config, deps, judged);
119
+ const { findings } = verdict;
120
+ return { verdict, plan: planRecord({ config, verdict }), bandWarnings: warningLines(bandWarningsOf(findings)), warnings: warningLines(standingWarningsOf(findings)) };
131
121
  };
132
122
 
133
- export const runWriteBaseline = ({ cwd, reason, deps = {} }) => {
123
+ // Layout is regenerated wherever it is judged; --layout starts it on a present config with none, and
124
+ // changes nothing on one that records layout or is absent.
125
+ export const runWriteBaseline = ({ cwd, reason, layout = false, deps = {} }) => {
134
126
  // Checked BEFORE the config is read, so a project that was never deployed hears about the
135
127
  // deployment rather than about a file it has no place to put.
136
128
  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));
129
+ const loaded = loadSourceSizeConfig(cwd, deps);
130
+ const absent = loaded.state === 'absent';
131
+ const parsed = absent ? ABSENT : loaded.parsed;
132
+ const config = absent ? validateSourceSizeConfig(parsed) : loaded.config;
133
+ if (layout && !absent && config.layout === null) assertNoStoreRoot(config.roots);
134
+ const judged = { absent, layout: absent || layout || config.layout !== null };
135
+ const { plan, bandWarnings, warnings } = judgeForWrite(cwd, config, deps, judged);
136
+ const starts = layout && !absent && config.layout === null;
137
+ // Starting layout on a minted record raises the layout record alone: growth takes the plain write first.
138
+ const plain = starts && loaded.state === 'minted' ? plan.deltas.filter((delta) => !plan.layout.deltas.includes(delta)) : [];
139
+ if (plain.some(isRaise)) return { code: 1, lines: [...bandWarnings, LAYOUT_GROWTH_LEAD, ...reasonRequiredLines(cwd, plain)], config, judged };
140
+ if (plan.raises.length > 0 && reason === undefined) return { code: 1, lines: [...bandWarnings, ...reasonRequiredLines(cwd, plan.deltas, { layout: starts })], config, judged };
141
+ const body = serialize(schema2Of(parsed), materialize(plan, reason));
143
142
  // Whether anything was written is decided by the BYTES, not by the delta count: completing a
144
143
  // 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 }) };
144
+ const changed = body !== loaded.text;
145
+ if (changed) writeRecord(cwd, body, deps);
146
+ const written = writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed });
147
+ return { code: 0, lines: [...warnings, ...movedLines(cwd, parsed), ...written], config, judged };
148
+ };
149
+
150
+ // --override: the projection under the CURRENT limits comes first, so an override's reason never
151
+ // lands on drift it did not cause; only then is the override applied and the record regenerated
152
+ // under the new limits, in the same atomic write.
153
+ export const runOverride = ({ cwd, id, value, tolerance, kitDefault, reason, deps = {} }) => {
154
+ assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
155
+ const { state, config, parsed, text, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
156
+ if (state === 'absent') return { code: 1, lines: absentRefusalLines(cwd) };
157
+ if (state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys }), config };
158
+ const judged = { absent: false, layout: config.layout !== null };
159
+ const current = planRecord({ config, verdict: judgeTree(cwd, config, deps, judged) });
160
+ if (current.raises.length > 0) return { code: 1, lines: overrideOutgrownLines(cwd, current.deltas), config, judged };
161
+ const resolved = config.limits[id];
162
+ const filled = kitDefault ? null : { value: value ?? resolved.value, tolerance: tolerance ?? resolved.tolerance, reason };
163
+ const kit = KIT_LIMITS[id];
164
+ if (filled !== null && filled.tolerance === kit.tolerance && (kit.value === null || filled.value === kit.value)) {
165
+ 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`);
166
+ }
167
+ const next = applyOverride(schema2Of(parsed), id, filled);
168
+ const nextConfig = validateSourceSizeConfig(next);
169
+ const { plan, warnings } = judgeForWrite(cwd, nextConfig, deps, judged);
170
+ const body = serialize(next, materialize(plan, reason));
171
+ if (body === text) return { code: 0, lines: [...warnings, ...overrideUnchangedLines(cwd, id)], config: nextConfig, judged };
172
+ writeRecord(cwd, body, deps);
173
+ return {
174
+ code: 0,
175
+ judged,
176
+ lines: [
177
+ ...warnings,
178
+ ...overrideWrittenLines({ cwd, id, removed: kitDefault, reason }),
179
+ ...movedLines(cwd, parsed),
180
+ ...(plan.deltas.length === 0 ? [] : writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed: true })),
181
+ ],
182
+ config: nextConfig,
183
+ };
148
184
  };
149
185
 
150
186
  // ── the adoption verb (D-16) ──────────────────────────────────────────────────────────────────────
@@ -201,65 +237,55 @@ const recognizeRecord = ({ cwd, deps }) => {
201
237
  return { code: 0, lines: recordRecognizedLines(cwd) };
202
238
  };
203
239
 
240
+ // A MINTED schema-1 config is moved in its own write before adoption reads it as schema 2: the
241
+ // authored half transformed, both machine records carried verbatim, nothing regenerated — so the
242
+ // adoption reason can never ride a raise. An authored or incomplete one is moved by the mint itself.
243
+ const moveMinted = (cwd, parsed, deps) => {
244
+ writeRecord(cwd, serialize(schema2Of(parsed), { baseline: parsed.baseline, aggregate: parsed.aggregate }), deps);
245
+ return movedLines(cwd, parsed);
246
+ };
247
+
248
+ // A stop after the move still prints the move: the write happened, and no stop may hide it.
249
+ const reportingMove = (moved, run) => {
250
+ try {
251
+ return run();
252
+ } catch (err) {
253
+ throw Object.assign(err, { lines: [...moved, ...(err.lines ?? [])] });
254
+ }
255
+ };
256
+
204
257
  // --adopt = settle the record, then declare the gate. The order is not a preference: the fill offers
205
258
  // the gate ONLY over a minted config (declaring it earlier would declare a gate that refuses), so
206
259
  // the record is what makes the declaration offerable at all.
207
260
  export const runAdopt = ({ cwd, reason, deps = {} }) => {
208
- const { state } = loadSourceSizeConfig(cwd, deps);
261
+ const { state, config, parsed } = loadSourceSizeConfig(cwd, deps);
209
262
  if (state === 'absent') return { code: 1, lines: adoptAbsentRefusalLines(cwd) };
263
+ const moved = state === 'minted' && config.schema === 1 ? moveMinted(cwd, parsed, deps) : [];
210
264
  // ADOPTED is asked FIRST, and it is a question about the GATE alone. Idempotence cannot be made
211
265
  // conditional on the record still holding: a declared gate reports its own staleness on every run,
212
266
  // with the reasoned lane, and stopping here would tell a reader the gate was not declared while it
213
267
  // plainly is — which is exactly what re-running the advisor's one-liner on a drifted tree does.
214
268
  // Once the gate is there and the record is minted, nothing is left to adopt.
215
269
  const declared = gateIsDeclared(cwd, deps);
216
- if (declared && state === 'minted') return { code: 0, lines: gateAlreadyDeclaredLines(GATES_REL) };
270
+ if (declared && state === 'minted') return { code: 0, lines: [...moved, ...gateAlreadyDeclaredLines(GATES_REL)] };
217
271
  // Either half carries its OWN self-servable refusals (a raise with no reason, a project with no
218
272
  // docs/ai, a record the tree outgrew). They are returned unchanged: re-wording them here would be
219
273
  // 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)] };
274
+ const record = state === 'minted' ? reportingMove(moved, () => recognizeRecord({ cwd, deps })) : runWriteBaseline({ cwd, reason, deps });
275
+ if (record.code !== 0) return { code: record.code, lines: [...moved, ...record.lines] };
276
+ if (declared) return { code: 0, lines: [...moved, ...record.lines, ...gateAlreadyDeclaredLines(GATES_REL)] };
223
277
  const gate = declareGate(cwd, deps);
224
- return { code: gate.code, lines: [...record.lines, ...gate.lines] };
278
+ return { code: gate.code, lines: [...moved, ...record.lines, ...gate.lines] };
225
279
  };
226
280
 
227
281
  // ── CLI ───────────────────────────────────────────────────────────────────────────────────────────
228
282
 
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.`;
283
+ const MODES = Object.freeze(['--check', '--write-baseline', '--adopt', '--override']);
284
+ const RUNS = Object.freeze({ '--check': runCheck, '--write-baseline': runWriteBaseline, '--adopt': runAdopt, '--override': runOverride });
285
+ // The modes whose run states the limits it judged; --adopt composes them and says what it did.
286
+ const STATES_LIMITS = Object.freeze(['--check', '--write-baseline', '--override']);
287
+ const KIT_DEFAULT = '--kit-default';
288
+ const LAYOUT = '--layout';
263
289
 
264
290
  const takeOption = (argv, flag) => {
265
291
  const at = argv.indexOf(flag);
@@ -268,33 +294,76 @@ const takeOption = (argv, flag) => {
268
294
  return { rest: [...argv.slice(0, at), ...argv.slice(at + 2)], value: argv[at + 1] };
269
295
  };
270
296
 
297
+ // A number on the command line is plain decimal digits, read inside its grammar or refused.
298
+ const numberOf = (flag, raw, min, max, what) => {
299
+ if (raw === undefined) return undefined;
300
+ const n = /^[0-9]+$/.test(raw) ? Number(raw) : NaN;
301
+ if (!Number.isSafeInteger(n) || n < min || n > max) throw usageFail(`${flag} must be ${what}, got ${JSON.stringify(raw)}`);
302
+ return n;
303
+ };
304
+
305
+ // Everything the argument list alone decides about --override: the id, the options' grammar and
306
+ // their combination. The state refusals and the equality stop come later, in the run.
307
+ const overrideOptions = ({ id, value, tolerance, kitDefault }) => {
308
+ 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(', ')}`);
309
+ if (kitDefault && (value !== undefined || tolerance !== undefined)) throw usageFail(`${KIT_DEFAULT} returns to the kit's numbers, so it takes no --value or --tolerance`);
310
+ if (!kitDefault && value === undefined && tolerance === undefined) throw usageFail(`--override ${id} needs --value, --tolerance or ${KIT_DEFAULT}`);
311
+ if (value !== undefined && KIT_LIMITS[id].value === null) throw usageFail(`--override ${id} takes --tolerance only — its count is the one a project records`);
312
+ return {
313
+ id,
314
+ kitDefault,
315
+ value: numberOf('--value', value, 1, Number.MAX_SAFE_INTEGER, 'a positive integer'),
316
+ tolerance: numberOf('--tolerance', tolerance, 0, 100, 'an integer percent from 0 to 100'),
317
+ };
318
+ };
319
+
271
320
  export const main = (argv, ctx = {}) => {
272
321
  try {
273
322
  if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: HELP, stderr: '' };
274
323
  const cwdOption = takeOption(argv, '--cwd');
275
324
  const reasonOption = takeOption(cwdOption.rest, '--reason');
325
+ const valueOption = takeOption(reasonOption.rest, '--value');
326
+ const toleranceOption = takeOption(valueOption.rest, '--tolerance');
327
+ const kitDefault = toleranceOption.rest.includes(KIT_DEFAULT);
328
+ const layout = toleranceOption.rest.includes(LAYOUT);
329
+ const rest = toleranceOption.rest.filter((arg) => arg !== KIT_DEFAULT && arg !== LAYOUT);
276
330
  // Resolved BEFORE the run and before anything is rendered: every path this run names is then
277
331
  // meaningful from any directory, not only from the one that invoked it.
278
332
  const cwd = resolve(ctx.cwd ?? process.cwd(), cwdOption.value ?? '.');
279
333
  // Counted over the ARGUMENTS, not over the mode list: filtering the list collapses repeats, so
280
334
  // `--adopt --adopt` read as exactly one mode and a WRITE ran under an argument list this very
281
335
  // guard had just called invalid.
282
- const modes = reasonOption.rest.filter((arg) => MODES.includes(arg));
336
+ const modes = rest.filter((arg) => MODES.includes(arg));
283
337
  if (modes.length === 0) throw usageFail(`nothing to do — pass one of ${MODES.join(', ')} (see --help)`);
284
338
  if (modes.length > 1) throw usageFail(`pass exactly ONE mode, got: ${modes.join(', ')}`);
285
- const unknown = reasonOption.rest.filter((arg) => !MODES.includes(arg));
339
+ const [mode] = modes;
340
+ const idOption = mode === '--override' ? takeOption(rest, '--override') : { rest, value: undefined };
341
+ const unknown = idOption.rest.filter((arg) => !MODES.includes(arg));
286
342
  if (unknown.length > 0) throw usageFail(`unknown argument: ${unknown[0]}`);
343
+ if (mode !== '--override') {
344
+ const stray = [['--value', valueOption.value], ['--tolerance', toleranceOption.value], [KIT_DEFAULT, kitDefault || undefined]]
345
+ .find(([, given]) => given !== undefined);
346
+ if (stray) throw usageFail(`${stray[0]} belongs to --override`);
347
+ }
348
+ if (layout && mode !== '--write-baseline') throw usageFail(`${LAYOUT} belongs to --write-baseline — it starts the layout record`);
287
349
  if (reasonOption.value !== undefined) {
288
- if (modes[0] === '--check') throw usageFail('--reason belongs to --write-baseline and --adopt — a check records nothing');
350
+ if (mode === '--check') throw usageFail('--reason belongs to --write-baseline, --adopt and --override — a check records nothing');
289
351
  const defect = reasonDefect(reasonOption.value);
290
352
  if (defect) throw usageFail(defect);
353
+ } else if (mode === '--override') {
354
+ throw usageFail('--override needs --reason "<text>" — an override is a reasoned change of a kit number');
291
355
  }
356
+ const override = mode === '--override'
357
+ ? overrideOptions({ id: idOption.value, value: valueOption.value, tolerance: toleranceOption.value, kitDefault })
358
+ : {};
292
359
  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: '' };
360
+ const { code, lines, config, judged } = RUNS[mode]({ cwd, reason: reasonOption.value, layout, deps, ...override });
361
+ const states = STATES_LIMITS.includes(mode) && config;
362
+ const limits = states ? statedLimitLines(config) : [];
363
+ const notJudged = states && judged ? notJudgedLines(cwd, { ...judged, config }) : [];
364
+ return { code, stdout: [...limits, ...notJudged, ...lines].join('\n'), stderr: '' };
296
365
  } catch (err) {
297
- return { code: err.exitCode ?? 1, stdout: '', stderr: `source-size-check: ${err.message}` };
366
+ return { code: err.exitCode ?? 1, stdout: (err.lines ?? []).join('\n'), stderr: `source-size-check: ${err.message}` };
298
367
  }
299
368
  };
300
369
 
@@ -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