@sabaiway/agent-workflow-kit 14.38.0 → 14.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/README.md +2 -1
- package/SKILL.md +5 -1
- package/capability.json +1 -1
- package/package.json +1 -1
- package/references/advisor-writers.md +1 -0
- package/references/modes/gates.md +1 -1
- package/references/modes/procedures.md +1 -1
- package/references/modes/recommendations.md +1 -1
- package/references/modes/rules.md +24 -0
- package/references/modes/upgrade.md +7 -7
- package/references/shared/composition-handoff.md +2 -2
- package/references/templates/architecture.md +5 -20
- package/tools/commands.mjs +7 -0
- package/tools/gates-init.mjs +17 -8
- package/tools/inject-methodology.mjs +16 -16
- package/tools/procedures.mjs +9 -2
- package/tools/project-rules/index.mjs +1 -0
- package/tools/project-rules/memory-map-row.mjs +62 -0
- package/tools/recommendations.mjs +25 -11
- package/tools/run-gates.mjs +13 -3
- package/tools/source-size/index.mjs +30 -0
- package/tools/source-size/layout.mjs +136 -0
- package/tools/source-size/limits.mjs +110 -0
- package/tools/source-size/record.mjs +143 -0
- package/tools/source-size-check.mjs +192 -127
- package/tools/source-size-config.mjs +92 -27
- package/tools/source-size-core.mjs +27 -0
- package/tools/source-size-judge.mjs +143 -77
- package/tools/source-size-refusal.mjs +8 -3
- package/tools/source-size-report.mjs +182 -46
- package/tools/source-size-scope.mjs +31 -6
- package/tools/write-lanes.mjs +1 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// The Memory Map row of each theme in a deployed AGENTS.md: a pure text leaf that reads and writes
|
|
2
|
+
// nothing; inject-methodology.mjs reconcile calls it and stays the file's one writer.
|
|
3
|
+
// Contract: docs/ai/specs/kit/project-rules/memory-map-row.md.
|
|
4
|
+
|
|
5
|
+
import { THEMES, themePaths } from './themes.mjs';
|
|
6
|
+
|
|
7
|
+
// The row texts a release shipped, append-only: a release that changes a row's text first appends
|
|
8
|
+
// the outgoing one here.
|
|
9
|
+
export const MEMORY_MAP_PRIOR_ROWS = Object.freeze([]);
|
|
10
|
+
|
|
11
|
+
const ANCHOR_PATH = 'docs/ai/agent_rules.md';
|
|
12
|
+
const opening = (path) => `| [\`${path}\`](./${path}) |`;
|
|
13
|
+
const rowOf = (theme) => {
|
|
14
|
+
const { effective } = themePaths(theme.name);
|
|
15
|
+
return `${opening(effective)} ${theme.readWhen} | Only through \`/agent-workflow-kit rules\` |`;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// The lines of a text, each keeping its own ending, so joining them gives the text back byte for byte.
|
|
19
|
+
const splitLines = (text) => text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
20
|
+
const bodyOf = (line) => line.replace(/\r?\n$/, '');
|
|
21
|
+
const endingOf = (line) => line.slice(bodyOf(line).length);
|
|
22
|
+
// A table line that does not close its last cell goes on over the next line.
|
|
23
|
+
const isWhole = (line) => bodyOf(line).trimEnd().endsWith('|');
|
|
24
|
+
|
|
25
|
+
// placeAfter(lines, i, row) → the lines with row on the line after i, taking line i's ending.
|
|
26
|
+
const placeAfter = (lines, i, row) => {
|
|
27
|
+
const ending = endingOf(lines[i]);
|
|
28
|
+
if (ending !== '') return lines.toSpliced(i + 1, 0, `${row}${ending}`);
|
|
29
|
+
return lines.toSpliced(i, 1, `${lines[i]}\n`, row);
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// reconcileMemoryMapRows(text, { maxLines, priors }) → { text, outcomes }: one outcome
|
|
33
|
+
// { theme, status, note } per registry theme in registry order, status inserted, kept, refreshed or
|
|
34
|
+
// skipped; a skipped theme changes no byte and its note names the reason.
|
|
35
|
+
export const reconcileMemoryMapRows = (text, { maxLines, priors = MEMORY_MAP_PRIOR_ROWS } = {}) => {
|
|
36
|
+
let lines = splitLines(text);
|
|
37
|
+
let last = -1;
|
|
38
|
+
const outcomes = [];
|
|
39
|
+
for (const theme of THEMES) {
|
|
40
|
+
const row = rowOf(theme);
|
|
41
|
+
const answer = (status, note = '') => outcomes.push({ theme: theme.name, status, note });
|
|
42
|
+
const at = lines.findIndex((line) => line.startsWith(opening(themePaths(theme.name).effective)));
|
|
43
|
+
if (at !== -1) {
|
|
44
|
+
if (priors.includes(bodyOf(lines[at]))) {
|
|
45
|
+
lines = lines.with(at, `${row}${endingOf(lines[at])}`);
|
|
46
|
+
answer('refreshed');
|
|
47
|
+
} else answer('kept');
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const anchor = last !== -1 ? last : lines.findIndex((line) => line.startsWith(opening(ANCHOR_PATH)));
|
|
51
|
+
if (anchor === -1) answer('skipped', `the Memory Map has no ${ANCHOR_PATH} row to place it after`);
|
|
52
|
+
else if (!isWhole(lines[anchor])) answer('skipped', `the Memory Map's ${ANCHOR_PATH} row spans more than one line`);
|
|
53
|
+
else if (maxLines != null && lines.length + 1 > maxLines) {
|
|
54
|
+
answer('skipped', `adding it would take the file past its ${maxLines}-line limit`);
|
|
55
|
+
} else {
|
|
56
|
+
lines = placeAfter(lines, anchor, row);
|
|
57
|
+
last = anchor + 1;
|
|
58
|
+
answer('inserted');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { text: lines.join(''), outcomes };
|
|
62
|
+
};
|
|
@@ -183,6 +183,8 @@ export const SEVERITIES = Object.freeze({
|
|
|
183
183
|
// acknowledgment. An id SQUATTER is the opposite: the id says adopted while nothing measures size.
|
|
184
184
|
'source-size.adopted-elsewhere': SEVERITY_OPTIONAL,
|
|
185
185
|
'source-size.id-squatter': SEVERITY_ATTENTION,
|
|
186
|
+
// A minted schema-1 config is a record the check stops on until the writer moves it.
|
|
187
|
+
'source-size.schema-1': SEVERITY_ATTENTION,
|
|
186
188
|
'gate-hook': SEVERITY_OPTIONAL,
|
|
187
189
|
// A placed hook that predates the marker key goes DARK on a marker-carrying declaration (unknown
|
|
188
190
|
// key → auto-approval off), so a CONFIGURED capability silently stops working: attention, not an
|
|
@@ -278,7 +280,8 @@ export const WHATS = Object.freeze({
|
|
|
278
280
|
'gates-inert.producer-unrecognized': 'the coverage checker ({id}) has NO producer declared and none offerable, on a tree the changed-line domain barely reaches',
|
|
279
281
|
'gates-inert.coverage-domain-narrow': 'certification covers the assessable minority only — {ext} dominate(s) the tracked tree, and the changed-line domain excludes them',
|
|
280
282
|
'source-size': 'no source-size gate — module size drifts unmeasured, and an over-cap file is invisible instead of recorded debt',
|
|
281
|
-
'source-size.unminted': 'the source-size gate is declared
|
|
283
|
+
'source-size.unminted': 'the source-size gate is declared over an unminted record ({state}) — the check refuses it, or if absent judges layout alone, no line',
|
|
284
|
+
'source-size.schema-1': 'the source-size config is schema 1, which the check stops on — the writer moves it to schema 2 in one write',
|
|
282
285
|
'source-size.adopted-elsewhere': "the source-size gate runs a DIFFERENT copy of this checker ({n} declared) — adopted here, just not through this kit's own tool",
|
|
283
286
|
'source-size.id-squatter': 'a gate carries the source-size id but is not this checker — the practice reads as declared while nothing measures module size',
|
|
284
287
|
'gate-hook': '{n} declared gate(s) prompt per run — the gate-approval hook is not wired',
|
|
@@ -830,10 +833,10 @@ export const probeGatesInert = ({ root, deps, add, skip }) => {
|
|
|
830
833
|
};
|
|
831
834
|
|
|
832
835
|
// The SOURCE-SIZE offer (baseline-practices Plan 1). This is the practice's ONE discovery lane: the
|
|
833
|
-
// checker ships with the kit and
|
|
834
|
-
// item a deployment would never learn the practice exists — the same
|
|
835
|
-
// the capability registry was built for. New and existing deployments
|
|
836
|
-
// the advisor section is mandatory at every upgrade.
|
|
836
|
+
// checker ships with the kit and, until a project declares its own scope, judges no file's lines, so
|
|
837
|
+
// without this item a deployment would never learn the practice exists — the same
|
|
838
|
+
// OPT-IN-SHIPS-INVISIBLE failure the capability registry was built for. New and existing deployments
|
|
839
|
+
// meet it identically, because the advisor section is mandatory at every upgrade.
|
|
837
840
|
//
|
|
838
841
|
// The probe asks what each declared cmd CLAIMS about this checker, in the three named outcomes —
|
|
839
842
|
// because the boolean it used to ask made a DELIBERATELY VENDORED copy read as "no source-size gate
|
|
@@ -845,11 +848,22 @@ export const probeGatesInert = ({ root, deps, add, skip }) => {
|
|
|
845
848
|
//
|
|
846
849
|
// Precedence over a MIXED declaration is pinned and deterministic: any canonical match answers the
|
|
847
850
|
// practice question outright; else any tool-elsewhere claim; else the id collision; else the offer.
|
|
851
|
+
// A MINTED schema-1 config is asked first, ahead of the gate arms: the check stops on it whatever is
|
|
852
|
+
// declared. Its line carries no reason, since a pinned one would launder a raise; an unreadable
|
|
853
|
+
// config keeps today's arms, which report it.
|
|
854
|
+
const schema1Minted = (root, deps) => {
|
|
855
|
+
try { const { state, config } = loadSourceSizeConfig(root, deps); return state === 'minted' && config.schema === 1; } catch { return false; }
|
|
856
|
+
};
|
|
857
|
+
|
|
848
858
|
const probeSourceSize = ({ root, deps, add, skip }) => {
|
|
849
859
|
try {
|
|
860
|
+
const tool = toolPath('source-size-check.mjs');
|
|
861
|
+
if (schema1Minted(root, deps)) {
|
|
862
|
+
add('source-size', fillTemplate(WHATS['source-size.schema-1'], {}), `node ${q(tool)} --write-baseline --cwd ${q(root)}`, 'source-size.schema-1');
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
850
865
|
const declaration = loadDeclaration(root, deps);
|
|
851
866
|
const gates = declaration.outcome === 'loaded' ? declaration.gates : [];
|
|
852
|
-
const tool = toolPath('source-size-check.mjs');
|
|
853
867
|
// The reason string is PINNED, not composed: it is copied unchanged into every entry the first
|
|
854
868
|
// mint records, and a first mint records the whole tree — so "this is what the tree already
|
|
855
869
|
// carried when the practice arrived" is the one sentence that is true of all of them.
|
|
@@ -858,11 +872,11 @@ const probeSourceSize = ({ root, deps, add, skip }) => {
|
|
|
858
872
|
const canonical = claims.filter((c) => c.claim === CHECKER_CLAIM.CANONICAL);
|
|
859
873
|
const elsewhere = claims.filter((c) => c.claim === CHECKER_CLAIM.ELSEWHERE);
|
|
860
874
|
if (canonical.length > 0 || elsewhere.length > 0) {
|
|
861
|
-
// A DECLARED gate is not the same fact as a working one: the checker refuses
|
|
862
|
-
//
|
|
863
|
-
//
|
|
864
|
-
// nothing about the one thing
|
|
865
|
-
// outcome, its attention class and its immunity to every ack are the same whichever copy runs.
|
|
875
|
+
// A DECLARED gate is not the same fact as a working one: the checker refuses an authored or
|
|
876
|
+
// half-written record, so a gate declared over one reds the matrix on every run, and over an
|
|
877
|
+
// absent one it judges layout alone and no line. The declaration alone would report that deployment
|
|
878
|
+
// as adopted and say nothing about the one thing wrong with it. The split changes NOTHING here —
|
|
879
|
+
// the outcome, its attention class and its immunity to every ack are the same whichever copy runs.
|
|
866
880
|
const { state } = loadSourceSizeConfig(root, deps);
|
|
867
881
|
if (state !== 'minted') {
|
|
868
882
|
// Only the way OUT differs. With the gate declared through another copy, `--adopt` would
|
package/tools/run-gates.mjs
CHANGED
|
@@ -72,6 +72,7 @@ import {
|
|
|
72
72
|
// token this runner records) — run-gates already imports core-evidence, so a shared home is the
|
|
73
73
|
// only direction that has no cycle. Re-exported here: this module is the vocabulary's public face.
|
|
74
74
|
import { COVERAGE } from './coverage-state.mjs';
|
|
75
|
+
import { CHECKER_CLAIM, SOURCE_SIZE_WARNING_PREFIX, classifySourceSizeGate } from './source-size-core.mjs';
|
|
75
76
|
|
|
76
77
|
export { GATES_REL, loadDeclaration, validateDeclaration, canonicalCheckerGates, isFinalCapableDeclaration, isReviewDependentGate };
|
|
77
78
|
export { COVERAGE };
|
|
@@ -227,8 +228,16 @@ export const BASH_PROBE_CMD = 'true';
|
|
|
227
228
|
const formatSeconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
|
|
228
229
|
const trimTrailingNewline = (text) => text.replace(/\n$/, '');
|
|
229
230
|
|
|
230
|
-
//
|
|
231
|
-
//
|
|
231
|
+
// A green source-size check's warnings print on every run, so the matrix echoes them — and nothing
|
|
232
|
+
// else of its output — under a gate running this checker or a regular-file copy of it elsewhere.
|
|
233
|
+
const SOURCE_SIZE_CLAIMS = new Set([CHECKER_CLAIM.CANONICAL, CHECKER_CLAIM.ELSEWHERE]);
|
|
234
|
+
const sourceSizeWarnings = (gate, cwd, stdout) => (SOURCE_SIZE_CLAIMS.has(classifySourceSizeGate(gate.cmd, cwd))
|
|
235
|
+
? String(stdout).split(/\r?\n/).filter((line) => line.startsWith(SOURCE_SIZE_WARNING_PREFIX))
|
|
236
|
+
: []);
|
|
237
|
+
|
|
238
|
+
// Run the selected gates sequentially (declaration order). A green gate logs one PASS line (and a
|
|
239
|
+
// source-size check its warnings); a failing gate logs FAIL + its captured stdout/stderr VERBATIM
|
|
240
|
+
// (triage without re-running).
|
|
232
241
|
export const runGates = (gates, { cwd, spawn = spawnGateViaBash, now = Date.now, log = console.log }) => {
|
|
233
242
|
const results = [];
|
|
234
243
|
for (const gate of gates) {
|
|
@@ -242,6 +251,7 @@ export const runGates = (gates, { cwd, spawn = spawnGateViaBash, now = Date.now,
|
|
|
242
251
|
results.push({ id: gate.id, title: gate.title, ok, code, elapsedMs, stdout: res.stdout ? String(res.stdout) : '' });
|
|
243
252
|
if (ok) {
|
|
244
253
|
log(` PASS (${formatSeconds(elapsedMs)})`);
|
|
254
|
+
for (const line of sourceSizeWarnings(gate, cwd, res.stdout ?? '')) log(line);
|
|
245
255
|
} else {
|
|
246
256
|
log(` FAIL exit=${code} (${formatSeconds(elapsedMs)})`);
|
|
247
257
|
if (res.stdout) log(trimTrailingNewline(res.stdout));
|
|
@@ -797,7 +807,7 @@ export const runCli = (argv, deps = {}) => {
|
|
|
797
807
|
}
|
|
798
808
|
}
|
|
799
809
|
}
|
|
800
|
-
// A green gate's stdout is
|
|
810
|
+
// A green gate's stdout is not echoed but for a source-size check's warnings — the table IS the report. The row above
|
|
801
811
|
// now names the withheld verdict; this block adds the checker's OWN words and the remedy, so a
|
|
802
812
|
// plain run never leaves a PASS standing for a coverage claim that was never made. Only that.
|
|
803
813
|
if (!opts.final && coverage.state === COVERAGE.notRun && coverage.checkerRow?.ok) {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// index.mjs — the door of the size check's module: every kit module outside tools/source-size/
|
|
2
|
+
// reaches it through this file alone.
|
|
3
|
+
|
|
4
|
+
export {
|
|
5
|
+
KIT_LIMITS,
|
|
6
|
+
SCHEMA1_REASON,
|
|
7
|
+
applyOverride,
|
|
8
|
+
limitLines,
|
|
9
|
+
limitsDefect,
|
|
10
|
+
migrateSchema1,
|
|
11
|
+
resolveLimits,
|
|
12
|
+
} from './limits.mjs';
|
|
13
|
+
|
|
14
|
+
export {
|
|
15
|
+
SPEC_STORE_ROOT,
|
|
16
|
+
bandOf,
|
|
17
|
+
layoutCounts,
|
|
18
|
+
layoutDefect,
|
|
19
|
+
walkSpecStore,
|
|
20
|
+
} from './layout.mjs';
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
changesFor,
|
|
24
|
+
isRaise,
|
|
25
|
+
materialize,
|
|
26
|
+
ownEntry,
|
|
27
|
+
planRecord,
|
|
28
|
+
projectLayout,
|
|
29
|
+
serialize,
|
|
30
|
+
} from './record.mjs';
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// layout.mjs — the layout limits: the band every limit is judged with, the layout count over a list
|
|
2
|
+
// of entries, the layout record's grammar and the spec store's walk. It writes no file, spawns no
|
|
3
|
+
// process and imports no file of the practice, so the record's reason rule is handed in by its
|
|
4
|
+
// caller; the walk alone reads the disk, through the readdir and lstat it is handed.
|
|
5
|
+
//
|
|
6
|
+
// A name is carried as a binary string — one code point per byte — so names are compared as bytes
|
|
7
|
+
// and a name that is not valid UTF-8 is still counted; the caller decodes a key only where a record
|
|
8
|
+
// needs one.
|
|
9
|
+
//
|
|
10
|
+
// Dependency-free, Node >= 22. No side effects on import.
|
|
11
|
+
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
|
|
14
|
+
// The spec store: one more judged root, at a fixed path, walked from disk because a deployment may
|
|
15
|
+
// hide it from git.
|
|
16
|
+
export const SPEC_STORE_ROOT = 'docs/ai/specs';
|
|
17
|
+
|
|
18
|
+
// bandOf(value, tolerance) → ceil(value × tolerance / 100), in integers so no float rounds it.
|
|
19
|
+
export const bandOf = (value, tolerance) => Math.floor((value * tolerance + 99) / 100);
|
|
20
|
+
|
|
21
|
+
// layoutCounts(entries) → { files, directories }: `entries` are { path, dir } relative to one root,
|
|
22
|
+
// '/'-separated; `directories` maps each directory ('' for the root's own) to its entries (the
|
|
23
|
+
// distinct names directly under it), its depth (its segments below the root) and its reach (the
|
|
24
|
+
// deepest level its subtree holds). A file's own name is no level; a non-directory entry is a file.
|
|
25
|
+
export const layoutCounts = (entries) => {
|
|
26
|
+
const children = new Map([['', new Set()]]);
|
|
27
|
+
const namesOf = (dir) => {
|
|
28
|
+
if (!children.has(dir)) children.set(dir, new Set());
|
|
29
|
+
return children.get(dir);
|
|
30
|
+
};
|
|
31
|
+
let files = 0;
|
|
32
|
+
for (const { path, dir } of entries) {
|
|
33
|
+
const segments = path.split('/');
|
|
34
|
+
segments.forEach((name, at) => namesOf(segments.slice(0, at).join('/')).add(name));
|
|
35
|
+
if (dir) namesOf(path);
|
|
36
|
+
else files += 1;
|
|
37
|
+
}
|
|
38
|
+
const directories = new Map([...children].map(([key, names]) => {
|
|
39
|
+
const depth = key === '' ? 0 : key.split('/').length;
|
|
40
|
+
return [key, { entries: names.size, depth, reach: depth }];
|
|
41
|
+
}));
|
|
42
|
+
for (const [key, { depth }] of directories) {
|
|
43
|
+
const segments = key === '' ? [] : key.split('/');
|
|
44
|
+
for (let at = 0; at < segments.length; at += 1) {
|
|
45
|
+
const ancestor = directories.get(segments.slice(0, at).join('/'));
|
|
46
|
+
if (ancestor.reach < depth) ancestor.reach = depth;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return { files, directories };
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
53
|
+
const BAD_SEGMENTS = new Set(['', '.', '..']);
|
|
54
|
+
|
|
55
|
+
const keysDefect = (value, what, allowed, required) => {
|
|
56
|
+
if (!isPlainObject(value)) return `${what} must be an object holding ${allowed.join(', ')}`;
|
|
57
|
+
const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
|
|
58
|
+
if (unknown.length > 0) return `${what} carries unknown key(s): ${unknown.join(', ')}`;
|
|
59
|
+
const missing = required.filter((key) => !Object.hasOwn(value, key));
|
|
60
|
+
return missing.length > 0 ? `${what} is missing ${missing.join(', ')}` : null;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const entryDefect = (key, entry, what, counts, reasonDefect) => {
|
|
64
|
+
if (key !== '.' && key.split('/').some((segment) => BAD_SEGMENTS.has(segment))) {
|
|
65
|
+
return `${what} key "${key}" must be ".", or a path with no empty, "." or ".." segment`;
|
|
66
|
+
}
|
|
67
|
+
const at = `${what}."${key}"`;
|
|
68
|
+
const shape = keysDefect(entry, at, [...counts, 'reason'], counts.length === 1 ? [...counts, 'reason'] : ['reason']);
|
|
69
|
+
if (shape) return shape;
|
|
70
|
+
if (!counts.some((count) => Object.hasOwn(entry, count))) return `${at} must record ${counts.join(' or ')}`;
|
|
71
|
+
for (const count of counts.filter((name) => Object.hasOwn(entry, name))) {
|
|
72
|
+
if (!(Number.isSafeInteger(entry[count]) && entry[count] >= 0)) {
|
|
73
|
+
return `${at}.${count} must be a non-negative integer, got ${JSON.stringify(entry[count])}`;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const reason = reasonDefect(entry.reason);
|
|
77
|
+
return reason ? `${at}.reason: ${reason}` : null;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// layoutDefect(layout, reasonDefect) → the first defect naming its key, or null. The record holds
|
|
81
|
+
// exactly roots (each exactly files and reason) and directories (entries, depth or both, and reason).
|
|
82
|
+
export const layoutDefect = (layout, reasonDefect) => {
|
|
83
|
+
const shape = keysDefect(layout, '"layout"', ['roots', 'directories'], ['roots', 'directories']);
|
|
84
|
+
if (shape) return shape;
|
|
85
|
+
for (const [map, counts] of [['roots', ['files']], ['directories', ['entries', 'depth']]]) {
|
|
86
|
+
const what = `"layout"."${map}"`;
|
|
87
|
+
if (!isPlainObject(layout[map])) return `${what} must be an object`;
|
|
88
|
+
for (const [key, entry] of Object.entries(layout[map])) {
|
|
89
|
+
const defect = entryDefect(key, entry, what, counts, reasonDefect);
|
|
90
|
+
if (defect) return defect;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const SLASH = Buffer.from('/');
|
|
97
|
+
|
|
98
|
+
// walkSpecStore(cwd, { readdir, lstat }) → { state: 'absent' } | { state: 'present', entries } |
|
|
99
|
+
// { state: 'refused', path, cause }. Every entry is read by lstat and no symlink is followed, so a
|
|
100
|
+
// link — one pointing at its own parent included — is counted once as an entry and never entered.
|
|
101
|
+
export const walkSpecStore = (cwd, { readdir, lstat }) => {
|
|
102
|
+
const root = Buffer.from(join(cwd, SPEC_STORE_ROOT));
|
|
103
|
+
const refused = (path, err) => ({ state: 'refused', path: path.toString(), cause: err?.message ?? String(err) });
|
|
104
|
+
let stat;
|
|
105
|
+
try {
|
|
106
|
+
stat = lstat(root);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return err?.code === 'ENOENT' || err?.code === 'ENOTDIR' ? { state: 'absent' } : refused(root, err);
|
|
109
|
+
}
|
|
110
|
+
if (!stat.isDirectory()) return refused(root, new Error('present but not a directory'));
|
|
111
|
+
const entries = [];
|
|
112
|
+
const pending = [{ abs: root, rel: '' }];
|
|
113
|
+
while (pending.length > 0) {
|
|
114
|
+
const { abs, rel } = pending.pop();
|
|
115
|
+
let names;
|
|
116
|
+
try {
|
|
117
|
+
names = readdir(abs, { encoding: 'buffer' });
|
|
118
|
+
} catch (err) {
|
|
119
|
+
return refused(abs, err);
|
|
120
|
+
}
|
|
121
|
+
for (const raw of names) {
|
|
122
|
+
const name = typeof raw === 'string' ? Buffer.from(raw) : raw;
|
|
123
|
+
const path = Buffer.concat([abs, SLASH, name]);
|
|
124
|
+
let entry;
|
|
125
|
+
try {
|
|
126
|
+
entry = lstat(path);
|
|
127
|
+
} catch (err) {
|
|
128
|
+
return refused(path, err);
|
|
129
|
+
}
|
|
130
|
+
const child = rel === '' ? name.toString('latin1') : `${rel}/${name.toString('latin1')}`;
|
|
131
|
+
entries.push({ path: child, dir: entry.isDirectory() });
|
|
132
|
+
if (entry.isDirectory()) pending.push({ abs: path, rel: child });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { state: 'present', entries };
|
|
136
|
+
};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// limits.mjs — the kit's five size limits and a project's reasoned overrides of them: the frozen
|
|
2
|
+
// table, the override grammar, the resolution every reader gets, the lines that state it, and the two
|
|
3
|
+
// transforms the writer applies (the schema-1 move and one override). Pure: it writes no file, spawns no process and
|
|
4
|
+
// imports no file of the practice, so the record's reason rule is handed in by its caller.
|
|
5
|
+
//
|
|
6
|
+
// Dependency-free, Node >= 22. No side effects on import.
|
|
7
|
+
|
|
8
|
+
const limit = (value, tolerance) => Object.freeze({ value, tolerance });
|
|
9
|
+
|
|
10
|
+
// `files-per-root` has no kit value: its count is the one a project records.
|
|
11
|
+
export const KIT_LIMITS = Object.freeze({
|
|
12
|
+
'lines-per-file': limit(400, 10),
|
|
13
|
+
'bytes-per-line': limit(1000, 0),
|
|
14
|
+
'entries-per-directory': limit(20, 10),
|
|
15
|
+
depth: limit(5, 0),
|
|
16
|
+
'files-per-root': limit(null, 10),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export const SCHEMA1_REASON = 'carried from schema 1';
|
|
20
|
+
|
|
21
|
+
// The schema-1 `defaults` key each carried limit was spelled under.
|
|
22
|
+
const SCHEMA1_KEY = Object.freeze({ 'lines-per-file': 'maxLines', 'bytes-per-line': 'maxLineBytes' });
|
|
23
|
+
|
|
24
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
25
|
+
const hasValue = (id) => KIT_LIMITS[id].value !== null;
|
|
26
|
+
const overrideKeys = (id) => (hasValue(id) ? ['value', 'tolerance', 'reason'] : ['tolerance', 'reason']);
|
|
27
|
+
|
|
28
|
+
const overrideDefect = (id, override, reasonDefect) => {
|
|
29
|
+
if (!isPlainObject(override)) return `"limits"."${id}" must be an object holding ${overrideKeys(id).join(', ')}`;
|
|
30
|
+
const keys = overrideKeys(id);
|
|
31
|
+
const unknown = Object.keys(override).filter((key) => !keys.includes(key));
|
|
32
|
+
if (unknown.length > 0) {
|
|
33
|
+
const why = hasValue(id) ? '' : ` — ${id} takes no value, its count being the one a project records`;
|
|
34
|
+
return `"limits"."${id}" carries unknown key(s): ${unknown.join(', ')}${why}`;
|
|
35
|
+
}
|
|
36
|
+
const missing = keys.filter((key) => !Object.hasOwn(override, key));
|
|
37
|
+
if (missing.length > 0) return `"limits"."${id}" is missing ${missing.join(', ')} — an override holds exactly ${keys.join(', ')}`;
|
|
38
|
+
if (hasValue(id) && !(Number.isSafeInteger(override.value) && override.value > 0)) {
|
|
39
|
+
return `"limits"."${id}".value must be a positive integer, got ${JSON.stringify(override.value)}`;
|
|
40
|
+
}
|
|
41
|
+
if (!(Number.isSafeInteger(override.tolerance) && override.tolerance >= 0 && override.tolerance <= 100)) {
|
|
42
|
+
return `"limits"."${id}".tolerance must be an integer percent from 0 to 100, got ${JSON.stringify(override.tolerance)}`;
|
|
43
|
+
}
|
|
44
|
+
const reason = reasonDefect(override.reason);
|
|
45
|
+
return reason ? `"limits"."${id}".reason: ${reason}` : null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// limitsDefect(limits, reasonDefect) → the first defect naming its key, or null. A mistyped override
|
|
49
|
+
// would otherwise leave the kit's value in force while its author believes it changed.
|
|
50
|
+
export const limitsDefect = (limits, reasonDefect) => {
|
|
51
|
+
if (!isPlainObject(limits)) return '"limits" must be an object mapping a kit limit id to its override';
|
|
52
|
+
for (const [id, override] of Object.entries(limits)) {
|
|
53
|
+
if (!Object.hasOwn(KIT_LIMITS, id)) return `"limits" names "${id}", which is no kit limit — the kit's limits are ${Object.keys(KIT_LIMITS).join(', ')}`;
|
|
54
|
+
const defect = overrideDefect(id, override, reasonDefect);
|
|
55
|
+
if (defect) return defect;
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// resolveLimits(limits) → { limits, defaults }: every limit with its value, tolerance and source, an
|
|
61
|
+
// override carrying its reason, and `defaults` in the shape the judge and the facts already read.
|
|
62
|
+
export const resolveLimits = (limits = {}) => {
|
|
63
|
+
const resolved = Object.fromEntries(Object.entries(KIT_LIMITS).map(([id, kit]) => {
|
|
64
|
+
if (!Object.hasOwn(limits, id)) return [id, { value: kit.value, tolerance: kit.tolerance, source: 'kit' }];
|
|
65
|
+
const override = limits[id];
|
|
66
|
+
return [id, { value: hasValue(id) ? override.value : null, tolerance: override.tolerance, source: 'override', reason: override.reason }];
|
|
67
|
+
}));
|
|
68
|
+
return {
|
|
69
|
+
limits: resolved,
|
|
70
|
+
defaults: { maxLines: resolved['lines-per-file'].value, maxLineBytes: resolved['bytes-per-line'].value },
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// limitLines(limits, { escape, recorded }) → one line per resolved limit, all five, in the table's
|
|
75
|
+
// order: value, tolerance and source. The escape that makes a reason safe on a line is handed in, so
|
|
76
|
+
// the check and the plan-time render state the same five lines from this one function.
|
|
77
|
+
export const limitLines = (limits, { escape = String, recorded = false } = {}) => Object.keys(KIT_LIMITS).map((id) => {
|
|
78
|
+
const { value, tolerance, source, reason } = limits[id];
|
|
79
|
+
const amount = value !== null ? `${value}` : recorded ? "each judged root's recorded count" : 'none recorded';
|
|
80
|
+
return `limit ${id} ${amount}, tolerance ${tolerance}% — ${source === 'kit' ? 'from kit' : `from override: ${escape(reason)}`}`;
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// migrateSchema1(parsed, readmes) → the schema-2 config the writer writes, every key in its place. A
|
|
84
|
+
// `_README` byte-equal to `readmes.schema1` becomes `readmes.schema2`; any other is carried verbatim.
|
|
85
|
+
export const migrateSchema1 = (parsed, readmes = {}) => {
|
|
86
|
+
const overrides = Object.fromEntries(Object.entries(SCHEMA1_KEY)
|
|
87
|
+
.filter(([id, key]) => parsed.defaults[key] !== KIT_LIMITS[id].value)
|
|
88
|
+
.map(([id, key]) => [id, { value: parsed.defaults[key], tolerance: KIT_LIMITS[id].tolerance, reason: SCHEMA1_REASON }]));
|
|
89
|
+
return Object.fromEntries(Object.entries(parsed).flatMap(([key, value]) => {
|
|
90
|
+
if (key === 'schema') return [[key, 2]];
|
|
91
|
+
if (key === '_README') return [[key, value === readmes.schema1 ? readmes.schema2 : value]];
|
|
92
|
+
if (key === 'defaults') return Object.keys(overrides).length === 0 ? [] : [['limits', overrides]];
|
|
93
|
+
return [[key, value]];
|
|
94
|
+
}));
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
// applyOverride(parsed, id, override) → the config with one id's override set from { value,
|
|
98
|
+
// tolerance, reason } or, given null, removed; a `limits` left empty is dropped and a new one is
|
|
99
|
+
// appended. It judges nothing about the tree: the writer regenerates the record from the result.
|
|
100
|
+
export const applyOverride = (parsed, id, override) => {
|
|
101
|
+
const limits = { ...(parsed.limits ?? {}) };
|
|
102
|
+
if (override === null) delete limits[id];
|
|
103
|
+
else limits[id] = Object.fromEntries(overrideKeys(id).map((key) => [key, override[key]]));
|
|
104
|
+
const kept = Object.keys(limits).length > 0;
|
|
105
|
+
const entries = Object.entries(parsed)
|
|
106
|
+
.filter(([key]) => key !== 'limits' || kept)
|
|
107
|
+
.map(([key, value]) => [key, key === 'limits' ? limits : value]);
|
|
108
|
+
if (kept && !Object.hasOwn(parsed, 'limits')) entries.push(['limits', limits]);
|
|
109
|
+
return Object.fromEntries(entries);
|
|
110
|
+
};
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// record.mjs — the recorded ratchet as data: the delta rules every half reads, the layout record a
|
|
2
|
+
// regeneration would write, the regeneration plan, its materialization with each reason, and the
|
|
3
|
+
// canonical serialization. Pure: it writes no file and spawns no process — the writer half applies
|
|
4
|
+
// it and owns the one write.
|
|
5
|
+
//
|
|
6
|
+
// Dependency-free, Node >= 22. No side effects on import.
|
|
7
|
+
|
|
8
|
+
import { bandOf } from './layout.mjs';
|
|
9
|
+
|
|
10
|
+
const FILE_DIMENSIONS = Object.freeze(['lines', 'maxLineBytes']);
|
|
11
|
+
const LAYOUT_DIMENSIONS = Object.freeze(['entries', 'depth']);
|
|
12
|
+
const MACHINE_KEYS = Object.freeze(['baseline', 'aggregate', 'layout']);
|
|
13
|
+
|
|
14
|
+
// A recorded entry is read by OWN key only. A declared root may legitimately be named like an
|
|
15
|
+
// Object.prototype member ("constructor", "toString"), and a plain lookup would then answer with an
|
|
16
|
+
// INHERITED value — which reads as "already recorded", so the raise goes unnoticed and the entry is
|
|
17
|
+
// written with no reason at all, producing a config the validator refuses.
|
|
18
|
+
export const ownEntry = (map, key) => (Object.hasOwn(map, key) ? map[key] : undefined);
|
|
19
|
+
|
|
20
|
+
// A change is a RAISE when it puts a number where there was none, or a bigger one where there was a
|
|
21
|
+
// smaller — the whole class a human's reason is required for. Everything else lowers or removes.
|
|
22
|
+
export const isRaise = ({ from, to }) => to !== null && (from === null || to > from);
|
|
23
|
+
|
|
24
|
+
// changesFor(target, projected, recorded, dimensions) → the per-dimension old→new pairs that differ.
|
|
25
|
+
// The refusal, the printed delta and the reason an entry ends up with all read THIS.
|
|
26
|
+
export const changesFor = (target, projected, recorded, dimensions = FILE_DIMENSIONS) => dimensions
|
|
27
|
+
.map((dimension) => ({
|
|
28
|
+
target,
|
|
29
|
+
dimension,
|
|
30
|
+
from: recorded && Object.hasOwn(recorded, dimension) ? recorded[dimension] : null,
|
|
31
|
+
to: Object.hasOwn(projected, dimension) ? projected[dimension] : null,
|
|
32
|
+
}))
|
|
33
|
+
.filter(({ from, to }) => from !== to);
|
|
34
|
+
|
|
35
|
+
const ceilingOf = ({ value, tolerance }) => value + bandOf(value, tolerance);
|
|
36
|
+
|
|
37
|
+
// projectLayout(measured, recorded, limits) → the layout record a regeneration would write, without
|
|
38
|
+
// reasons. A root's files are written as measured, except a count above its record and within its
|
|
39
|
+
// band, which keeps the record: a warning never raises. A directory is recorded only beyond its band:
|
|
40
|
+
// `entries` its count, `depth` on the shallowest directory beyond the depth band, holding the deepest
|
|
41
|
+
// level its subtree reaches.
|
|
42
|
+
export const projectLayout = (measured, recorded, limits) => {
|
|
43
|
+
const tolerance = limits['files-per-root'].tolerance;
|
|
44
|
+
const roots = Object.fromEntries([...measured.roots].map(([root, files]) => {
|
|
45
|
+
const kept = recorded ? ownEntry(recorded.roots, root) : undefined;
|
|
46
|
+
const keep = kept !== undefined && files > kept.files && files <= kept.files + bandOf(kept.files, tolerance);
|
|
47
|
+
return [root, keep ? kept.files : files];
|
|
48
|
+
}));
|
|
49
|
+
const entries = ceilingOf(limits['entries-per-directory']);
|
|
50
|
+
const holder = ceilingOf(limits.depth) + 1;
|
|
51
|
+
const directories = Object.fromEntries([...measured.directories].flatMap(([key, facts]) => {
|
|
52
|
+
const next = {
|
|
53
|
+
...(facts.entries > entries ? { entries: facts.entries } : {}),
|
|
54
|
+
...(facts.depth === holder ? { depth: facts.reach } : {}),
|
|
55
|
+
};
|
|
56
|
+
return Object.keys(next).length > 0 ? [[key, next]] : [];
|
|
57
|
+
}));
|
|
58
|
+
return { roots, directories };
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const layoutPlan = (recorded, projected) => {
|
|
62
|
+
const old = recorded ?? { roots: {}, directories: {} };
|
|
63
|
+
const roots = Object.entries(projected.roots).map(([root, next]) => ({ root, next, recorded: ownEntry(old.roots, root) }));
|
|
64
|
+
const directories = Object.entries(projected.directories).map(([key, next]) => {
|
|
65
|
+
const was = ownEntry(old.directories, key);
|
|
66
|
+
return { key, next, recorded: was, changes: changesFor(key, next, was, LAYOUT_DIMENSIONS) };
|
|
67
|
+
});
|
|
68
|
+
const deltas = [
|
|
69
|
+
...roots
|
|
70
|
+
.filter(({ next, recorded: was }) => (was ? was.files : null) !== next)
|
|
71
|
+
.map(({ root, next, recorded: was }) => ({ target: root, dimension: 'files', from: was ? was.files : null, to: next })),
|
|
72
|
+
...Object.entries(old.roots)
|
|
73
|
+
.filter(([root]) => !Object.hasOwn(projected.roots, root))
|
|
74
|
+
.map(([root, was]) => ({ target: root, dimension: 'files', from: was.files, to: null })),
|
|
75
|
+
...directories.flatMap(({ changes }) => changes),
|
|
76
|
+
...Object.entries(old.directories)
|
|
77
|
+
.filter(([key]) => !Object.hasOwn(projected.directories, key))
|
|
78
|
+
.flatMap(([key, was]) => changesFor(key, {}, was, LAYOUT_DIMENSIONS)),
|
|
79
|
+
];
|
|
80
|
+
return { roots, directories, deltas };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
// planRecord({ config, verdict }) computes what the regeneration WOULD write, before any reason is
|
|
84
|
+
// applied — so a raise can be refused without ever building an entry that carries no reason. It reads
|
|
85
|
+
// the JUDGE's projection, never its own: the checker's verdict and the file the writer produces are
|
|
86
|
+
// then two renderings of one computation.
|
|
87
|
+
export const planRecord = ({ config, verdict }) => {
|
|
88
|
+
const oldBaseline = config.baseline ?? {};
|
|
89
|
+
const oldAggregate = config.aggregate ?? {};
|
|
90
|
+
const files = verdict.scope.files.map((rel) => {
|
|
91
|
+
const next = verdict.projected.get(rel);
|
|
92
|
+
const recorded = ownEntry(oldBaseline, rel);
|
|
93
|
+
return { rel, next, recorded, changes: changesFor(rel, next, recorded) };
|
|
94
|
+
});
|
|
95
|
+
const roots = config.roots.map((root) => ({ root, lines: verdict.rootLines.get(root) ?? 0, recorded: ownEntry(oldAggregate, root) }));
|
|
96
|
+
const layout = verdict.layout ? layoutPlan(config.layout, verdict.layout.projected) : null;
|
|
97
|
+
const deltas = [
|
|
98
|
+
...files.flatMap(({ changes }) => changes),
|
|
99
|
+
// A record whose file left scope is REMOVED, never kept: that is what makes a split or a rename
|
|
100
|
+
// visible in the delta instead of silently surviving as headroom.
|
|
101
|
+
...Object.entries(oldBaseline)
|
|
102
|
+
.filter(([rel]) => !verdict.measured.has(rel))
|
|
103
|
+
.flatMap(([rel, recorded]) => changesFor(rel, {}, recorded)),
|
|
104
|
+
...roots
|
|
105
|
+
.filter(({ lines, recorded }) => (recorded ? recorded.lines : null) !== lines)
|
|
106
|
+
.map(({ root, lines, recorded }) => ({ target: root, dimension: 'aggregate lines', from: recorded ? recorded.lines : null, to: lines })),
|
|
107
|
+
...Object.entries(oldAggregate)
|
|
108
|
+
.filter(([root]) => !config.roots.includes(root))
|
|
109
|
+
.map(([root, recorded]) => ({ target: root, dimension: 'aggregate lines', from: recorded.lines, to: null })),
|
|
110
|
+
...(layout ? layout.deltas : []),
|
|
111
|
+
];
|
|
112
|
+
return { files, roots, layout, deltas, raises: deltas.filter(isRaise) };
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const byKey = (entries) => Object.fromEntries(entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
116
|
+
|
|
117
|
+
// The reason of an entry the regeneration did NOT raise is the one already recorded — a tighten
|
|
118
|
+
// rewrites a number, never the human sentence that justified it.
|
|
119
|
+
export const materialize = ({ files, roots, layout }, reason) => ({
|
|
120
|
+
baseline: Object.fromEntries(
|
|
121
|
+
files
|
|
122
|
+
.filter(({ next }) => Object.keys(next).length > 0)
|
|
123
|
+
.map(({ rel, next, recorded, changes }) => [rel, { ...next, reason: changes.some(isRaise) ? reason : recorded.reason }]),
|
|
124
|
+
),
|
|
125
|
+
aggregate: Object.fromEntries(
|
|
126
|
+
roots.map(({ root, lines, recorded }) => [root, { lines, reason: !recorded || lines > recorded.lines ? reason : recorded.reason }]),
|
|
127
|
+
),
|
|
128
|
+
...(layout === null ? {} : {
|
|
129
|
+
layout: {
|
|
130
|
+
roots: byKey(layout.roots.map(({ root, next, recorded }) => [root, { files: next, reason: !recorded || next > recorded.files ? reason : recorded.reason }])),
|
|
131
|
+
directories: byKey(layout.directories.map(({ key, next, recorded, changes }) => [key, { ...next, reason: changes.some(isRaise) ? reason : recorded.reason }])),
|
|
132
|
+
},
|
|
133
|
+
}),
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// The file is CANONICALLY serialized: the authored VALUES and the ORDER the human wrote them in are
|
|
137
|
+
// preserved exactly, their formatting is not — this file is machine-maintained and the writer owns
|
|
138
|
+
// half of it, so one deterministic rendering is what makes "regenerate an unchanged tree and get the
|
|
139
|
+
// same bytes" true at all. The machine keys follow in their fixed order.
|
|
140
|
+
export const serialize = (parsed, machine) => {
|
|
141
|
+
const authored = Object.fromEntries(Object.entries(parsed).filter(([key]) => !MACHINE_KEYS.includes(key)));
|
|
142
|
+
return `${JSON.stringify({ ...authored, ...machine }, null, 2)}\n`;
|
|
143
|
+
};
|