@sabaiway/agent-workflow-kit 23.7.0 → 23.9.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.
@@ -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
+ };
@@ -15,9 +15,10 @@
15
15
  // Dependency-free, Node >= 22. No side effects on import; the only child process is a read-only git
16
16
  // query, so the read-graph purity suite stays true.
17
17
 
18
- import { lstatSync, readdirSync, readFileSync } from 'node:fs';
19
- import { join } from 'node:path';
18
+ import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
19
+ import { join, relative, sep } from 'node:path';
20
20
  import { spawnSync } from 'node:child_process';
21
+ import { createHash } from 'node:crypto';
21
22
  import { configFail, configPathFor, scopeFail } from './source-size-refusal.mjs';
22
23
  import { KIT_FOLDER_ROOT, WHOLE_TREE_ROOT } from './source-size-config.mjs';
23
24
  import { SPEC_STORE_ROOT, walkSpecStore } from './source-size/index.mjs';
@@ -51,27 +52,65 @@ const bufSegmentPrefix = (path, prefix) =>
51
52
  const bufEndsWith = (path, suffix) =>
52
53
  path.length >= suffix.length && path.subarray(path.length - suffix.length).equals(suffix);
53
54
 
54
- // The enumeration-error class (exit 2) also refuses every git LOCATION but a work tree, by its own
55
- // state name — a redirecting GIT_DIR would otherwise enumerate ANOTHER repository's index in
56
- // silence — and a runner that throws, which is an answer here, never a raw stack.
57
- export const enumerateIndex = (cwd, deps = {}) => {
55
+ const queryGit = (cwd, args, deps, what) => {
58
56
  const spawn = deps.spawn ?? spawnSync;
59
57
  const env = deps.env ?? process.env;
60
58
  const location = resolveGitLocation(cwd, { spawn, env });
61
59
  if (location.state !== 'work-tree') {
62
- throw configFail(`the git index could not be enumerated in ${cwd} (the git location is ${location.state}: ${location.cause}) — the declared scope is unknown, so nothing is judged`);
63
- }
64
- let result;
65
- try {
66
- result = spawn('git', ['ls-files', '-s', '-z'], { cwd, env: withGitPath(env), maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
67
- } catch (err) {
68
- result = { error: err };
60
+ throw configFail(`${what} in ${cwd} (the git location is ${location.state}: ${location.cause}) — the declared scope is unknown, so nothing is judged`);
69
61
  }
62
+ const result = (() => {
63
+ try {
64
+ return spawn('git', args, { cwd, env: withGitPath(env), maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
65
+ } catch (error) {
66
+ return { error };
67
+ }
68
+ })();
70
69
  if (result.error || result.status !== 0) {
71
70
  const why = result.error ? result.error.message : result.signal ? `git was killed by ${result.signal}` : `git exited ${result.status}`;
72
- throw configFail(`the git index could not be enumerated in ${cwd} (${why}) — the declared scope is unknown, so nothing is judged`);
71
+ throw configFail(`${what} in ${cwd} (${why}) — the declared scope is unknown, so nothing is judged`);
73
72
  }
74
- return parseIndexEntries(result.stdout);
73
+ return { stdout: result.stdout, top: location.top };
74
+ };
75
+
76
+ export const enumerateIndex = (cwd, deps = {}) => parseIndexEntries(
77
+ queryGit(cwd, ['ls-files', '-s', '-z'], deps, 'the git index could not be enumerated').stdout);
78
+
79
+ const WORK_TREE_ARGS = Object.freeze(['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignore-submodules=all', '--no-renames']);
80
+ const UNTRACKED_STATUS = '??';
81
+ const INTENT_STATUS = ' A';
82
+ const WORK_TREE_UNCHANGED = ' ';
83
+ const SHA256_HEX_LENGTH = 64;
84
+ const hashBlob = (bytes, oid) => createHash(oid.length === SHA256_HEX_LENGTH ? 'sha256' : 'sha1')
85
+ .update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
86
+ const rulesOf = (config) => ({
87
+ roots: config.roots.map((rel) => ({ rel, buf: Buffer.from(rel, 'utf8') })),
88
+ excludes: config.exclude.map((rel) => Buffer.from(rel, 'utf8')),
89
+ extensions: config.extensions.map((extension) => Buffer.from(extension, 'utf8')),
90
+ });
91
+ const rootOf = ({ roots }, path) => roots.find((root) => root.rel === WHOLE_TREE_ROOT || bufSegmentPrefix(path, root.buf));
92
+ const isExcluded = ({ excludes }, path) => excludes.some((entry) => bufSegmentPrefix(path, entry));
93
+ const isExtended = ({ extensions }, path) => extensions.some((extension) => bufEndsWith(path, extension));
94
+
95
+ export const workTreeOf = (cwd, config, { scope, bytes, layout }, deps = {}) => {
96
+ const { stdout, top } = queryGit(cwd, WORK_TREE_ARGS, deps, "the git work tree's state could not be read");
97
+ const below = relative(realpathSync(top), realpathSync(cwd)).split(sep).join('/');
98
+ const prefix = below === '' ? Buffer.alloc(0) : Buffer.from(`${below}/`, 'utf8');
99
+ const entries = stdout.toString('latin1').split('\0').filter(Boolean)
100
+ .map((record) => ({ status: record.slice(0, 2), path: Buffer.from(record.slice(3), 'latin1') }))
101
+ .filter(({ path }) => path.subarray(0, prefix.length).equals(prefix))
102
+ .map((entry) => ({ ...entry, path: entry.path.subarray(prefix.length) }));
103
+ const rules = rulesOf(config);
104
+ const intents = new Set(entries.filter((entry) => entry.status === INTENT_STATUS).map((entry) => decodeStrict(entry.path)));
105
+ const untracked = entries.filter(({ status, path }) => status === UNTRACKED_STATUS
106
+ && rootOf(rules, path) !== undefined && !isExcluded(rules, path) && !bufSegmentPrefix(path, KIT_FOLDER)
107
+ && (isExtended(rules, path) || (layout && !bufSegmentPrefix(path, SPEC_STORE))))
108
+ .map(({ path }) => path.toString('utf8')).sort();
109
+ const changed = new Set(entries.filter(({ status }) => status !== UNTRACKED_STATUS && status[1] !== WORK_TREE_UNCHANGED)
110
+ .map((entry) => decodeStrict(entry.path)));
111
+ const differing = scope.files.filter((rel) => intents.has(rel)
112
+ || (changed.has(rel) && hashBlob(bytes.get(rel), scope.objectIds.get(rel)) !== scope.objectIds.get(rel)));
113
+ return { untracked, differing };
75
114
  };
76
115
 
77
116
  // resolveScope(cwd, config) → { files: [rel…] sorted, perRoot: Map<root, [rel…]>, layout: Map<root,
@@ -87,18 +126,23 @@ export const resolveScope = (cwd, config, deps = {}) => {
87
126
  if (unmerged.length > 0) {
88
127
  throw scopeFail(`the git index is UNMERGED (${unmerged.length} conflict-stage entr(ies)) — an ambiguous index cannot be judged; resolve the conflict, then re-run`);
89
128
  }
90
- const roots = config.roots.map((rel) => ({ rel, buf: Buffer.from(rel, 'utf8') }));
91
- const excludes = config.exclude.map((rel) => Buffer.from(rel, 'utf8'));
92
- const extensions = config.extensions.map((ext) => Buffer.from(ext, 'utf8'));
129
+ const rules = rulesOf(config);
130
+ const { excludes, extensions } = rules;
131
+ const excluded = config.exclude.map((entry, at) => {
132
+ const carried = entries.filter(({ path }) => bufSegmentPrefix(path, excludes[at]));
133
+ const count = carried.filter(({ path }) => rootOf(rules, path) !== undefined).length;
134
+ return { entry, count, carried: carried.length };
135
+ });
136
+ const objectIds = new Map();
93
137
  const perRoot = new Map(config.roots.map((rel) => [rel, []]));
94
138
  const layout = new Map(config.roots.map((rel) => [rel, []]));
95
139
  const files = [];
96
140
  const kitMatched = new Set();
97
141
  for (const entry of entries) {
98
- const root = roots.find((r) => r.rel === WHOLE_TREE_ROOT || bufSegmentPrefix(entry.path, r.buf));
142
+ const root = rootOf(rules, entry.path);
99
143
  if (!root) continue;
100
- if (excludes.some((ex) => bufSegmentPrefix(entry.path, ex))) continue;
101
- const extended = extensions.some((ext) => bufEndsWith(entry.path, ext));
144
+ if (isExcluded(rules, entry.path)) continue;
145
+ const extended = isExtended(rules, entry.path);
102
146
  if (bufSegmentPrefix(entry.path, KIT_FOLDER)) {
103
147
  if (extended) kitMatched.add(root.rel);
104
148
  continue;
@@ -115,10 +159,11 @@ export const resolveScope = (cwd, config, deps = {}) => {
115
159
  throw scopeFail(`an in-scope tracked path's NAME is not valid UTF-8 (bytes ${entry.path.toString('hex')}) — it cannot be addressed losslessly, so nothing is judged; rename it, or add its prefix to "exclude" in ${configPathFor(cwd)}`);
116
160
  }
117
161
  files.push(rel);
162
+ objectIds.set(rel, entry.sha);
118
163
  perRoot.get(root.rel).push(rel);
119
164
  }
120
165
  // A config declaring no extension judges no file, and the check says so instead of refusing.
121
- if (extensions.length === 0) return { files, perRoot, layout, emptyRoots: [], kitFolderRoots: [] };
166
+ if (extensions.length === 0) return { files, perRoot, layout, emptyRoots: [], kitFolderRoots: [], excluded, objectIds };
122
167
  // A scope the kit's own folder alone matches judges no line, and is no misdeclaration.
123
168
  if (files.length === 0 && kitMatched.size === 0) {
124
169
  throw scopeFail(`the declared scope matches ZERO tracked files (roots: ${config.roots.join(', ')}; extensions: ${config.extensions.join(', ')}) — an empty scope is a misdeclaration, never an empty green; either widen "roots" / "extensions" in ${configPathFor(cwd)}, or track a file the declared scope covers`);
@@ -126,7 +171,7 @@ export const resolveScope = (cwd, config, deps = {}) => {
126
171
  files.sort();
127
172
  for (const list of perRoot.values()) list.sort();
128
173
  const emptyRoots = [...perRoot].filter(([, list]) => list.length === 0).map(([rel]) => rel);
129
- return { files, perRoot, layout, emptyRoots, kitFolderRoots: emptyRoots.filter((rel) => kitMatched.has(rel)) };
174
+ return { files, perRoot, layout, emptyRoots, kitFolderRoots: emptyRoots.filter((rel) => kitMatched.has(rel)), excluded, objectIds };
130
175
  };
131
176
 
132
177
  // specStoreEntries(cwd) → the spec store's entries walked from disk, or null where it is absent. A
@@ -162,7 +207,7 @@ export const countBytes = (buf) => {
162
207
  // measureFile(cwd, rel) → { lines, maxLineBytes }. The judged bytes are the WORKTREE bytes of an
163
208
  // index-visible path; an in-scope file the checker cannot verify is exit 1 naming the exclude lane,
164
209
  // never a silent or green skip.
165
- export const measureFile = (cwd, rel, deps = {}) => {
210
+ export const measureFile = (cwd, rel, deps = {}, observe = () => {}) => {
166
211
  const read = deps.readFile ?? readFileSync;
167
212
  let buf;
168
213
  try {
@@ -173,5 +218,6 @@ export const measureFile = (cwd, rel, deps = {}) => {
173
218
  if (decodeStrict(buf) === null) {
174
219
  throw scopeFail(`${rel}: in-scope but not valid UTF-8 — its size cannot be judged; add its prefix to "exclude" in ${configPathFor(cwd)}`);
175
220
  }
221
+ observe(buf);
176
222
  return countBytes(buf);
177
223
  };