@sabaiway/agent-workflow-kit 23.7.0 → 23.8.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.
@@ -1,290 +1,20 @@
1
1
  #!/usr/bin/env node
2
- // source-size-check.mjs — the source-size practice's CLI and its writer half. The pure read core
3
- // (config, scope, counting, the canonical gate-cmd matcher) lives in source-size-core.mjs, the
4
- // verdict in source-size-judge.mjs and its wording in source-size-report.mjs; all three are imported
5
- // here. NOTHING in the read graph imports THIS module, so the advisor surfaces can ask about the
6
- // practice without ever reaching a writer (D-18).
7
- //
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.
13
- //
14
- // What --write-baseline does: regenerates the machine keys from the tree, and ONLY the machine keys.
15
- // The authored half is copied through with its VALUES and their ORDER preserved exactly; the file
16
- // itself is canonically serialized, so its formatting becomes the writer's (that is what makes a
17
- // regeneration of an unchanged tree reproduce the same bytes). A regeneration that RAISES any value takes
18
- // --reason "<text>" — the checker cannot invent the human's reason — and that string lands verbatim
19
- // in the entry it raises. A pure tighten needs none: shrinking is progress. The printed old→new
20
- // delta is the durable record where docs/ai is git-hidden; it is what the commit message carries.
21
- //
22
- // What --adopt does: mints the record and declares the gate — the whole adoption as ONE consented
23
- // line, because the alternative is a two-step ceremony whose halves can be left half-done. It
24
- // composes the two writers it already has (this module's mint, the fill's consented apply restricted
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.
2
+ // source-size-check.mjs — the size check's command line: it parses the arguments, runs the one mode
3
+ // they name from source-size-runs.mjs (what each mode does is told there) and composes what that run
4
+ // returned.
31
5
  //
32
6
  // Exit codes: 0 green / 1 violation or refusal / 2 usage, config or enumeration error, or an unexpected error.
33
7
  // Dependency-free, Node >= 22. No side effects on import.
34
8
 
35
9
  import { resolve } from 'node:path';
36
10
  import { composeRedBlock, composeUsageRefusal, guardChecker } from '../references/scripts/shared/index.mjs';
37
- import { assertDocsAiDeployment, writeDocsAiFileAtomic } from './atomic-write.mjs';
38
11
  import { isDirectRun, sameFile } from './direct-run.mjs';
39
- import {
40
- KIT_LIMITS,
41
- SOURCE_SIZE_CONFIG_REL,
42
- SOURCE_SIZE_GATE_ID,
43
- SOURCE_SIZE_SCHEMA,
44
- applyOverride,
45
- assertNoStoreRoot,
46
- checkTargetOf, escapeForLine,
47
- isRaise,
48
- loadSourceSizeConfig,
49
- matchesSourceSizeGate,
50
- materialize,
51
- migrateSchema1,
52
- planRecord,
53
- reasonDefect,
54
- scopeFail,
55
- serialize,
56
- validateSourceSizeConfig,
57
- } from './source-size-core.mjs';
58
- import { bandWarningsOf, judgeTree, standingWarningsOf, stopsOf } from './source-size-judge.mjs';
59
- import { GATES_REL, loadDeclaration } from './gates-declaration.mjs';
60
- import { applyFill } from './gates-init.mjs';
61
- import {
62
- HELP,
63
- TEMPLATE_README,
64
- TEMPLATE_READMES,
65
- absentRefusalLines,
66
- adoptAbsentRefusalLines,
67
- checkReportLines, checkStopBlock, escapeLeadingSpace,
68
- gateAlreadyDeclaredLines,
69
- gateDeclaredLines,
70
- gateRefusedLines,
71
- notJudgedLines,
72
- overrideOutgrownLines,
73
- overrideUnchangedLines,
74
- overrideWrittenLines,
75
- reasonRequiredLines,
76
- recordNoLongerHoldsLines,
77
- recordRecognizedLines,
78
- schema1MovedLines, schema1StopBlock,
79
- statedLimitLines, unmintedRefusalLines, unmintedStopBlock,
80
- warningLines,
81
- writtenLines,
82
- } from './source-size-report.mjs';
12
+ import { KIT_LIMITS, commandReasonDefect, escapeForLine, reasonDefect } from './source-size-core.mjs';
13
+ import { HELP, escapeLeadingSpace, notJudgedLines, statedLimitLines } from './source-size-report.mjs';
14
+ import { CHECKER_NAME, ERROR_PREFIX, USAGE_REFUSAL, runAdopt, runCheck, runOverride, runWriteBaseline, usageFail } from './source-size-runs.mjs';
83
15
 
84
- const ERROR_PREFIX = '[agent-workflow-kit] ';
85
- const CHECKER_NAME = 'source-size';
86
- const USAGE_REFUSAL = Symbol('usage refusal');
87
16
  const HELP_LINES = HELP.split('\n');
88
17
  const USAGE = HELP_LINES.slice(HELP_LINES.indexOf('Usage:')).slice(0, 6).join('\n');
89
- const usageFail = (message) => Object.assign(new Error(`${ERROR_PREFIX}${message}`), { exitCode: 2, [USAGE_REFUSAL]: true });
90
- const RECORD_NOUN = 'the source-size record';
91
- 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.';
92
-
93
- // What an absent config is judged as: schema 2 under the kit's values, layout over "." and the store.
94
- const ABSENT = Object.freeze({ _README: TEMPLATE_README, schema: SOURCE_SIZE_SCHEMA });
95
-
96
- // Every run returns the config it resolved, so the CLI states the limits that run judged, and the
97
- // scope it judged, so the CLI says once what it did not.
98
- export const runCheck = ({ cwd, deps = {} }) => {
99
- const target = checkTargetOf({ loaded: loadSourceSizeConfig(cwd, deps), absentConfig: validateSourceSizeConfig(ABSENT) });
100
- const { config, judged } = target;
101
- if (target.stop === 'schema-1') return { code: 1, block: schema1StopBlock(cwd), config };
102
- if (target.stop === 'unminted') return { code: 1, block: unmintedStopBlock(cwd, { state: target.state, missing: target.missing }), config };
103
- const verdict = judgeTree(cwd, config, deps, judged);
104
- const report = { cwd, config, verdict, absent: judged.absent };
105
- return stopsOf(verdict.findings).length > 0 ? { code: 1, block: checkStopBlock(report), config, judged }
106
- : { code: 0, lines: checkReportLines(report), config, judged };
107
- };
108
-
109
- // ── the writer ────────────────────────────────────────────────────────────────────────────────────
110
-
111
- // A schema-1 config is moved by the one transform, the kit's old template `_README` replaced by the
112
- // new one; every write of this module goes through it, so no writer ever writes schema 1 back.
113
- const schema2Of = (parsed) => (parsed.schema === 1 ? migrateSchema1(parsed, TEMPLATE_READMES) : parsed);
114
-
115
- // What a move says it did, read off the moved config itself.
116
- const movedLines = (cwd, parsed) => (parsed.schema === 1 ? schema1MovedLines(cwd) : []);
117
-
118
- const writeRecord = (cwd, body, deps) =>
119
- writeDocsAiFileAtomic(cwd, SOURCE_SIZE_CONFIG_REL, body, deps, { stop: scopeFail, noun: RECORD_NOUN });
120
-
121
- // A run that writes prints every warning its write leaves standing; a refused write prints only
122
- // those standing today.
123
- const judgeForWrite = (cwd, config, deps, judged) => {
124
- const verdict = judgeTree(cwd, config, deps, judged);
125
- const { findings } = verdict;
126
- return { verdict, plan: planRecord({ config, verdict }), bandWarnings: warningLines(bandWarningsOf(findings)), warnings: warningLines(standingWarningsOf(findings)) };
127
- };
128
-
129
- // Layout is regenerated wherever it is judged; --layout starts it on a present config with none, and
130
- // changes nothing on one that records layout or is absent.
131
- export const runWriteBaseline = ({ cwd, reason, layout = false, deps = {} }) => {
132
- // Checked BEFORE the config is read, so a project that was never deployed hears about the
133
- // deployment rather than about a file it has no place to put.
134
- assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
135
- const loaded = loadSourceSizeConfig(cwd, deps);
136
- const absent = loaded.state === 'absent';
137
- const parsed = absent ? ABSENT : loaded.parsed;
138
- const config = absent ? validateSourceSizeConfig(parsed) : loaded.config;
139
- if (layout && !absent && config.layout === null) assertNoStoreRoot(config.roots);
140
- const judged = { absent, layout: absent || layout || config.layout !== null };
141
- const { plan, bandWarnings, warnings } = judgeForWrite(cwd, config, deps, judged);
142
- const starts = layout && !absent && config.layout === null;
143
- // Starting layout on a minted record raises the layout record alone: growth takes the plain write first.
144
- const plain = starts && loaded.state === 'minted' ? plan.deltas.filter((delta) => !plan.layout.deltas.includes(delta)) : [];
145
- if (plain.some(isRaise)) return { code: 1, lines: [...bandWarnings, LAYOUT_GROWTH_LEAD, ...reasonRequiredLines(cwd, plain)], config, judged };
146
- if (plan.raises.length > 0 && reason === undefined) return { code: 1, lines: [...bandWarnings, ...reasonRequiredLines(cwd, plan.deltas, { layout: starts })], config, judged };
147
- const body = serialize(schema2Of(parsed), materialize(plan, reason));
148
- // Whether anything was written is decided by the BYTES, not by the delta count: completing a
149
- // hand-edited half record changes the file while raising nothing at all.
150
- const changed = body !== loaded.text;
151
- if (changed) writeRecord(cwd, body, deps);
152
- const written = writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed });
153
- return { code: 0, lines: [...warnings, ...movedLines(cwd, parsed), ...written], config, judged };
154
- };
155
-
156
- // --override: the projection under the CURRENT limits comes first, so an override's reason never
157
- // lands on drift it did not cause; only then is the override applied and the record regenerated
158
- // under the new limits, in the same atomic write.
159
- export const runOverride = ({ cwd, id, value, tolerance, kitDefault, reason, deps = {} }) => {
160
- assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
161
- const { state, config, parsed, text, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
162
- if (state === 'absent') return { code: 1, lines: absentRefusalLines(cwd) };
163
- if (state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys }), config };
164
- const judged = { absent: false, layout: config.layout !== null };
165
- const current = planRecord({ config, verdict: judgeTree(cwd, config, deps, judged) });
166
- if (current.raises.length > 0) return { code: 1, lines: overrideOutgrownLines(cwd, current.deltas), config, judged };
167
- const resolved = config.limits[id];
168
- const filled = kitDefault ? null : { value: value ?? resolved.value, tolerance: tolerance ?? resolved.tolerance, reason };
169
- const kit = KIT_LIMITS[id];
170
- if (filled !== null && filled.tolerance === kit.tolerance && (kit.value === null || filled.value === kit.value)) {
171
- 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`);
172
- }
173
- const next = applyOverride(schema2Of(parsed), id, filled);
174
- const nextConfig = validateSourceSizeConfig(next);
175
- const { plan, warnings } = judgeForWrite(cwd, nextConfig, deps, judged);
176
- const body = serialize(next, materialize(plan, reason));
177
- if (body === text) return { code: 0, lines: [...warnings, ...overrideUnchangedLines(cwd, id)], config: nextConfig, judged };
178
- writeRecord(cwd, body, deps);
179
- return {
180
- code: 0,
181
- judged,
182
- lines: [
183
- ...warnings,
184
- ...overrideWrittenLines({ cwd, id, removed: kitDefault, reason }),
185
- ...movedLines(cwd, parsed),
186
- ...(plan.deltas.length === 0 ? [] : writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed: true })),
187
- ],
188
- config: nextConfig,
189
- };
190
- };
191
-
192
- // ── the adoption verb (D-16) ──────────────────────────────────────────────────────────────────────
193
-
194
- // Declaring the gate is delegated to the FILL's own consented apply, restricted to this one id: the
195
- // fill owns every rule about what a written declaration may look like (placement, id collisions, the
196
- // coverage invariant, the atomic write), and a second writer here would be a second set of those
197
- // rules — the one that drifts. `--adopt` is therefore a composition, never a re-implementation.
198
- //
199
- // The already-declared arm is checked FIRST and through the practice's own matcher: an earlier
200
- // partial run leaves a minted record and a declared gate, and re-running must converge rather than
201
- // collide. A gate that merely CARRIES the id without being this checker does not count — it reaches
202
- // the fill and collides there, loudly, which is the honest answer to a squatter.
203
- // The READ is inside the try with the write, deliberately: by the time this runs the record is
204
- // already minted, so ANY failure here — a malformed declaration the reader throws on, just as much
205
- // as a collision the fill refuses — must still report both halves. Letting the read escape would
206
- // surface a bare error carrying neither the mint that succeeded nor the exit contract this tool
207
- // documents.
208
- const declareGate = (cwd, deps) => {
209
- try {
210
- applyFill({ cwd, onlyIds: [SOURCE_SIZE_GATE_ID] }, deps);
211
- return { code: 0, lines: gateDeclaredLines(GATES_REL, SOURCE_SIZE_GATE_ID) };
212
- } catch (err) {
213
- return { code: 1, lines: gateRefusedLines(GATES_REL, err?.message ?? String(err)) };
214
- }
215
- };
216
-
217
- // Is the canonical gate ALREADY there? Asked through the practice's own matcher, so a gate that
218
- // merely carries the id — running something else entirely — never reads as adopted; it reaches the
219
- // fill and collides there, loudly, which is the honest answer to a squatter.
220
- //
221
- // An unreadable declaration is NOT a verdict here. This read is a shortcut, and aborting on it would
222
- // report an outcome before the record was settled; the fill re-reads the same file and refuses
223
- // authoritatively AFTER, so the partial report names both halves truthfully.
224
- const gateIsDeclared = (cwd, deps) => {
225
- try {
226
- const declaration = loadDeclaration(cwd, deps);
227
- return (declaration.outcome === 'loaded' ? declaration.gates : []).some((gate) => matchesSourceSizeGate(gate.cmd, cwd));
228
- } catch {
229
- return false;
230
- }
231
- };
232
-
233
- // A MINTED record is RECOGNIZED, never regenerated. Adoption carries a PINNED reason — the advisor
234
- // renders it as a fixed string, and its item keeps firing while the gate is undeclared — so a
235
- // re-run after a partial adoption would let that one sentence raise whatever the tree grew in the
236
- // meantime. That is exactly the laundering the reason requirement exists to prevent, so the verb
237
- // asks the checker instead: a record that no longer holds is a ratchet question with its own
238
- // reasoned lane, and it must be answered BEFORE a gate is declared over it — declaring one that is
239
- // certain to red the matrix is what the offer rules refuse everywhere else.
240
- const recognizeRecord = ({ cwd, deps }) => {
241
- const verdict = runCheck({ cwd, deps });
242
- if (verdict.code !== 0) return { code: verdict.code, lines: [...composeRedBlock({ name: CHECKER_NAME, ...verdict.block }), ...recordNoLongerHoldsLines(GATES_REL)] };
243
- return { code: 0, lines: recordRecognizedLines(cwd) };
244
- };
245
-
246
- // A MINTED schema-1 config is moved in its own write before adoption reads it as schema 2: the
247
- // authored half transformed, both machine records carried verbatim, nothing regenerated — so the
248
- // adoption reason can never ride a raise. An authored or incomplete one is moved by the mint itself.
249
- const moveMinted = (cwd, parsed, deps) => {
250
- writeRecord(cwd, serialize(schema2Of(parsed), { baseline: parsed.baseline, aggregate: parsed.aggregate }), deps);
251
- return movedLines(cwd, parsed);
252
- };
253
-
254
- // A stop after the move still prints the move: the write happened, and no stop may hide it.
255
- const reportingMove = (moved, run) => {
256
- try {
257
- return run();
258
- } catch (err) {
259
- throw Object.assign(err, { lines: [...moved, ...(err.lines ?? [])] });
260
- }
261
- };
262
-
263
- // --adopt = settle the record, then declare the gate. The order is not a preference: the fill offers
264
- // the gate ONLY over a minted config (declaring it earlier would declare a gate that refuses), so
265
- // the record is what makes the declaration offerable at all.
266
- export const runAdopt = ({ cwd, reason, deps = {} }) => {
267
- const { state, config, parsed } = loadSourceSizeConfig(cwd, deps);
268
- if (state === 'absent') return { code: 1, lines: adoptAbsentRefusalLines(cwd) };
269
- const moved = state === 'minted' && config.schema === 1 ? moveMinted(cwd, parsed, deps) : [];
270
- // ADOPTED is asked FIRST, and it is a question about the GATE alone. Idempotence cannot be made
271
- // conditional on the record still holding: a declared gate reports its own staleness on every run,
272
- // with the reasoned lane, and stopping here would tell a reader the gate was not declared while it
273
- // plainly is — which is exactly what re-running the advisor's one-liner on a drifted tree does.
274
- // Once the gate is there and the record is minted, nothing is left to adopt.
275
- const declared = gateIsDeclared(cwd, deps);
276
- if (declared && state === 'minted') return { code: 0, lines: [...moved, ...gateAlreadyDeclaredLines(GATES_REL)] };
277
- // Either half carries its OWN self-servable refusals (a raise with no reason, a project with no
278
- // docs/ai, a record the tree outgrew). They are returned unchanged: re-wording them here would be
279
- // the second practice this module exists to avoid, and each already names the step that clears it.
280
- const record = state === 'minted' ? reportingMove(moved, () => recognizeRecord({ cwd, deps })) : runWriteBaseline({ cwd, reason, deps });
281
- if (record.code !== 0) return { code: record.code, lines: [...moved, ...record.lines] };
282
- if (declared) return { code: 0, lines: [...moved, ...record.lines, ...gateAlreadyDeclaredLines(GATES_REL)] };
283
- const gate = declareGate(cwd, deps);
284
- return { code: gate.code, lines: [...moved, ...record.lines, ...gate.lines] };
285
- };
286
-
287
- // ── CLI ───────────────────────────────────────────────────────────────────────────────────────────
288
18
 
289
19
  const MODES = Object.freeze(['--check', '--write-baseline', '--adopt', '--override']);
290
20
  const RUNS = Object.freeze({ '--check': runCheck, '--write-baseline': runWriteBaseline, '--adopt': runAdopt, '--override': runOverride });
@@ -354,7 +84,7 @@ export const main = (argv, ctx = {}) => {
354
84
  if (layout && mode !== '--write-baseline') throw usageFail(`${LAYOUT} belongs to --write-baseline — it starts the layout record`);
355
85
  if (reasonOption.value !== undefined) {
356
86
  if (mode === '--check') throw usageFail('--reason belongs to --write-baseline, --adopt and --override — a check records nothing');
357
- const defect = reasonDefect(reasonOption.value);
87
+ const defect = reasonDefect(reasonOption.value) ?? commandReasonDefect(reasonOption.value, { override: mode === '--override' });
358
88
  if (defect) throw usageFail(defect);
359
89
  } else if (mode === '--override') {
360
90
  throw usageFail('--override needs --reason "<text>" — an override is a reasoned change of a kit number');
@@ -363,10 +93,10 @@ export const main = (argv, ctx = {}) => {
363
93
  ? overrideOptions({ id: idOption.value, value: valueOption.value, tolerance: toleranceOption.value, kitDefault })
364
94
  : {};
365
95
  const deps = ctx.deps ?? {};
366
- const { code, lines, block, config, judged } = RUNS[mode]({ cwd, reason: reasonOption.value, layout, deps, ...override });
96
+ const { code, lines, block, config, judged, scope } = RUNS[mode]({ cwd, reason: reasonOption.value, layout, deps, ...override });
367
97
  const states = STATES_LIMITS.includes(mode) && config;
368
98
  const limits = states ? statedLimitLines(config) : [];
369
- const notJudged = states && judged ? notJudgedLines(cwd, { ...judged, config }) : [];
99
+ const notJudged = states && judged ? notJudgedLines(cwd, { ...judged, config, excluded: scope?.excluded }) : [];
370
100
  const output = block ? composeRedBlock({ name: CHECKER_NAME, ...block, after: [...limits, ...notJudged, ...block.after] }) : [...limits, ...notJudged, ...lines];
371
101
  return { code, stdout: output.join('\n'), stderr: '' };
372
102
  } catch (err) {
@@ -26,9 +26,7 @@ export const SOURCE_SIZE_DEFAULTS = Object.freeze({
26
26
  maxLineBytes: KIT_LIMITS['bytes-per-line'].value,
27
27
  });
28
28
  export const REASON_MAX_BYTES = 300;
29
- // The reason a FIRST mint records: every value is new, so every value is a raise, and "this is what
30
- // the tree already carried when the practice arrived" is the honest sentence for all of them.
31
- export const INITIAL_ADOPTION_REASON = 'initial adoption';
29
+ export { INITIAL_ADOPTION_REASON } from './source-size/index.mjs';
32
30
  // The root an absent `roots` declares: every tracked path. Admitted only as the sole root.
33
31
  export const WHOLE_TREE_ROOT = '.';
34
32
  // The kit's own folder: taken away from every judgment by this fixed path, with no config key.
@@ -93,6 +93,12 @@ export {
93
93
  queueChecksOf,
94
94
  spliceLater,
95
95
  helpText,
96
+ GROWTH_REASON_PLACEHOLDER,
97
+ halfOf,
98
+ presentHalves,
99
+ refusedRaises,
100
+ mintReasonOf,
101
+ commandReasonDefect,
96
102
  } from './source-size/index.mjs';
97
103
 
98
104
  export {
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // Dependency-free, Node >= 22. No writes, no side effects on import.
12
12
 
13
- import { measureFile, resolveScope, specStoreEntries } from './source-size-scope.mjs';
13
+ import { measureFile, resolveScope, specStoreEntries, workTreeOf } from './source-size-scope.mjs';
14
14
  import { scopeFail } from './source-size-refusal.mjs';
15
15
  import { SPEC_STORE_ROOT, bandOf, changesFor, isRaise, layoutCounts, ownEntry, projectLayout } from './source-size/index.mjs';
16
16
 
@@ -32,17 +32,19 @@ export const recordFor = (measured, limits) => Object.fromEntries(
32
32
  );
33
33
 
34
34
  const BAND_KINDS = new Set(['within-band', 'root-band', 'dir-band']);
35
+ const WORK_TREE_KINDS = Object.freeze({ untracked: 'untracked', differing: 'unstaged' });
36
+ const STANDING_KINDS = new Set([...BAND_KINDS, ...Object.values(WORK_TREE_KINDS)]);
35
37
  // D-9: the unmechanizable question — real decomposition, or the same coupling spread thinner? — is
36
38
  // asked exactly where a record went DOWN or disappeared, and the checker itself raises it there.
37
39
  const LOWERED_KINDS = new Set(['stale', 'record-obsolete', 'entry-gone', 'root-stale', 'root-gone', 'dir-stale', 'dir-obsolete', 'dir-gone']);
38
40
 
39
41
  export const stopsOf = (findings) => findings.filter((f) => f.severity === STOP);
40
42
  export const warningsOf = (findings) => findings.filter((f) => f.severity === WARNING);
41
- export const bandWarningsOf = (findings) => findings.filter((f) => BAND_KINDS.has(f.kind));
43
+ export const bandWarningsOf = (findings) => findings.filter((f) => STANDING_KINDS.has(f.kind));
42
44
  // The warnings a write leaves standing: a value within its band, one whose obsolete record it drops included.
43
45
  const BAND_OF_OBSOLETE = Object.freeze({ 'record-obsolete': 'within-band', 'dir-obsolete': 'dir-band' });
44
46
  export const standingWarningsOf = (findings) => findings.flatMap((f) => {
45
- if (BAND_KINDS.has(f.kind)) return [f];
47
+ if (STANDING_KINDS.has(f.kind)) return [f];
46
48
  const kind = BAND_OF_OBSOLETE[f.kind];
47
49
  return kind && f.dimension !== 'depth' && f.actual > f.allowed && f.actual <= f.ceiling ? [{ ...f, kind }] : [];
48
50
  });
@@ -165,7 +167,8 @@ const judgeLayout = (cwd, config, scope, deps, { absent }) => {
165
167
  // refuses even when its size is recorded debt. An absent config's aggregate is no finding.
166
168
  export const judgeTree = (cwd, config, deps = {}, { layout = false, absent = false } = {}) => {
167
169
  const scope = resolveScope(cwd, config, deps);
168
- const measured = new Map(scope.files.map((rel) => [rel, measureFile(cwd, rel, deps)]));
170
+ const bytes = new Map();
171
+ const measured = new Map(scope.files.map((rel) => [rel, measureFile(cwd, rel, deps, (content) => bytes.set(rel, content))]));
169
172
  const projected = new Map(scope.files.map((rel) => [rel, recordFor(measured.get(rel), config.limits)]));
170
173
  const baseline = config.baseline ?? {};
171
174
  const findings = scope.files.flatMap((rel) => fileFindings(rel, measured.get(rel), projected.get(rel), ownEntry(baseline, rel), config.limits));
@@ -178,5 +181,8 @@ export const judgeTree = (cwd, config, deps = {}, { layout = false, absent = fal
178
181
  if (!absent) findings.push(...judgeAggregate(rootLines, config.aggregate ?? {}));
179
182
  const judged = layout ? judgeLayout(cwd, config, scope, deps, { absent }) : null;
180
183
  if (judged) findings.push(...judged.findings);
184
+ const tree = workTreeOf(cwd, config, { scope, bytes, layout }, deps);
185
+ findings.push(...Object.entries(WORK_TREE_KINDS).filter(([part]) => tree[part].length > 0)
186
+ .map(([part, kind]) => ({ kind, severity: WARNING, paths: tree[part] })));
181
187
  return { scope, measured, projected, rootLines, layout: judged, findings };
182
188
  };
@@ -16,18 +16,18 @@
16
16
  // Dependency-free, Node >= 22. No writes, no side effects on import.
17
17
 
18
18
  import { SOURCE_SIZE_CONFIG_REL, SOURCE_SIZE_WARNING_PREFIX, SOURCE_SIZE_WHY, configPathFor, escapeForLine, isLineUnsafe, jsonForLine } from './source-size-refusal.mjs';
19
- import { INITIAL_ADOPTION_REASON, KIT_FOLDER_ROOT, SOURCE_SIZE_SCHEMA, practiceFacts } from './source-size-config.mjs';
19
+ import { KIT_FOLDER_ROOT, SOURCE_SIZE_SCHEMA, practiceFacts } from './source-size-config.mjs';
20
20
  import { SOURCE_SIZE_TOOL_PATH, dqUnsafePath } from './source-size-gate-cmd.mjs';
21
21
  import { hasLoweredRecord, hasStoreRecord, stopsOf, warningsOf } from './source-size-judge.mjs';
22
- import { helpText, isRaise, limitLines } from './source-size/index.mjs';
22
+ import { GROWTH_REASON_PLACEHOLDER, INITIAL_ADOPTION_REASON, helpText, isRaise, limitLines, mintReasonOf } from './source-size/index.mjs';
23
+
24
+ export { GROWTH_REASON_PLACEHOLDER };
23
25
 
24
26
  // The project directory is project-controlled too, so the path every refusal names enters its line
25
27
  // escaped like any other such value. configPathFor itself stays literal — it also builds the real
26
28
  // filesystem path the writer opens.
27
29
  const namedConfig = (cwd) => escapeForLine(configPathFor(cwd));
28
30
 
29
- export const GROWTH_REASON_PLACEHOLDER = '<why this size is accepted>';
30
-
31
31
  // The `_README` the kit's schema-1 template carried, frozen: the move replaces a `_README` byte-equal
32
32
  // to it with the schema-2 text and carries any other verbatim.
33
33
  export const SCHEMA1_TEMPLATE_README = 'Source-size practice: declared scope + thresholds + the recorded ratchet. Authored keys: schema, defaults, roots, exclude, extensions. Machine keys: baseline, aggregate — each recorded entry carries a reason, and a recorded size is debt, not permission. Strict JSON — unknown keys refused.';
@@ -50,13 +50,21 @@ export const statedLimitLines = (config) =>
50
50
 
51
51
  const KIT_FOLDER_LINE = `source-size: NOTE — ${KIT_FOLDER_ROOT} is the kit's own folder, so nothing in it is judged here; the kit's own repository judges its files`;
52
52
 
53
+ const excludedLine = ({ entry, count, carried }) => {
54
+ const lead = `source-size: NOTE — the "exclude" entry "${escapeForLine(entry)}" leaves out`;
55
+ if (count > 0) return `${lead} ${count} tracked path(s) under the declared roots`;
56
+ const literal = `${lead} nothing: an entry is a literal path prefix, never a pattern, and`;
57
+ return carried === 0 ? `${literal} no tracked path carries it` : `${literal} the ${carried} tracked path(s) that carry it lie outside every declared root`;
58
+ };
59
+
53
60
  // What a run does not judge is said once, before its warnings: no extension, no config, no layout,
54
- // and last the kit's own folder.
55
- export const notJudgedLines = (cwd, { absent, config, layout }) => {
61
+ // each exclude entry, and last the kit's own folder.
62
+ export const notJudgedLines = (cwd, { absent, config, layout, excluded = [] }) => {
56
63
  if (absent) return [`source-size: NOTE — ${namedConfig(cwd)} is absent, so the kit's values judge layout alone and no file is judged on lines or bytes`, KIT_FOLDER_LINE];
57
64
  return [
58
65
  ...(config.extensions.length === 0 ? [`source-size: NOTE — ${namedConfig(cwd)} declares no extension, so no file is judged on lines or bytes`] : []),
59
66
  ...(layout ? [] : [`source-size: NOTE — ${namedConfig(cwd)} records no "layout", so entries per directory, depth and files per root are not judged; --write-baseline --layout --reason "<text>" starts it`]),
67
+ ...excluded.map(excludedLine),
60
68
  KIT_FOLDER_LINE,
61
69
  ];
62
70
  };
@@ -72,7 +80,7 @@ const WITHHELD_LINE = 'source-size: no paste-ready command is printed — this p
72
80
  // The withheld fallback is the reader's ONLY remaining instruction, so it has to be the instruction
73
81
  // for what they were actually doing. Sending an adoption to the regenerator would leave them with a
74
82
  // record and no gate — half an adoption, handed over as the way out — so the lane is per MODE.
75
- const WITHHELD_LANE = 'Run the regenerator yourself with the working directory set to this project (source-size-check.mjs --write-baseline, plus --reason "<text>" for any raise), or record each size by hand below.';
83
+ const WITHHELD_LANE = 'Run the regenerator yourself with the working directory set to this project (source-size-check.mjs --write-baseline, plus --reason "<text>" for any raise), or record each size by hand below, your reason in place of the placeholder.';
76
84
  const WITHHELD_ADOPT_LANE = `Run source-size-check.mjs --adopt --reason "${INITIAL_ADOPTION_REASON}" yourself, with the working directory set to this project — it mints the record and declares the gate in one step.`;
77
85
 
78
86
  // → { command, withheld }: exactly one of the two is non-null. ONE renderer for every mode this tool
@@ -113,23 +121,25 @@ const unmintedSentence = (cwd, { state, missing }) => state === 'incomplete'
113
121
  ? `${namedConfig(cwd)} is INCOMPLETE: it carries a machine half no regenerator produces (missing ${missing.map((key) => `"${key}"`).join(', ')}), so the ratchet holds only part of this tree.`
114
122
  : `${namedConfig(cwd)} is AUTHORED but not yet MINTED (it records no size yet), so there is nothing for the ratchet to hold.`;
115
123
  const MINT_LINE = 'Mint it — the regenerator records what this tree already carries; recording a value for the first time is a raise, so it takes a reason';
116
- const UNMINTED_LANE = `Run source-size-check.mjs --write-baseline --reason "${INITIAL_ADOPTION_REASON}" with the working directory set to this project.`;
124
+ const unmintedLane = (reason) => `Run source-size-check.mjs --write-baseline --reason "${reason}" with the working directory set to this project.`;
117
125
 
118
- export const unmintedRefusalLines = (cwd, { state, missing }) => {
119
- const { command, withheld } = regenerator(cwd, INITIAL_ADOPTION_REASON);
126
+ export const unmintedRefusalLines = (cwd, { state, missing, config }) => {
127
+ const reason = mintReasonOf(config);
128
+ const { command, withheld } = regenerator(cwd, reason);
120
129
  return refusal([
121
130
  `source-size: REFUSED — ${unmintedSentence(cwd, { state, missing })}`,
122
131
  `${MINT_LINE}:`,
123
- command === null ? `${withheld} ${UNMINTED_LANE}` : ` ${command}`,
132
+ command === null ? `${withheld} ${unmintedLane(reason)}` : ` ${command}`,
124
133
  ]);
125
134
  };
126
135
 
127
- export const unmintedStopBlock = (cwd, { state, missing }) => {
128
- const { command, withheld } = regenerator(cwd, INITIAL_ADOPTION_REASON);
136
+ export const unmintedStopBlock = (cwd, { state, missing, config }) => {
137
+ const reason = mintReasonOf(config);
138
+ const { command, withheld } = regenerator(cwd, reason);
129
139
  return {
130
140
  failed: escapeLeadingSpace(unmintedSentence(cwd, { state, missing }).slice(0, -1)),
131
141
  findings: [{ place: SOURCE_SIZE_CONFIG_REL, text: MINT_LINE }],
132
- remedies: [command ?? UNMINTED_LANE],
142
+ remedies: [command ?? unmintedLane(reason)],
133
143
  after: refusal(command === null ? [withheld] : []),
134
144
  };
135
145
  };
@@ -148,6 +158,8 @@ const lineSafeFinding = (finding) => ({
148
158
  });
149
159
 
150
160
  const BAND = (f) => `over the limit ${f.allowed} but within its band (up to ${f.ceiling})`;
161
+ const NAMED_PATHS = 3;
162
+ const namedPaths = (paths) => `${paths.slice(0, NAMED_PATHS).map(escapeForLine).join(', ')}${paths.length > NAMED_PATHS ? ` and ${paths.length - NAMED_PATHS} more` : ''}`;
151
163
 
152
164
  // A stop: the regeneration would raise.
153
165
  const FINDING_LINE = Object.freeze({
@@ -177,6 +189,8 @@ const WARNING_LINE = Object.freeze({
177
189
  'dir-stale': (f) => `${f.dir}: ${f.dimension} ${f.actual} is under the recorded ${f.recorded} — the regeneration lowers it`,
178
190
  'dir-obsolete': (f) => (f.actual > f.ceiling ? `${f.dir}: its depth record ${f.recorded} no longer sits on the shallowest directory beyond the depth band — the regeneration removes it` : `${f.dir}: ${f.dimension} ${f.actual} is within its band (up to ${f.ceiling}), so its record is obsolete — the regeneration removes it`),
179
191
  'dir-gone': (f) => `${f.dir}: recorded in "layout"."directories" but no directory the run judges — the regeneration removes it`,
192
+ untracked: (f) => `${f.paths.length} path(s) this run would judge are untracked and not ignored, so the index-based scope did not include them: ${namedPaths(f.paths)}`,
193
+ unstaged: (f) => `${f.paths.length} judged file(s) hold work-tree bytes that differ from the index, and the work tree's bytes are the ones measured: ${namedPaths(f.paths)}`,
180
194
  });
181
195
 
182
196
  export const warningLines = (findings) =>
@@ -220,7 +234,7 @@ export const checkStopBlock = ({ cwd, verdict, absent = false }) => {
220
234
  after: refusal([
221
235
  ...emptyRootLines(verdict), ...warningLines(warnings),
222
236
  ...(command === null ? [withheld] : ['This regeneration RAISES a recorded value, so the reason is REQUIRED — it is recorded in the entry it raises, and it is what the commit message and the CHANGELOG restate.']),
223
- ...(command !== null && entries.length > 0 ? ['Or record each size by hand under "baseline" — the validator accepts exactly these bytes:'] : []),
237
+ ...(command !== null && entries.length > 0 ? ['Or record each size by hand under "baseline" — replace the placeholder with your reason; the validator accepts the rest of these bytes as they are:'] : []),
224
238
  ...entries, ...(hasLoweredRecord(warnings) ? [SPLIT_QUALITY_FOCUS] : []),
225
239
  ]),
226
240
  };
@@ -255,16 +269,19 @@ export const deltaLines = (deltas) => deltas.map(
255
269
  ` ${escapeForLine(target)}: ${dimension} ${from ?? 'none'} → ${to ?? 'none'}${isRaise({ from, to }) ? ' (raise)' : ''}`);
256
270
 
257
271
  // A run that starts the layout record says so in the command it prints, or pasting it would not.
258
- export const reasonRequiredLines = (cwd, deltas, { layout = false } = {}) => {
272
+ const regenerationRefusal = (lead, cwd, deltas, layout) => {
259
273
  const { command, withheld } = regenerator(cwd, GROWTH_REASON_PLACEHOLDER, layout);
260
- const raises = deltas.filter(isRaise).length;
261
- return refusal([
262
- `source-size: REFUSED — this regeneration RAISES ${raises} recorded value(s), and a raise takes a reason (it lands verbatim in the entry it raises, in the commit message and in the CHANGELOG). The whole old→new it would write:`,
263
- ...deltaLines(deltas),
264
- command === null ? `${withheld} ${WITHHELD_LANE}` : ` ${command}`,
265
- ]);
274
+ return refusal([lead, ...deltaLines(deltas), command === null ? `${withheld} ${WITHHELD_LANE}` : ` ${command}`]);
266
275
  };
267
276
 
277
+ export const reasonRequiredLines = (cwd, deltas, { layout = false } = {}) => regenerationRefusal(
278
+ `source-size: REFUSED — this regeneration RAISES ${deltas.filter(isRaise).length} recorded value(s), and a raise takes a reason (it lands verbatim in the entry it raises, in the commit message and in the CHANGELOG). The whole old→new it would write:`,
279
+ cwd, deltas, layout);
280
+
281
+ export const kitSentenceRefusedLines = (cwd, deltas, refused, { layout = false } = {}) => regenerationRefusal(
282
+ `source-size: REFUSED — --reason "${INITIAL_ADOPTION_REASON}" is the kit's own sentence, true only of a record half this write creates, and this regeneration RAISES ${refused} value(s) in a half the config already holds. The whole old→new it would write:`,
283
+ cwd, deltas, layout);
284
+
268
285
  // ── schema 1 and --override ───────────────────────────────────────────────────────────────────────
269
286
 
270
287
  // The check no longer judges schema 1: it names the one move, which the writer makes in its one write.