@sabaiway/agent-workflow-kit 23.6.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.
@@ -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 { 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
@@ -87,11 +95,8 @@ const regenerator = (cwd, reason, layout = false) => rendered(cwd, layout ? '--w
87
95
 
88
96
  const SPLIT_QUALITY_FOCUS = 'source-size: REVIEW FOCUS — a recorded size went DOWN or disappeared: check that this is real decomposition and not the same coupling spread across more files (paste this line into the review dispatch focus).';
89
97
 
90
- // Every refusal THIS module renders closes with the canonical WHY. The two thrown classes do not
91
- // carry it — the exit-1 scope refusals (an unverifiable in-scope source file, a non-UTF-8 path, an
92
- // unmerged index, an empty declared scope) and the exit-2 config, usage and enumeration errors: both
93
- // are about a tree the practice could not judge at all, where a sentence about module size explains
94
- // nothing.
98
+ // Rendered refusals close with WHY. Thrown stops and usage refusals carry no WHY line; the command
99
+ // line composes them, each with the remedy of its exit class (usage carries only its help lines).
95
100
  const WHY_LINE = `source-size: WHY — ${SOURCE_SIZE_WHY}`;
96
101
  const refusal = (lines) => [...lines, WHY_LINE];
97
102
 
@@ -112,17 +117,33 @@ export const absentRefusalLines = (cwd) => refusal([
112
117
  // Both not-yet-MINTED states route to the same lane — the regenerator writes the machine half — so
113
118
  // they differ only in what they say happened: AUTHORED is the state a human creates, INCOMPLETE is a
114
119
  // machine half no regenerator produces, which means the file was hand-edited into it.
115
- export const unmintedRefusalLines = (cwd, { state, missing }) => {
116
- const { command, withheld } = regenerator(cwd, INITIAL_ADOPTION_REASON);
120
+ const unmintedSentence = (cwd, { state, missing }) => state === 'incomplete'
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.`
122
+ : `${namedConfig(cwd)} is AUTHORED but not yet MINTED (it records no size yet), so there is nothing for the ratchet to hold.`;
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';
124
+ const unmintedLane = (reason) => `Run source-size-check.mjs --write-baseline --reason "${reason}" with the working directory set to this project.`;
125
+
126
+ export const unmintedRefusalLines = (cwd, { state, missing, config }) => {
127
+ const reason = mintReasonOf(config);
128
+ const { command, withheld } = regenerator(cwd, reason);
117
129
  return refusal([
118
- state === 'incomplete'
119
- ? `source-size: REFUSED — ${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.`
120
- : `source-size: REFUSED — ${namedConfig(cwd)} is AUTHORED but not yet MINTED (it records no size yet), so there is nothing for the ratchet to hold.`,
121
- '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:',
122
- command === null ? `${withheld} Run source-size-check.mjs --write-baseline --reason "${INITIAL_ADOPTION_REASON}" with the working directory set to this project.` : ` ${command}`,
130
+ `source-size: REFUSED — ${unmintedSentence(cwd, { state, missing })}`,
131
+ `${MINT_LINE}:`,
132
+ command === null ? `${withheld} ${unmintedLane(reason)}` : ` ${command}`,
123
133
  ]);
124
134
  };
125
135
 
136
+ export const unmintedStopBlock = (cwd, { state, missing, config }) => {
137
+ const reason = mintReasonOf(config);
138
+ const { command, withheld } = regenerator(cwd, reason);
139
+ return {
140
+ failed: escapeLeadingSpace(unmintedSentence(cwd, { state, missing }).slice(0, -1)),
141
+ findings: [{ place: SOURCE_SIZE_CONFIG_REL, text: MINT_LINE }],
142
+ remedies: [command ?? unmintedLane(reason)],
143
+ after: refusal(command === null ? [withheld] : []),
144
+ };
145
+ };
146
+
126
147
  // Every finding names a path or a root the PROJECT chose, and each one crosses the line-safety
127
148
  // boundary ONCE — in lineSafeFinding, before any branch sees it. Nine branches each remembering to
128
149
  // escape would be nine chances to forget, and the tenth branch nobody has written yet would start
@@ -137,6 +158,8 @@ const lineSafeFinding = (finding) => ({
137
158
  });
138
159
 
139
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` : ''}`;
140
163
 
141
164
  // A stop: the regeneration would raise.
142
165
  const FINDING_LINE = Object.freeze({
@@ -166,6 +189,8 @@ const WARNING_LINE = Object.freeze({
166
189
  'dir-stale': (f) => `${f.dir}: ${f.dimension} ${f.actual} is under the recorded ${f.recorded} — the regeneration lowers it`,
167
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`),
168
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)}`,
169
194
  });
170
195
 
171
196
  export const warningLines = (findings) =>
@@ -183,17 +208,36 @@ const suggestedEntryLines = (verdict) => {
183
208
  });
184
209
  };
185
210
 
186
- // A stop is a raise, so its regeneration always takes the reason.
187
- const servableStep = (cwd, verdict) => {
211
+ export const escapeLeadingSpace = (text) => text.replace(/^ /, '\\u0020');
212
+
213
+ const findingPart = (finding) => {
214
+ const safe = lineSafeFinding(finding);
215
+ const place = safe.rel ?? safe.root ?? safe.dir;
216
+ const line = FINDING_LINE[finding.kind](safe);
217
+ const ownPlace = place === '.' || (place !== 'source-size' && !place.startsWith(' ')
218
+ && !/[\\:]/.test(place) && place.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'));
219
+ return { place: ownPlace ? place : '.', text: escapeLeadingSpace(ownPlace ? line.slice(place.length + 2) : line) };
220
+ };
221
+
222
+ const emptyRootLines = (verdict) => verdict.scope.emptyRoots.map((rel) =>
223
+ `source-size: NOTE — the declared root "${escapeForLine(rel)}" matches no tracked file with a declared extension${verdict.scope.kitFolderRoots.includes(rel) ? ` outside the kit's own folder ${KIT_FOLDER_ROOT}` : ''}`);
224
+
225
+ export const checkStopBlock = ({ cwd, verdict, absent = false }) => {
226
+ const stops = stopsOf(verdict.findings);
227
+ const warnings = warningsOf(verdict.findings);
188
228
  const entries = suggestedEntryLines(verdict);
189
229
  const { command, withheld } = regenerator(cwd, GROWTH_REASON_PLACEHOLDER);
190
- const byHand = entries.length === 0 ? [] : ['Or record each size by hand under "baseline" — the validator accepts exactly these bytes:', ...entries];
191
- if (command === null) return [withheld, WITHHELD_LANE, ...entries];
192
- return [
193
- '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:',
194
- ` ${command}`,
195
- ...byHand,
196
- ];
230
+ return {
231
+ failed: escapeLeadingSpace(`${stops.length} finding(s) ${absent ? `under the kit's values (${namedConfig(cwd)} is absent)` : `against ${namedConfig(cwd)}`}`),
232
+ findings: stops.map(findingPart),
233
+ remedies: [command ?? WITHHELD_LANE],
234
+ after: refusal([
235
+ ...emptyRootLines(verdict), ...warningLines(warnings),
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.']),
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:'] : []),
238
+ ...entries, ...(hasLoweredRecord(warnings) ? [SPLIT_QUALITY_FOCUS] : []),
239
+ ]),
240
+ };
197
241
  };
198
242
 
199
243
  // A lowered or removed record warns with the paste-ready regeneration, which needs no reason.
@@ -202,27 +246,18 @@ const tightenLine = (cwd) => {
202
246
  return `${SOURCE_SIZE_WARNING_PREFIX}a record above is lower or gone, so regenerating lowers or removes it with no reason: ${command ?? `${withheld} ${WITHHELD_LANE}`}`;
203
247
  };
204
248
 
205
- // The order every check prints: its notes, its warnings, then the green line or its stops.
249
+ // A passing check keeps its notes, warnings and green line in that order.
206
250
  export const checkReportLines = ({ cwd, config, verdict, absent = false }) => {
207
- const lines = verdict.scope.emptyRoots.map((rel) =>
208
- `source-size: NOTE — the declared root "${escapeForLine(rel)}" matches no tracked file with a declared extension${verdict.scope.kitFolderRoots.includes(rel) ? ` outside the kit's own folder ${KIT_FOLDER_ROOT}` : ''}`);
209
- const stops = stopsOf(verdict.findings);
251
+ const lines = emptyRootLines(verdict);
210
252
  const warnings = warningsOf(verdict.findings);
211
253
  lines.push(...warningLines(warnings));
212
254
  const lowered = hasLoweredRecord(warnings);
213
- if (stops.length === 0) {
214
- if (lowered || hasStoreRecord(warnings)) lines.push(tightenLine(cwd));
215
- if (lowered) lines.push(SPLIT_QUALITY_FOCUS);
216
- lines.push(warnings.length === 0
217
- ? `source-size: PASS — ${verdict.scope.files.length} in-scope file(s) within the declared caps`
218
- : `source-size: PASS with ${warnings.length} warning(s) — ${verdict.scope.files.length} in-scope file(s) judged and nothing beyond a band or a record; each warning above repeats on every run until it is settled`);
219
- return absent ? lines : [...lines, practiceLine(config)];
220
- }
221
- lines.push(`source-size: FAIL — ${stops.length} finding(s) ${absent ? `under the kit's values (${namedConfig(cwd)} is absent)` : `against ${namedConfig(cwd)}`}:`);
222
- for (const finding of stops) lines.push(` ${FINDING_LINE[finding.kind](lineSafeFinding(finding))}`);
223
- lines.push(...servableStep(cwd, verdict));
255
+ if (lowered || hasStoreRecord(warnings)) lines.push(tightenLine(cwd));
224
256
  if (lowered) lines.push(SPLIT_QUALITY_FOCUS);
225
- return refusal(lines);
257
+ lines.push(warnings.length === 0
258
+ ? `source-size: PASS — ${verdict.scope.files.length} in-scope file(s) within the declared caps`
259
+ : `source-size: PASS with ${warnings.length} warning(s) — ${verdict.scope.files.length} in-scope file(s) judged and nothing beyond a band or a record; each warning above repeats on every run until it is settled`);
260
+ return absent ? lines : [...lines, practiceLine(config)];
226
261
  };
227
262
 
228
263
  // The delta is the DURABLE RECORD on a deployment whose docs/ai is git-hidden: it is what the commit
@@ -234,24 +269,30 @@ export const deltaLines = (deltas) => deltas.map(
234
269
  ` ${escapeForLine(target)}: ${dimension} ${from ?? 'none'} → ${to ?? 'none'}${isRaise({ from, to }) ? ' (raise)' : ''}`);
235
270
 
236
271
  // A run that starts the layout record says so in the command it prints, or pasting it would not.
237
- export const reasonRequiredLines = (cwd, deltas, { layout = false } = {}) => {
272
+ const regenerationRefusal = (lead, cwd, deltas, layout) => {
238
273
  const { command, withheld } = regenerator(cwd, GROWTH_REASON_PLACEHOLDER, layout);
239
- const raises = deltas.filter(isRaise).length;
240
- return refusal([
241
- `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:`,
242
- ...deltaLines(deltas),
243
- command === null ? `${withheld} ${WITHHELD_LANE}` : ` ${command}`,
244
- ]);
274
+ return refusal([lead, ...deltaLines(deltas), command === null ? `${withheld} ${WITHHELD_LANE}` : ` ${command}`]);
245
275
  };
246
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
+
247
285
  // ── schema 1 and --override ───────────────────────────────────────────────────────────────────────
248
286
 
249
287
  // The check no longer judges schema 1: it names the one move, which the writer makes in its one write.
250
- export const schema1StopLines = (cwd) => {
288
+ export const schema1StopBlock = (cwd) => {
251
289
  const { command, withheld } = regenerator(cwd);
252
- return refusal([
253
- `source-size: STOPPED — ${namedConfig(cwd)} is schema 1, which the check no longer judges; --write-baseline moves it to schema 2 in its one write (a raise riding it still takes --reason): ${command ?? `${withheld} Run source-size-check.mjs --write-baseline with the working directory set to this project.`}`,
254
- ]);
290
+ return {
291
+ failed: escapeLeadingSpace(`${namedConfig(cwd)} is schema 1, which the check no longer judges`),
292
+ findings: [{ place: SOURCE_SIZE_CONFIG_REL, text: '--write-baseline moves it to schema 2 in its one write (a raise riding it still takes --reason)' }],
293
+ remedies: [command ?? 'Run source-size-check.mjs --write-baseline with the working directory set to this project.'],
294
+ after: refusal(command === null ? [withheld] : []),
295
+ };
255
296
  };
256
297
 
257
298
  // Claims only what holds of every written file.
@@ -343,56 +384,4 @@ export const writtenLines = ({ cwd, deltas, reason, changed }) => {
343
384
 
344
385
  // ── --help ────────────────────────────────────────────────────────────────────────────────────────
345
386
 
346
- export const HELP = `source-size-check — the declared source-size practice (agent-workflow family).
347
-
348
- Usage:
349
- node source-size-check.mjs --check [--cwd <project-root>]
350
- node source-size-check.mjs --write-baseline [--layout] [--reason "<text>"] [--cwd <project-root>]
351
- node source-size-check.mjs --adopt [--reason "<text>"] [--cwd <project-root>]
352
- node source-size-check.mjs --override <id> [--value <n>] [--tolerance <p>] --reason "<text>" [--cwd <project-root>]
353
- node source-size-check.mjs --override <id> --kit-default --reason "<text>" [--cwd <project-root>]
354
-
355
- Judges every in-scope file against ${SOURCE_SIZE_CONFIG_REL} (schema ${SOURCE_SIZE_SCHEMA}): git-tracked files
356
- under a declared root carrying a declared extension, minus the excluded path-segment prefixes and
357
- the kit's own folder ${KIT_FOLDER_ROOT}, which nothing here judges and no root may declare. An
358
- absent "roots" is the one root ".", every tracked path; a config declaring no extension judges no
359
- file, and every check says so. With the config absent the check judges layout alone under the
360
- kit's values. Symlinks and submodule gitlinks are skipped by kind; an unmerged index, a non-UTF-8
361
- in-scope path, an unverifiable in-scope file and an empty declared scope are refusals.
362
-
363
- Limits: the kit's own five, kept in its code, each with a tolerance; the config holds only a
364
- project's reasoned overrides under "limits". A value at or under its limit is clean, above it within
365
- the band ceil(value x tolerance / 100) a WARNING printed on every run (exit 0), and beyond the band a
366
- stop unless a record holds it. Every --check, --write-baseline and --override run that resolves the
367
- config and ends in no usage, config, enumeration or scope error states all five limits with value,
368
- tolerance and source, then what it does not judge, then its warnings, then its stops.
369
-
370
- Counting: lines, and the longest line in BYTES. A terminator never counts (the CR of a CRLF
371
- included); a last line with no final newline still counts; an empty file is 0 lines. Layout: the
372
- entries of each directory and its depth below its root, over every tracked entry under a declared
373
- root outside the kit's own folder ${KIT_FOLDER_ROOT} plus the spec store docs/ai/specs walked from
374
- disk, and the files of each declared root.
375
-
376
- A recorded entry is DEBT: a finding stops exactly when the regeneration would raise it, and a record
377
- above the tree or gone warns until the regeneration lowers or removes it. Each declared root carries
378
- the same exact ratchet over its summed lines.
379
-
380
- --write-baseline regenerates the machine keys (baseline, aggregate, and layout where it is judged)
381
- from the tree; on an absent config it writes a schema-2 one. --layout starts the layout record on a
382
- present config that has none. The authored keys keep their values and their order; the file is
383
- canonically serialized. A regeneration that RAISES any recorded value needs --reason; the string is
384
- recorded in the entry it raised. A pure tighten needs none. A schema-1 config is moved to schema 2 in
385
- the same write; --check stops on one until it is.
386
-
387
- --adopt is the ONE-line adoption: it mints the record and declares the source-size gate (and NOTHING
388
- else) in docs/ai/gates.json. It is idempotent on an already-adopted project. With the config absent
389
- it refuses with the exact file to author. A refused declaration exits nonzero and reports both
390
- halves: what was minted and what was not declared.
391
-
392
- --override writes one override of a kit limit (lines-per-file, bytes-per-line, entries-per-directory,
393
- depth: --value and/or --tolerance; files-per-root: --tolerance only), or with --kit-default removes
394
- it; an option left out keeps the limit's current value or tolerance, and --reason is mandatory. It
395
- runs only once regenerating the record under the current limits would raise nothing, and
396
- regenerates the record in the same write.
397
-
398
- Exit codes: 0 green, warnings included; 1 a stop or a refusal; 2 usage, config or enumeration error.`;
387
+ export const HELP = helpText({ SOURCE_SIZE_CONFIG_REL, SOURCE_SIZE_SCHEMA, KIT_FOLDER_ROOT });
@@ -0,0 +1,290 @@
1
+ // source-size-runs.mjs — what each mode of the size check does: the check, the writer half
2
+ // (--write-baseline, --override) and the adoption verb. The command line in source-size-check.mjs parses
3
+ // the arguments and composes what a run returns. NOTHING in the read graph imports this module, so the
4
+ // advisor surfaces can ask about the practice without ever reaching a writer (D-18).
5
+ //
6
+ // What --check judges: every in-scope file against the resolved limits with their bands, layout
7
+ // where it is recorded or the config is absent, and every RECORDED size against the ratchet — a
8
+ // record may not grow, and one above the tree or gone warns until the regeneration lowers or removes
9
+ // it. Each declared root carries the same exact ratchet over its summed lines, so splitting one big
10
+ // file into six buys no headroom. An absent config is judged under the kit's values.
11
+ //
12
+ // What --write-baseline does: regenerates the machine keys from the tree, and ONLY the machine keys.
13
+ // The authored half is copied through with its VALUES and their ORDER preserved exactly; the file
14
+ // itself is canonically serialized, so its formatting becomes the writer's (that is what makes a
15
+ // regeneration of an unchanged tree reproduce the same bytes). A regeneration that RAISES any value takes
16
+ // --reason "<text>" — the checker cannot invent the human's reason — and that string lands verbatim
17
+ // in the entry it raises. A pure tighten needs none: shrinking is progress. The printed old→new
18
+ // delta is the durable record where docs/ai is git-hidden; it is what the commit message carries.
19
+ //
20
+ // What --adopt does: mints the record and declares the gate — the whole adoption as ONE consented
21
+ // line, because the alternative is a two-step ceremony whose halves can be left half-done. It
22
+ // composes the two writers it already has (this module's mint, the fill's consented apply restricted
23
+ // to this one id) and owns no write of its own, but for the schema-1 move of a minted config, which
24
+ // carries both records verbatim.
25
+ //
26
+ // What --override does: once a regeneration under the current limits would raise nothing, writes or
27
+ // removes one reasoned override of a kit limit and regenerates the machine keys under the new limits
28
+ // in the same write. Every write here moves a schema-1 config to schema 2; --check stops on one.
29
+ //
30
+ //
31
+ // Dependency-free, Node >= 22. No side effects on import.
32
+
33
+ import { composeRedBlock } from '../references/scripts/shared/index.mjs';
34
+ import { assertDocsAiDeployment, writeDocsAiFileAtomic } from './atomic-write.mjs';
35
+ import {
36
+ KIT_LIMITS,
37
+ SOURCE_SIZE_CONFIG_REL,
38
+ SOURCE_SIZE_GATE_ID,
39
+ SOURCE_SIZE_SCHEMA,
40
+ applyOverride,
41
+ assertNoStoreRoot,
42
+ checkTargetOf,
43
+ isRaise,
44
+ loadSourceSizeConfig,
45
+ matchesSourceSizeGate,
46
+ materialize,
47
+ migrateSchema1,
48
+ planRecord,
49
+ refusedRaises,
50
+ scopeFail,
51
+ serialize,
52
+ validateSourceSizeConfig,
53
+ } from './source-size-core.mjs';
54
+ import { bandWarningsOf, judgeTree, standingWarningsOf, stopsOf } from './source-size-judge.mjs';
55
+ import { GATES_REL, loadDeclaration } from './gates-declaration.mjs';
56
+ import { applyFill } from './gates-init.mjs';
57
+ import {
58
+ TEMPLATE_README,
59
+ TEMPLATE_READMES,
60
+ absentRefusalLines,
61
+ adoptAbsentRefusalLines,
62
+ checkReportLines, checkStopBlock,
63
+ gateAlreadyDeclaredLines,
64
+ gateDeclaredLines,
65
+ gateRefusedLines,
66
+ kitSentenceRefusedLines,
67
+ overrideOutgrownLines,
68
+ overrideUnchangedLines,
69
+ overrideWrittenLines,
70
+ reasonRequiredLines,
71
+ recordNoLongerHoldsLines,
72
+ recordRecognizedLines,
73
+ schema1MovedLines, schema1StopBlock,
74
+ unmintedRefusalLines, unmintedStopBlock,
75
+ warningLines,
76
+ writtenLines,
77
+ } from './source-size-report.mjs';
78
+
79
+ export const ERROR_PREFIX = '[agent-workflow-kit] ';
80
+ export const CHECKER_NAME = 'source-size';
81
+ export const USAGE_REFUSAL = Symbol('usage refusal');
82
+ export const usageFail = (message) => Object.assign(new Error(`${ERROR_PREFIX}${message}`), { exitCode: 2, [USAGE_REFUSAL]: true });
83
+ const RECORD_NOUN = 'the source-size record';
84
+ 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; no record was regenerated.';
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.
91
+ export const runCheck = ({ cwd, deps = {} }) => {
92
+ const target = checkTargetOf({ loaded: loadSourceSizeConfig(cwd, deps), absentConfig: validateSourceSizeConfig(ABSENT) });
93
+ const { config, judged } = target;
94
+ if (target.stop === 'schema-1') return { code: 1, block: schema1StopBlock(cwd), config };
95
+ if (target.stop === 'unminted') return { code: 1, block: unmintedStopBlock(cwd, { state: target.state, missing: target.missing, config }), config };
96
+ const verdict = judgeTree(cwd, config, deps, judged);
97
+ const report = { cwd, config, verdict, absent: judged.absent };
98
+ return stopsOf(verdict.findings).length > 0 ? { code: 1, block: checkStopBlock(report), config, judged, scope: verdict.scope }
99
+ : { code: 0, lines: checkReportLines(report), config, judged, scope: verdict.scope };
100
+ };
101
+
102
+ // ── the writer ────────────────────────────────────────────────────────────────────────────────────
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);
107
+
108
+ // What a move says it did, read off the moved config itself.
109
+ const movedLines = (cwd, parsed) => (parsed.schema === 1 ? schema1MovedLines(cwd) : []);
110
+
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)) };
120
+ };
121
+
122
+ const writeRefusalOf = ({ cwd, plan, reason, config, minted, starts }) => {
123
+ const plain = starts && minted ? plan.deltas.filter((delta) => !plan.layout.deltas.includes(delta)) : [];
124
+ if (plain.some(isRaise)) return [LAYOUT_GROWTH_LEAD, ...reasonRequiredLines(cwd, plain)];
125
+ if (plan.raises.length > 0 && reason === undefined) return reasonRequiredLines(cwd, plan.deltas, { layout: starts });
126
+ const refused = refusedRaises({ plan, config, reason });
127
+ return refused.length > 0 ? kitSentenceRefusedLines(cwd, plan.deltas, refused.length, { layout: starts }) : null;
128
+ };
129
+
130
+ // Layout is regenerated wherever it is judged; --layout starts it on a present config with none, and
131
+ // changes nothing on one that records layout or is absent.
132
+ export const runWriteBaseline = ({ cwd, reason, layout = false, deps = {} }) => {
133
+ // Checked BEFORE the config is read, so a project that was never deployed hears about the
134
+ // deployment rather than about a file it has no place to put.
135
+ assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
136
+ const loaded = loadSourceSizeConfig(cwd, deps);
137
+ const absent = loaded.state === 'absent';
138
+ const parsed = absent ? ABSENT : loaded.parsed;
139
+ const config = absent ? validateSourceSizeConfig(parsed) : loaded.config;
140
+ if (layout && !absent && config.layout === null) assertNoStoreRoot(config.roots);
141
+ const judged = { absent, layout: absent || layout || config.layout !== null };
142
+ const { verdict, plan, bandWarnings, warnings } = judgeForWrite(cwd, config, deps, judged);
143
+ const scope = verdict.scope;
144
+ const minted = loaded.state === 'minted';
145
+ const refused = writeRefusalOf({ cwd, plan, reason, config, minted, starts: layout && !absent && config.layout === null });
146
+ if (refused !== null) {
147
+ const moved = minted && config.schema === 1 ? moveMinted(cwd, parsed, deps) : [];
148
+ return { code: 1, lines: [...bandWarnings, ...moved, ...refused], config, judged, scope };
149
+ }
150
+ const body = serialize(schema2Of(parsed), materialize(plan, reason));
151
+ // Whether anything was written is decided by the BYTES, not by the delta count: completing a
152
+ // hand-edited half record changes the file while raising nothing at all.
153
+ const changed = body !== loaded.text;
154
+ if (changed) writeRecord(cwd, body, deps);
155
+ const written = writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed });
156
+ return { code: 0, lines: [...warnings, ...movedLines(cwd, parsed), ...written], config, judged, scope };
157
+ };
158
+
159
+ // --override: the projection under the CURRENT limits comes first, so an override's reason never
160
+ // lands on drift it did not cause; only then is the override applied and the record regenerated
161
+ // under the new limits, in the same atomic write.
162
+ export const runOverride = ({ cwd, id, value, tolerance, kitDefault, reason, deps = {} }) => {
163
+ assertDocsAiDeployment(cwd, deps, { stop: scopeFail, rel: SOURCE_SIZE_CONFIG_REL, noun: RECORD_NOUN });
164
+ const { state, config, parsed, text, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
165
+ if (state === 'absent') return { code: 1, lines: absentRefusalLines(cwd) };
166
+ if (state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys, config }), config };
167
+ const judged = { absent: false, layout: config.layout !== null };
168
+ const current = judgeForWrite(cwd, config, deps, judged);
169
+ const scope = current.verdict.scope;
170
+ if (current.plan.raises.length > 0) return { code: 1, lines: [...current.bandWarnings, ...overrideOutgrownLines(cwd, current.plan.deltas)], config, judged, scope };
171
+ const resolved = config.limits[id];
172
+ const filled = kitDefault ? null : { value: value ?? resolved.value, tolerance: tolerance ?? resolved.tolerance, reason };
173
+ const kit = KIT_LIMITS[id];
174
+ if (filled !== null && filled.tolerance === kit.tolerance && (kit.value === null || filled.value === kit.value)) {
175
+ 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`);
176
+ }
177
+ const next = applyOverride(schema2Of(parsed), id, filled);
178
+ const nextConfig = validateSourceSizeConfig(next);
179
+ const { plan, warnings } = judgeForWrite(cwd, nextConfig, deps, judged);
180
+ const body = serialize(next, materialize(plan, reason));
181
+ if (body === text) return { code: 0, lines: [...warnings, ...overrideUnchangedLines(cwd, id)], config: nextConfig, judged, scope };
182
+ writeRecord(cwd, body, deps);
183
+ return {
184
+ code: 0,
185
+ judged,
186
+ scope,
187
+ lines: [
188
+ ...warnings,
189
+ ...overrideWrittenLines({ cwd, id, removed: kitDefault, reason }),
190
+ ...movedLines(cwd, parsed),
191
+ ...(plan.deltas.length === 0 ? [] : writtenLines({ cwd, deltas: plan.deltas, reason: plan.raises.length > 0 ? reason : undefined, changed: true })),
192
+ ],
193
+ config: nextConfig,
194
+ };
195
+ };
196
+
197
+ // ── the adoption verb (D-16) ──────────────────────────────────────────────────────────────────────
198
+
199
+ // Declaring the gate is delegated to the FILL's own consented apply, restricted to this one id: the
200
+ // fill owns every rule about what a written declaration may look like (placement, id collisions, the
201
+ // coverage invariant, the atomic write), and a second writer here would be a second set of those
202
+ // rules — the one that drifts. `--adopt` is therefore a composition, never a re-implementation.
203
+ //
204
+ // The already-declared arm is checked FIRST and through the practice's own matcher: an earlier
205
+ // partial run leaves a minted record and a declared gate, and re-running must converge rather than
206
+ // collide. A gate that merely CARRIES the id without being this checker does not count — it reaches
207
+ // the fill and collides there, loudly, which is the honest answer to a squatter.
208
+ // The READ is inside the try with the write, deliberately: by the time this runs the record is
209
+ // already minted, so ANY failure here — a malformed declaration the reader throws on, just as much
210
+ // as a collision the fill refuses — must still report both halves. Letting the read escape would
211
+ // surface a bare error carrying neither the mint that succeeded nor the exit contract this tool
212
+ // documents.
213
+ const declareGate = (cwd, deps) => {
214
+ try {
215
+ applyFill({ cwd, onlyIds: [SOURCE_SIZE_GATE_ID] }, deps);
216
+ return { code: 0, lines: gateDeclaredLines(GATES_REL, SOURCE_SIZE_GATE_ID) };
217
+ } catch (err) {
218
+ return { code: 1, lines: gateRefusedLines(GATES_REL, err?.message ?? String(err)) };
219
+ }
220
+ };
221
+
222
+ // Is the canonical gate ALREADY there? Asked through the practice's own matcher, so a gate that
223
+ // merely carries the id — running something else entirely — never reads as adopted; it reaches the
224
+ // fill and collides there, loudly, which is the honest answer to a squatter.
225
+ //
226
+ // An unreadable declaration is NOT a verdict here. This read is a shortcut, and aborting on it would
227
+ // report an outcome before the record was settled; the fill re-reads the same file and refuses
228
+ // authoritatively AFTER, so the partial report names both halves truthfully.
229
+ const gateIsDeclared = (cwd, deps) => {
230
+ try {
231
+ const declaration = loadDeclaration(cwd, deps);
232
+ return (declaration.outcome === 'loaded' ? declaration.gates : []).some((gate) => matchesSourceSizeGate(gate.cmd, cwd));
233
+ } catch {
234
+ return false;
235
+ }
236
+ };
237
+
238
+ // A MINTED record is RECOGNIZED, never regenerated. Adoption carries a PINNED reason — the advisor
239
+ // renders it as a fixed string, and its item keeps firing while the gate is undeclared — so a
240
+ // re-run after a partial adoption would let that one sentence raise whatever the tree grew in the
241
+ // meantime. That is exactly the laundering the reason requirement exists to prevent, so the verb
242
+ // asks the checker instead: a record that no longer holds is a ratchet question with its own
243
+ // reasoned lane, and it must be answered BEFORE a gate is declared over it — declaring one that is
244
+ // certain to red the matrix is what the offer rules refuse everywhere else.
245
+ const recognizeRecord = ({ cwd, deps }) => {
246
+ const verdict = runCheck({ cwd, deps });
247
+ if (verdict.code !== 0) return { code: verdict.code, lines: [...composeRedBlock({ name: CHECKER_NAME, ...verdict.block }), ...recordNoLongerHoldsLines(GATES_REL)] };
248
+ return { code: 0, lines: recordRecognizedLines(cwd) };
249
+ };
250
+
251
+ // A MINTED schema-1 config is moved in its own write before adoption reads it as schema 2: the
252
+ // authored half transformed, both machine records carried verbatim, nothing regenerated — so the
253
+ // adoption reason can never ride a raise. An authored or incomplete one is moved by the mint itself.
254
+ const moveMinted = (cwd, parsed, deps) => {
255
+ writeRecord(cwd, serialize(schema2Of(parsed), { baseline: parsed.baseline, aggregate: parsed.aggregate }), deps);
256
+ return movedLines(cwd, parsed);
257
+ };
258
+
259
+ // A stop after the move still prints the move: the write happened, and no stop may hide it.
260
+ const reportingMove = (moved, run) => {
261
+ try {
262
+ return run();
263
+ } catch (err) {
264
+ throw Object.assign(err, { lines: [...moved, ...(err.lines ?? [])] });
265
+ }
266
+ };
267
+
268
+ // --adopt = settle the record, then declare the gate. The order is not a preference: the fill offers
269
+ // the gate ONLY over a minted config (declaring it earlier would declare a gate that refuses), so
270
+ // the record is what makes the declaration offerable at all.
271
+ export const runAdopt = ({ cwd, reason, deps = {} }) => {
272
+ const { state, config, parsed } = loadSourceSizeConfig(cwd, deps);
273
+ if (state === 'absent') return { code: 1, lines: adoptAbsentRefusalLines(cwd) };
274
+ const moved = state === 'minted' && config.schema === 1 ? moveMinted(cwd, parsed, deps) : [];
275
+ // ADOPTED is asked FIRST, and it is a question about the GATE alone. Idempotence cannot be made
276
+ // conditional on the record still holding: a declared gate reports its own staleness on every run,
277
+ // with the reasoned lane, and stopping here would tell a reader the gate was not declared while it
278
+ // plainly is — which is exactly what re-running the advisor's one-liner on a drifted tree does.
279
+ // Once the gate is there and the record is minted, nothing is left to adopt.
280
+ const declared = gateIsDeclared(cwd, deps);
281
+ if (declared && state === 'minted') return { code: 0, lines: [...moved, ...gateAlreadyDeclaredLines(GATES_REL)] };
282
+ // Either half carries its OWN self-servable refusals (a raise with no reason, a project with no
283
+ // docs/ai, a record the tree outgrew). They are returned unchanged: re-wording them here would be
284
+ // the second practice this module exists to avoid, and each already names the step that clears it.
285
+ const record = state === 'minted' ? reportingMove(moved, () => recognizeRecord({ cwd, deps })) : runWriteBaseline({ cwd, reason, deps });
286
+ if (record.code !== 0) return { code: record.code, lines: [...moved, ...record.lines] };
287
+ if (declared) return { code: 0, lines: [...moved, ...record.lines, ...gateAlreadyDeclaredLines(GATES_REL)] };
288
+ const gate = declareGate(cwd, deps);
289
+ return { code: gate.code, lines: [...moved, ...record.lines, ...gate.lines] };
290
+ };