@sabaiway/agent-workflow-kit 19.5.0 → 20.0.1

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +18 -10
  3. package/SKILL.md +6 -6
  4. package/bin/install.mjs +1 -1
  5. package/capability.json +1 -1
  6. package/migrations/1.1.0-communication-language.md +2 -4
  7. package/migrations/1.2.0-agent-attribution.md +1 -3
  8. package/migrations/5.0.0-kit-text-in-kit-files.md +30 -0
  9. package/migrations/README.md +2 -2
  10. package/package.json +1 -1
  11. package/references/advisor-writers.md +1 -1
  12. package/references/contracts.md +9 -11
  13. package/references/modes/bootstrap.md +2 -4
  14. package/references/modes/hook.md +1 -1
  15. package/references/modes/procedures.md +1 -1
  16. package/references/modes/recommendations.md +1 -1
  17. package/references/modes/rules.md +4 -3
  18. package/references/modes/upgrade.md +23 -49
  19. package/references/modes/velocity.md +1 -1
  20. package/references/reference-profile.json +0 -6
  21. package/references/rules/communication.md +22 -0
  22. package/references/rules/project-layout.md +2 -0
  23. package/references/rules/story-sessions.md +14 -0
  24. package/references/shared/composition-handoff.md +24 -59
  25. package/references/shared/deploy-tail.md +2 -2
  26. package/references/templates/AGENTS.md +0 -10
  27. package/references/templates/agent_rules.md +0 -33
  28. package/tools/cheap-agents-read.mjs +1 -1
  29. package/tools/delegation.mjs +5 -8
  30. package/tools/engine-source.mjs +13 -11
  31. package/tools/family-registry.mjs +4 -5
  32. package/tools/inject-methodology.mjs +153 -493
  33. package/tools/migration-blocks.mjs +0 -6
  34. package/tools/orchestration-readme.mjs +1 -1
  35. package/tools/payload-prune.mjs +48 -8
  36. package/tools/profile-gap-screen.mjs +2 -6
  37. package/tools/profile-gaps.mjs +19 -100
  38. package/tools/project-rules/index.mjs +1 -2
  39. package/tools/project-rules/rules-ensure.mjs +37 -6
  40. package/tools/project-rules/rules-priors.mjs +1 -0
  41. package/tools/project-rules/themes.mjs +13 -5
  42. package/tools/transition/index.mjs +214 -0
  43. package/tools/upgrade-runlist.mjs +2 -17
  44. package/tools/velocity-profile.mjs +1 -1
  45. package/tools/lens-region.mjs +0 -281
  46. package/tools/project-rules/memory-map-row.mjs +0 -81
  47. package/tools/rules-insert.mjs +0 -203
  48. package/tools/rules-regions.mjs +0 -190
@@ -1,544 +1,204 @@
1
1
  #!/usr/bin/env node
2
- // Marker-slot injection + reconciliation — the composition root's only mutation of a deployed
3
- // AGENTS.md. A deployed entry point carries THREE reconciled marker slots, each filled LIVE from the
4
- // installed agent-workflow-engine (the family's one source of truth, no bundled mirror):
5
- // 1. workflow:methodology — the plan→execute→review pointer (references/methodology-slot.md).
6
- // 2. workflow:orchestration — the recipe-vocabulary pointer (references/orchestration-slot.md).
7
- // 3. workflow:autonomy — the autonomy-policy read contract (references/autonomy-slot.md).
8
- //
9
- // All share ONE generic marker engine (a slot DESCRIPTOR parameterizes the markers / anchor / empty-slot
10
- // / leading-blank); the methodology exports delegate to it byte-for-byte. After the three slots,
11
- // reconcile keeps one Memory Map row per project-rules theme (project-rules/memory-map-row.mjs).
12
- //
13
- // Contract per slot, strictly enforced:
14
- // exactly one ordered start→end pair → replace only the bytes between them;
15
- // markers absent → ensure-insert an empty pair at the slot's anchor (or NO-OP in legacy inject);
16
- // any malformed state (single, reversed, nested, duplicate) → NO-OP WITH AN ERROR, never edit.
17
- // The live read is fail-loud: the engine is read for every slot the ensure can place (a filled slot
18
- // cannot be judged without its fragment), and a needed-but-absent/invalid engine is a loud STOP.
19
- // Pure string functions (testable with byte-preservation fixtures); dependency-free, Node >= 22.
20
- //
21
- // The policy per slot (entry-pointers revision 1): content equal to the fragment is left, a KNOWN PRIOR
22
- // canonical fragment (drift-guarded, append-only per descriptor) is refreshed, and any other content is
23
- // written current with no question and no copy kept. Contract: docs/ai/specs/kit/install/entry-pointers.md.
2
+ // The kit block — the composition root's only mutation of a deployed AGENTS.md. ONE block between two
3
+ // marker lines holds the precedence line, the read line, the installed engine's three fragments (read
4
+ // LIVE, no bundled copy) and the rules-themes table. The block is written current on every run with no
5
+ // question and no copy kept; outside it nothing is written or found. An absent or invalid engine is a
6
+ // STOP; malformed marker lines are refused with their line numbers. Pure string functions plus one
7
+ // return-code entry point; dependency-free, Node >= 22. Contract: docs/ai/specs/kit/install/entry-pointers.md.
24
8
 
25
9
  import { isDirectRun } from './direct-run.mjs';
26
10
  import { normalizeCanonical } from './orchestration-config.mjs';
27
- import { reconcileMemoryMapRows, ROW_ROUTE } from './project-rules/index.mjs';
28
-
29
- export const START_MARKER = '<!-- workflow:methodology:start -->';
30
- export const END_MARKER = '<!-- workflow:methodology:end -->';
31
- export const ORCH_START_MARKER = '<!-- workflow:orchestration:start -->';
32
- export const ORCH_END_MARKER = '<!-- workflow:orchestration:end -->';
33
- export const AUTONOMY_START_MARKER = '<!-- workflow:autonomy:start -->';
34
- export const AUTONOMY_END_MARKER = '<!-- workflow:autonomy:end -->';
35
- export const AGENTS_MD_CAP = 100; // the deployed AGENTS.md line budget (its own footer rule)
36
-
37
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
-
39
- // Count lines independent of a trailing newline (CRLF-safe: split on '\n' — a CRLF line still ends
40
- // in '\n', so the count is the same as for LF).
41
- const lineCount = (text) => text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
42
-
43
- const countOccurrences = (haystack, needle) => {
44
- let count = 0;
45
- let from = 0;
46
- for (;;) {
47
- const idx = haystack.indexOf(needle, from);
48
- if (idx === -1) return count;
49
- count += 1;
50
- from = idx + needle.length;
51
- }
52
- };
53
-
54
- const countMatches = (text, re) => (text.match(new RegExp(re.source, 'gm')) || []).length;
55
-
56
- // The Session-Protocols anchor line both deployed templates carry (the agent_rules.md §1 sentence).
57
- // ensureSlot inserts an empty METHODOLOGY slot right after this line when a legacy entry point has no
58
- // markers. Contract: EXACTLY ONE match required — 0 or >1 → error (never guess where it lives).
59
- export const METHODOLOGY_ANCHOR = /^.*Read it before any code change\..*$/m;
60
- // The orchestration pair lands right BELOW the methodology end marker — so its anchor is that line.
61
- // A well-formed entry point carries exactly one methodology end marker → exactly one anchor.
62
- export const ORCH_ANCHOR = new RegExp(`^.*${escapeRegExp(END_MARKER)}.*$`, 'm');
63
- // The autonomy pair chains right below the orchestration pair — its anchor is the orchestration end
64
- // marker line. The anchor can legitimately be ABSENT (a legacy file whose orchestration pair was
65
- // itself skipped) — the chained CLI classifies that as a soft skip, never a hard STOP (D4).
66
- export const AUTONOMY_ANCHOR = new RegExp(`^.*${escapeRegExp(ORCH_END_MARKER)}.*$`, 'm');
67
-
68
- // The canonical empty slots (an ordered start→end pair, nothing between) — what a fresh template
69
- // ships and what ensureSlot inserts. LF form; ensureSlot rewrites the newline to match the document.
70
- export const EMPTY_SLOT = `${START_MARKER}\n${END_MARKER}`;
71
- export const ORCH_EMPTY_SLOT = `${ORCH_START_MARKER}\n${ORCH_END_MARKER}`;
72
- export const AUTONOMY_EMPTY_SLOT = `${AUTONOMY_START_MARKER}\n${AUTONOMY_END_MARKER}`;
73
-
74
- // ── known-prior canonical fragments (drift-guarded, APPEND-ONLY per slot) ───────
75
- // The EXACT content a PREVIOUS release's engine fragment shipped (what a filled slot would carry today).
76
- // reconcileMarkerSlot words a filled slot's write as a refresh IFF its content normalize-matches one of
77
- // these. Any release that CHANGES an engine fragment must FIRST append the
78
- // OUTGOING content here, so the immediately-previous deployments still match (a drift-guard test pins
79
- // current-minus-one → new). NEVER edit an existing entry — only append.
80
- export const KNOWN_PRIOR_METHODOLOGY_SLOT = [
81
- // v1.3.0 — pre-communication-contract methodology pointer (procedures route, no §1.9 clause).
82
- '> **Workflow methodology** — plan → execute → review. Plans are ephemeral `docs/plans/*.md` (gitignored, **never committed**); every Plan ends with a mandatory **Phase: Cleanup**; series order lives in `docs/plans/queue.md`. Full vocabulary, lifecycle, and the plan-then-execute split live in the project\'s **planning skill** (it overrides the generic `writing-plans`); summary in `docs/ai/agent_rules.md` §5. Named activities (plan-authoring, plan-execution) have procedures — see `/agent-workflow-kit procedures <activity>` for the steps + resolved recipe.',
83
- // engine 2.1.0 — the pre-canon-rewrite pointer (vocabulary + plan-then-execute wording, with the communication contract).
84
- '> **Workflow methodology** — plan → execute → review. Plans are ephemeral `docs/plans/*.md` (gitignored, **never committed**); every Plan ends with a mandatory **Phase: Cleanup**; series order lives in `docs/plans/queue.md`. Full vocabulary, lifecycle, and the plan-then-execute split live in the project\'s **planning skill** (it overrides the generic `writing-plans`); summary in `docs/ai/agent_rules.md` §5. Named activities (plan-authoring, plan-execution) have procedures — see `/agent-workflow-kit procedures <activity>` for the steps + resolved recipe. **Communication:** user-facing messages deliver the artifact inline (paste the prompt / diff / command — never "see §X" as a substitute), lead with the result, show exactly what was asked, and never read as mockery (a large artifact: a real summary inline + a link).',
85
- // engine 4.2.0 — the two-activity pointer, before `routine` joined the named activities.
86
- '> **Workflow methodology** — plan → execute → review. Plans are ephemeral `docs/plans/*.md` (gitignored, **never committed**); every Plan ends with a mandatory **Phase: Cleanup**; series order lives in `docs/plans/queue.md`. The plan shape, its caps and lifecycle live in the project\'s **planning skill** (it overrides the generic `writing-plans`); summary in `docs/ai/agent_rules.md` §5. Named activities (plan-authoring, plan-execution) have procedures — see `/agent-workflow-kit procedures <activity>` for the steps + resolved recipe. **Communication:** user-facing messages deliver the artifact inline (paste the prompt / diff / command — never "see §X" as a substitute), lead with the result, show exactly what was asked, and never read as mockery (a large artifact: a real summary inline + a link).',
87
- // engine 4.6.0 — the three-activity pointer, before feedback-triage joined the named activities.
88
- '> **Workflow methodology** — plan → execute → review. Plans are ephemeral `docs/plans/*.md` (gitignored, **never committed**); every Plan ends with a mandatory **Phase: Cleanup**; series order lives in `docs/plans/queue.md`. The plan shape, its caps and lifecycle live in the project\'s **planning skill** (it overrides the generic `writing-plans`); summary in `docs/ai/agent_rules.md` §5. Named activities (plan-authoring, plan-execution, routine) have procedures — see `/agent-workflow-kit procedures <activity>` for the steps + resolved recipe. **Communication:** user-facing messages deliver the artifact inline (paste the prompt / diff / command — never "see §X" as a substitute), lead with the result, show exactly what was asked, and never read as mockery (a large artifact: a real summary inline + a link).',
89
- // engine 5.7.0 — the four-activity pointer, before epic and task joined the named activities.
90
- '> **Workflow methodology** — plan → execute → review. Plans are ephemeral `docs/plans/*.md` (gitignored, **never committed**); every Plan ends with a mandatory **Phase: Cleanup**; series order lives in `docs/plans/queue.md`. The plan shape, its caps and lifecycle live in the project\'s **planning skill** (it overrides the generic `writing-plans`); summary in `docs/ai/agent_rules.md` §5. Named activities (plan-authoring, plan-execution, routine, feedback-triage) have procedures — see `/agent-workflow-kit procedures <activity>` for the steps + resolved recipe. **Communication:** user-facing messages deliver the artifact inline (paste the prompt / diff / command — never "see §X" as a substitute), lead with the result, show exactly what was asked, and never read as mockery (a large artifact: a real summary inline + a link).',
91
- ];
92
- export const KNOWN_PRIOR_ORCH_SLOT = [
93
- // v1.3.0 — pre-read-at-start orchestration pointer (recipes vocabulary, no orchestration.json clause).
94
- '> **Orchestration recipes** — compose plan → execute → review with a named recipe: **Solo** (no backend), **Reviewed** (one backend reviews), **Council** (both review, you synthesize), **Delegated** (a backend executes a bounded sub-task); the orchestrator always commits, a backend is never autonomous. Pick + plan one for this environment with `/agent-workflow-kit recipes` (read-only); the deployed how/why lives in your `docs/ai/` workflow docs.',
95
- // engine 4.2.0 — the four-recipe pointer with the read-at-start clause, before the Subagent carrier joined the list.
96
- '> **Orchestration recipes** — compose plan → execute → review with a named recipe: **Solo** (no backend), **Reviewed** (one backend reviews), **Council** (both review, you synthesize), **Delegated** (a backend executes a bounded sub-task); the orchestrator always commits, a backend is never autonomous. Pick + plan one for this environment with `/agent-workflow-kit recipes` (read-only); the deployed how/why lives in your `docs/ai/` workflow docs. At the start of a planning/execution session, read your standing recipe preference in `docs/ai/orchestration.json` — set it in plain language with `/agent-workflow-kit set-recipe` (previews first; hand-edit stays supported).',
97
- ];
98
-
99
- // A slot descriptor bundles everything the generic engine needs to operate on ONE marker pair.
100
- // `leadingBlank` controls whether the inserted empty pair gets a blank separator line above it — the
101
- // methodology insert keeps it (readability), the orchestration insert omits it to save a cap line
102
- // (the pair already sits right under the methodology block). `knownPriorCanonicals` words the refresh;
103
- // `label` names the pointer in the reconcile line and the over-cap error.
104
- export const METHODOLOGY_DESCRIPTOR = {
105
- startMarker: START_MARKER,
106
- endMarker: END_MARKER,
107
- anchor: METHODOLOGY_ANCHOR,
108
- emptySlot: EMPTY_SLOT,
109
- leadingBlank: true,
110
- markerName: 'methodology',
111
- label: 'workflow-methodology',
112
- anchorLabel: 'methodology anchor (the "Read it before any code change." Session-Protocols line)',
113
- knownPriorCanonicals: KNOWN_PRIOR_METHODOLOGY_SLOT,
114
- };
115
- export const ORCHESTRATION_DESCRIPTOR = {
116
- startMarker: ORCH_START_MARKER,
117
- endMarker: ORCH_END_MARKER,
118
- anchor: ORCH_ANCHOR,
119
- emptySlot: ORCH_EMPTY_SLOT,
120
- leadingBlank: false,
121
- markerName: 'orchestration',
122
- label: 'orchestration-recipes',
123
- anchorLabel: 'orchestration anchor (the methodology end-marker line)',
124
- knownPriorCanonicals: KNOWN_PRIOR_ORCH_SLOT,
11
+ import { PRECEDENCE_LINE, THEMES, themePaths } from './project-rules/index.mjs';
12
+ import {
13
+ AUTONOMY_FRAGMENT_REL, ENGINE_FRAGMENT_REL, ORCHESTRATION_FRAGMENT_REL, detectEngine, readEngineFragment, resolveEngineDir,
14
+ } from './engine-source.mjs';
15
+
16
+ export const BLOCK_START = '<!-- workflow:kit:start -->';
17
+ export const BLOCK_END = '<!-- workflow:kit:end -->';
18
+ export const READ_LINE = 'Read `docs/ai/index.md` after this file; read `docs/ai/agent_rules.md` before any code change.';
19
+ export const SKIP_PREFIX = 'Kit text not supplied by the installed engine:';
20
+ export const BLOCK_ROUTE = "text of your own goes outside the two workflow:kit comment lines; a change to a kit rule goes in its theme's file under docs/ai/rules/local/";
21
+
22
+ const LF = '\n';
23
+ const CRLF = '\r\n';
24
+ const BOM = '\uFEFF';
25
+ const INSTALL = 'npx @sabaiway/agent-workflow-engine@latest init';
26
+ const TAG = '[inject-methodology]';
27
+
28
+ // The three engine fragments in block order; a valid engine lacking one but methodology leaves a skip line.
29
+ const FRAGMENTS = Object.freeze([
30
+ Object.freeze({ id: 'methodology', rel: ENGINE_FRAGMENT_REL }),
31
+ Object.freeze({ id: 'orchestration', rel: ORCHESTRATION_FRAGMENT_REL, name: 'the orchestration recipes' }),
32
+ Object.freeze({ id: 'autonomy', rel: AUTONOMY_FRAGMENT_REL, name: 'the autonomy policy' }),
33
+ ]);
34
+ const themeName = (name) => `the ${name} rules theme`;
35
+
36
+ // ── the finder: marker lines outside closed fences ───────────────────────────────────────────────
37
+
38
+ // The fence opener and closer rules of references/scripts/markdown-blocks.mjs, applied here.
39
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
40
+ const matchable = (line) => line.replace(/\s+$/u, '');
41
+ const opensFence = (line) => {
42
+ const match = FENCE_RE.exec(matchable(line));
43
+ if (!match || (match[1][0] === '`' && match[2].includes('`'))) return null;
44
+ return { char: match[1][0], length: match[1].length };
125
45
  };
126
- // The autonomy-policy slot (AD-044 Plan 3) — first canon, so no known priors yet: any future
127
- // fragment change must append the outgoing content to a KNOWN_PRIOR_AUTONOMY_SLOT store first.
128
- export const AUTONOMY_DESCRIPTOR = {
129
- startMarker: AUTONOMY_START_MARKER,
130
- endMarker: AUTONOMY_END_MARKER,
131
- anchor: AUTONOMY_ANCHOR,
132
- emptySlot: AUTONOMY_EMPTY_SLOT,
133
- leadingBlank: false,
134
- markerName: 'autonomy',
135
- label: 'autonomy',
136
- anchorLabel: 'autonomy anchor (the orchestration end-marker line)',
137
- knownPriorCanonicals: [],
46
+ const closesFence = (line, open) => {
47
+ const match = FENCE_RE.exec(matchable(line));
48
+ return Boolean(match) && match[1][0] === open.char && match[1].length >= open.length && match[2].trim() === '';
138
49
  };
139
50
 
140
- // ── generic marker-slot engine (descriptor-parameterized) ──────────────────────
141
-
142
- // Classify the marker state of a slot. Pure; no fs.
143
- // { state: 'ok', startIdx, endIdx } exactly one ordered pair
144
- // { state: 'absent' } no markers at all → caller no-ops / ensure-inserts
145
- // { state: 'malformed', reason } anything else → caller no-ops WITH error
146
- export const findMarkerSlot = (text, descriptor) => {
147
- const starts = countOccurrences(text, descriptor.startMarker);
148
- const ends = countOccurrences(text, descriptor.endMarker);
149
- if (starts === 0 && ends === 0) return { state: 'absent' };
150
- if (starts !== 1 || ends !== 1) {
151
- return { state: 'malformed', reason: `expected exactly one start/end marker pair, found ${starts} start / ${ends} end` };
51
+ // markerLines(lines) → [{ index, marker }] for every start or end marker line; a closed fence hides its
52
+ // lines, an opener no later line closes fences nothing.
53
+ const markerLines = (lines) => {
54
+ const found = [];
55
+ for (let index = 0; index < lines.length; index += 1) {
56
+ const open = opensFence(lines[index]);
57
+ if (open) {
58
+ const close = lines.findIndex((line, at) => at > index && closesFence(line, open));
59
+ if (close !== -1) index = close;
60
+ continue;
61
+ }
62
+ const content = lines[index].replace(/\r$/u, '').trim();
63
+ if (content === BLOCK_START || content === BLOCK_END) found.push({ index, marker: content });
152
64
  }
153
- const startIdx = text.indexOf(descriptor.startMarker);
154
- const endIdx = text.indexOf(descriptor.endMarker);
155
- if (endIdx < startIdx) return { state: 'malformed', reason: 'end marker precedes start marker' };
156
- return { state: 'ok', startIdx, endIdx };
65
+ return found;
157
66
  };
158
67
 
159
- // Inject `fragment` between the markers, replacing only the bytes between them. Returns
160
- // { status: 'injected' | 'noop-absent' | 'error', text, error? }. On absent/error the returned text
161
- // is the INPUT, byte-for-byte. Pass `{ maxLines }` to enforce the AGENTS.md line cap (refuse, don't bust).
162
- export const injectIntoSlot = (text, descriptor, fragment, { maxLines } = {}) => {
163
- if (fragment.includes(descriptor.startMarker) || fragment.includes(descriptor.endMarker)) {
164
- return { status: 'error', text, error: `fragment contains a ${descriptor.markerName} marker — refusing to inject (would create a duplicate/nested slot)` };
68
+ // findKitBlock(text) → { state: 'ok', start, end } | { state: 'absent' } | { state: 'malformed', lines }.
69
+ export const findKitBlock = (text) => {
70
+ const found = markerLines(text.split(LF));
71
+ if (found.length === 0) return { state: 'absent' };
72
+ const [first, second] = found;
73
+ if (found.length === 2 && first.marker === BLOCK_START && second.marker === BLOCK_END) {
74
+ return { state: 'ok', start: first.index + 1, end: second.index + 1 };
165
75
  }
166
- const slot = findMarkerSlot(text, descriptor);
167
- if (slot.state === 'absent') return { status: 'noop-absent', text };
168
- if (slot.state === 'malformed') return { status: 'error', text, error: slot.reason };
169
- // Frame the fragment with the DOCUMENT's newline style (and convert the LF-canonical fragment to
170
- // it) so injecting into a CRLF file does not leave lone LFs around the slot.
171
- const nl = text.includes('\r\n') ? '\r\n' : '\n';
172
- const before = text.slice(0, slot.startIdx + descriptor.startMarker.length);
173
- const after = text.slice(slot.endIdx);
174
- const body = fragment.trim().replace(/\r?\n/g, nl);
175
- const out = `${before}${nl}${body}${nl}${after}`;
176
- if (maxLines != null && lineCount(out) > maxLines) {
177
- return { status: 'error', text, error: `injection would push AGENTS.md to ${lineCount(out)} lines (cap ${maxLines}) — trim the fragment or the file` };
178
- }
179
- return { status: 'injected', text: out };
76
+ return { state: 'malformed', lines: found.map(({ index }) => index + 1) };
180
77
  };
181
78
 
182
- // Extract the current slot content (preserve-on-upgrade inverse). Bytes strictly between the markers,
183
- // or null on absent/malformed.
184
- export const extractMarkerSlot = (text, descriptor) => {
185
- const slot = findMarkerSlot(text, descriptor);
186
- if (slot.state !== 'ok') return null;
187
- return text.slice(slot.startIdx + descriptor.startMarker.length, slot.endIdx);
79
+ // ── the composer and the judgement (pure) ────────────────────────────────────────────────────────
80
+
81
+ const skipLine = (name) => `${SKIP_PREFIX} ${name} — refresh it with ${INSTALL}`;
82
+ const effectiveOf = (theme) => themePaths(theme.name).effective;
83
+
84
+ // composeKitBlock({ fragments, themes, lacking? }) → the block in LF form; a fragment that is not a
85
+ // string, and a theme named in lacking, each leave a skip line.
86
+ export const composeKitBlock = ({ fragments, themes, lacking = [] }) => {
87
+ const texts = FRAGMENTS.map(({ id, name }) => (typeof fragments[id] === 'string'
88
+ ? fragments[id].replace(/\r\n/gu, LF).trim()
89
+ : skipLine(name)));
90
+ const rows = themes.filter((theme) => !lacking.includes(theme.name))
91
+ .map((theme) => `| [\`${effectiveOf(theme)}\`](./${effectiveOf(theme)}) | ${theme.readWhen} |`);
92
+ const table = ['| Rules theme | Read when |', '|---|---|', ...rows].join(LF);
93
+ const skips = themes.filter((theme) => lacking.includes(theme.name)).map((theme) => skipLine(themeName(theme.name)));
94
+ return [BLOCK_START, PRECEDENCE_LINE, READ_LINE, ...texts, table, ...skips, BLOCK_END].join(LF + LF);
188
95
  };
189
96
 
190
- // Ensure a single, well-formed slot EXISTS — without filling it. Pure; no fs.
191
- // { status: 'present', text } a well-formed slot already exists → bytes unchanged (idempotent).
192
- // { status: 'inserted', text } absent + exactly one anchor → an EMPTY slot inserted right after
193
- // the anchor line, newline style + all other bytes preserved.
194
- // { status: 'error', text, error } malformed slot, OR (when absent) 0/>1 anchors → bytes unchanged.
195
- export const ensureMarkerSlot = (text, descriptor) => {
196
- const slot = findMarkerSlot(text, descriptor);
197
- if (slot.state === 'ok') return { status: 'present', text };
198
- if (slot.state === 'malformed') return { status: 'error', text, error: slot.reason };
199
- const anchors = countMatches(text, descriptor.anchor);
200
- if (anchors !== 1) {
201
- return {
202
- status: 'error',
203
- text,
204
- error: `expected exactly one ${descriptor.anchorLabel}, found ${anchors} — refusing to guess where the slot belongs; add the slot markers manually`,
205
- };
206
- }
207
- const nl = text.includes('\r\n') ? '\r\n' : '\n';
208
- const match = text.match(descriptor.anchor);
209
- const eol = text.indexOf('\n', match.index);
210
- const insertAt = eol === -1 ? text.length : eol + 1;
211
- const slotText = descriptor.emptySlot.replace(/\n/g, nl);
212
- const block = descriptor.leadingBlank ? `${nl}${slotText}${nl}` : `${slotText}${nl}`;
213
- const out = `${text.slice(0, insertAt)}${block}${text.slice(insertAt)}`;
214
- return { status: 'inserted', text: out };
97
+ // The byte offset where 1-based line n starts, and where its content ends (before its CR and LF).
98
+ const lineStart = (text, n) => {
99
+ let offset = 0;
100
+ for (let line = 1; line < n; line += 1) offset = text.indexOf(LF, offset) + 1;
101
+ return offset;
215
102
  };
216
-
217
- // Bootstrap/upgrade reconciliation policy (pure): ensure the slot exists, then judge the bytes between
218
- // its markers against `fragment`, enforcing the line cap — all as one step the CLI commits with a single
219
- // atomic write. On ANY error the INPUT bytes are returned unchanged.
220
- // reconciled-inserted — slot was absent, inserted at the anchor, then filled.
221
- // reconciled-filled — slot existed but was empty, now filled.
222
- // reconciled-refreshed — slot was filled with a KNOWN PRIOR canonical → replaced with `fragment`.
223
- // reconciled-written — slot held any other content → replaced with `fragment`.
224
- // present-filled — slot already carries `fragment` → left, bytes unchanged.
225
- // error — malformed slot, 0/>1 anchors, a blank fragment, or cap exceeded → input unchanged.
226
- export const reconcileMarkerSlot = (text, descriptor, fragment, { maxLines } = {}) => {
227
- const ensured = ensureMarkerSlot(text, descriptor);
228
- if (ensured.status === 'error') return { status: 'error', text, error: ensured.error };
229
- if (fragment.trim() === '') return { status: 'error', text, error: `the ${descriptor.label} fragment is blank — refusing to write an empty pointer` };
230
- const current = extractMarkerSlot(ensured.text, descriptor);
231
- let status = ensured.status === 'inserted' ? 'reconciled-inserted' : 'reconciled-filled';
232
- if (current.trim() !== '') {
233
- if (normalizeCanonical(current) === normalizeCanonical(fragment)) {
234
- if (maxLines != null && lineCount(ensured.text) > maxLines) {
235
- return { status: 'error', text, error: `AGENTS.md is ${lineCount(ensured.text)} lines (cap ${maxLines}) — trim the file (the current ${descriptor.label} pointer must still fit the cap)` };
236
- }
237
- return { status: 'present-filled', text: ensured.text };
238
- }
239
- const priors = descriptor.knownPriorCanonicals ?? [];
240
- status = priors.some((p) => normalizeCanonical(p) === normalizeCanonical(current)) ? 'reconciled-refreshed' : 'reconciled-written';
241
- }
242
- const injected = injectIntoSlot(ensured.text, descriptor, fragment, { maxLines });
243
- if (injected.status !== 'injected') return { status: 'error', text, error: injected.error };
244
- return { status, text: injected.text };
103
+ const contentEnd = (text, n) => {
104
+ const start = lineStart(text, n);
105
+ const eol = text.indexOf(LF, start);
106
+ const end = eol === -1 ? text.length : eol;
107
+ return text[end - 1] === '\r' ? end - 1 : end;
245
108
  };
246
109
 
247
- // Pure predicate (no fs): can the ensure place this slot (present or insertable)? Every such slot is
248
- // judged against its fragment, so main() reads the engine exactly when this is true. Reuses the SAME
249
- // ensure as reconcileMarkerSlot, so the engine-read guard cannot diverge from the policy.
250
- export const markerSlotEnsurable = (text, descriptor) => ensureMarkerSlot(text, descriptor).status !== 'error';
251
-
252
- // ── methodology-slot exports (delegate to the generic engine, byte-for-byte) ────
253
-
254
- export const findSlot = (text) => findMarkerSlot(text, METHODOLOGY_DESCRIPTOR);
255
- export const injectMethodology = (text, fragment, opts) => injectIntoSlot(text, METHODOLOGY_DESCRIPTOR, fragment, opts);
256
- export const extractSlot = (text) => extractMarkerSlot(text, METHODOLOGY_DESCRIPTOR);
257
- export const ensureSlot = (text) => ensureMarkerSlot(text, METHODOLOGY_DESCRIPTOR);
258
- export const reconcileSlot = (text, fragment, opts) => reconcileMarkerSlot(text, METHODOLOGY_DESCRIPTOR, fragment, opts);
259
-
260
- // The route the reconcile's pointer note names when it wrote a pointer over a different one.
261
- export const POINTER_ROUTE = 'text of your own goes outside the two <!-- workflow: --> comment lines around each pointer';
110
+ // reconcileKitBlock(text, block) → { status: 'current' | 'written' | 'inserted', text } | { status: 'refused', text, lines }.
111
+ export const reconcileKitBlock = (text, block) => {
112
+ const bom = text.startsWith(BOM) ? BOM : '';
113
+ const firstEol = text.indexOf(LF);
114
+ const eol = firstEol > 0 && text[firstEol - 1] === '\r' ? CRLF : LF;
115
+ const composed = block.split(LF).join(eol);
116
+ const found = findKitBlock(text);
117
+ if (found.state === 'malformed') return { status: 'refused', text, lines: found.lines };
118
+ if (found.state === 'absent') return { status: 'inserted', text: `${bom}${composed}${eol}${eol}${text.slice(bom.length)}` };
119
+ const from = Math.max(lineStart(text, found.start), bom.length);
120
+ const to = contentEnd(text, found.end);
121
+ if (normalizeCanonical(text.slice(from, to)) === normalizeCanonical(block)) return { status: 'current', text };
122
+ return { status: 'written', text: `${text.slice(0, from)}${composed}${text.slice(to)}` };
123
+ };
262
124
 
263
- // A cap-refusal is a SOFT, reported skip (distinct from a malformed/anchor STOP) — keyed off the
264
- // stable "(cap N)" substring both cap messages carry, so the dual-slot reconcile can skip the
265
- // orchestration pointer (loud) while keeping the methodology fill, instead of aborting both.
266
- const isCapRefusal = (errorMessage) => typeof errorMessage === 'string' && errorMessage.includes('(cap ');
267
- // The autonomy lane distinguishes the TWO cap messages "(cap " conflates (D4 cap-lane honesty):
268
- // only a FILL-overflow from an in-cap input (injectIntoSlot's "injection would push …") is the soft
269
- // skip — the pointer was genuinely withheld. An ALREADY-over-cap file (reconcileMarkerSlot's
270
- // "AGENTS.md is N lines … trim the file") keeps its distinct over-cap report as a hard refusal,
271
- // never a mislabeled "skipped". Exported so the split is pinned against the real messages.
272
- export const isFillCapRefusal = (errorMessage) =>
273
- isCapRefusal(errorMessage) && errorMessage.includes('injection would push');
125
+ // ── the command ──────────────────────────────────────────────────────────────────────────────────
274
126
 
275
127
  const EXIT = Symbol('inject-methodology.exit');
276
- const ROW_WORDS = { inserted: 'added', kept: 'already present', refreshed: 'refreshed to the current text', written: 'written with the current text' };
277
- // The reconcile line's clause for a judged slot, by its status.
278
- const describeSlot = (descriptor, status) => {
279
- const pointer = `${descriptor.label} pointer`;
280
- const where = descriptor === METHODOLOGY_DESCRIPTOR ? 'at the Session-Protocols anchor' : 'below it';
281
- return {
282
- 'reconciled-inserted': `inserted the ${pointer} ${where} and filled it`,
283
- 'reconciled-filled': `filled the empty ${pointer}`,
284
- 'reconciled-refreshed': `refreshed the ${pointer} to the current canon`,
285
- 'reconciled-written': `wrote the current ${pointer} over a different one`,
286
- 'present-filled': `${pointer} already present`,
287
- }[status];
128
+ const OUTCOME = {
129
+ current: `${TAG} kit block: already current — nothing to do (zero-diff).`,
130
+ written: `${TAG} kit block: written with the current kit text; ${BLOCK_ROUTE}.`,
131
+ inserted: `${TAG} kit block: added at the start of the file; ${BLOCK_ROUTE}.`,
132
+ };
133
+ const refusalLine = (lines) => `${TAG} kit block refused — the workflow:kit comment lines must be exactly one start line before one end line (found on lines ${lines.join(', ')}); fix them, then re-run; ${BLOCK_ROUTE}.`;
134
+ const noteLine = (name) => `${TAG} note: ${name} was not written — the installed engine does not supply it; refresh it with ${INSTALL}.`;
135
+
136
+ // readEngineParts({ env, home }) → { fragments, lacking }, or a throw tagged with exit 1 after the STOP
137
+ // line: the methodology fragment is required; a missing later fragment or engine-homed theme is a skip.
138
+ const readEngineParts = ({ env, home, logError }) => {
139
+ const { dir, source } = resolveEngineDir({ env, home });
140
+ const read = (rel) => {
141
+ try {
142
+ return readEngineFragment(dir, { source, rel });
143
+ } catch (err) {
144
+ logError(`${TAG} reconcile STOP — ${err.message}`);
145
+ throw Object.assign(new Error('exit 1'), { [EXIT]: 1 });
146
+ }
147
+ };
148
+ const fragments = {};
149
+ for (const { id, rel, name } of FRAGMENTS) {
150
+ if (name === undefined || detectEngine(dir, { source, rel }).ok) fragments[id] = read(rel);
151
+ }
152
+ const lacking = THEMES.filter((theme) => theme.home === 'engine' && !detectEngine(dir, { source, rel: theme.template }).ok)
153
+ .map((theme) => theme.name);
154
+ return { fragments, lacking };
288
155
  };
289
156
 
290
- // The return-code entry point (5.1): argv[] + injected env/home → { code, stdout, stderr }, no
291
- // process.argv / process.exit / console inside — an in-process caller is as hermetic as a spawned
292
- // one. The thin shell at the bottom is the only process-coupled code.
157
+ // runCli(argv, { env, home }) → { code, stdout, stderr }; never exits. `reconcile <AGENTS.md>` is the one form.
293
158
  export const runCli = async (argv, deps = {}) => {
294
159
  const { readFile, writeFile, rename, rm } = await import('node:fs/promises');
295
160
  const { dirname, basename, join, resolve } = await import('node:path');
296
161
  const { homedir } = await import('node:os');
297
- const { resolveEngineDir, readEngineFragment, detectEngine, ENGINE_FRAGMENT_REL, ORCHESTRATION_FRAGMENT_REL, AUTONOMY_FRAGMENT_REL } = await import('./engine-source.mjs');
298
162
  const env = deps.env ?? process.env;
299
163
  const home = deps.home ?? homedir();
300
-
301
164
  const stdoutLines = [];
302
165
  const stderrLines = [];
303
166
  const log = (line) => stdoutLines.push(line);
304
167
  const logError = (line) => stderrLines.push(line);
305
168
  const result = (code) => ({
306
169
  code,
307
- stdout: stdoutLines.length > 0 ? `${stdoutLines.join('\n')}\n` : '',
308
- stderr: stderrLines.length > 0 ? `${stderrLines.join('\n')}\n` : '',
170
+ stdout: stdoutLines.length > 0 ? `${stdoutLines.join(LF)}${LF}` : '',
171
+ stderr: stderrLines.length > 0 ? `${stderrLines.join(LF)}${LF}` : '',
309
172
  });
310
- // Nested sourcing helpers end the run from arbitrary depth — a tagged throw the catch below
311
- // translates into the result code (the process.exit of the pre-entry-point CLI).
312
- const stop = (code) => Object.assign(new Error(`exit ${code}`), { [EXIT]: code });
313
-
314
- // `reconcile <AGENTS.md> [fragment.md]` = ensure-slot + inject-if-empty + cap (bootstrap/upgrade) for
315
- // ALL THREE slots; `<AGENTS.md> [fragment.md]` = the legacy inject-into-existing-(methodology)-slot mode.
316
- const mode = argv[0] === 'reconcile' ? 'reconcile' : 'inject';
317
- const rest = mode === 'reconcile' ? argv.slice(1) : argv;
318
- const agentsPath = rest[0];
319
- if (!agentsPath) {
320
- logError('usage: inject-methodology.mjs [reconcile] <path/to/AGENTS.md> [fragment.md]');
173
+ if (argv.length !== 2 || argv[0] !== 'reconcile') {
174
+ logError('usage: inject-methodology.mjs reconcile <path/to/AGENTS.md>');
321
175
  return result(2);
322
176
  }
323
- const explicitFragmentArg = rest[1];
324
- try {
325
- const text = await readFile(resolve(agentsPath), 'utf8');
326
-
327
- // Source a bounded fragment per slot. An explicit [fragment.md] arg (tests + manual) wins and skips
328
- // engine resolution entirely; it binds the METHODOLOGY slot only. Otherwise read it LIVE from the
329
- // installed engine (no bundled mirror) — readEngineFragment THROWS (never falls back) when the engine
330
- // is needed but absent/invalid; sourceFragmentOrStop turns that into a hard, loud STOP carrying the
331
- // install command. The caller invokes this for every slot the ensure can place.
332
- const sourceFragment = async (rel) => {
333
- if (explicitFragmentArg) return readFile(resolve(explicitFragmentArg), 'utf8');
334
- const { dir, source } = resolveEngineDir({ env, home });
335
- return readEngineFragment(dir, { source, rel }); // sync; throws loudly when the engine is absent/invalid
336
- };
337
- const sourceFragmentOrStop = async (label, rel) => {
338
- try {
339
- return await sourceFragment(rel);
340
- } catch (err) {
341
- // Engine needed-but-absent → a hard STOP, distinct from the soft cap-skip. The "methodology
342
- // engine not found/invalid" prefix lets the agent classify this exit (SKILL.md).
343
- logError(`[inject-methodology] ${label} — ${err.message}`);
344
- throw stop(1);
345
- }
346
- };
347
-
348
- // The orchestration + autonomy fragments are the CHAINED (less-critical) pointers. Source each, but
349
- // DISTINGUISH two failures keyed off the engine's own detection (not message text): an engine that
350
- // is VALID but simply TOO OLD to ship the requested fragment is a SOFT skip — the earlier slots'
351
- // results are written and the pointer is reported as withheld (parallel to the cap-skip); only a FULLY
352
- // absent/invalid engine (it cannot supply ANY pointer) is a hard STOP. A read error on a PRESENT
353
- // fragment is a real corruption STOP, NEVER a "too old" skip (don't mislabel a current engine with
354
- // an unreadable fragment). Returns { fragment } on success, { skip } for the soft case, or
355
- // process.exit(1) for the hard STOP.
356
- const sourceChainedFragment = async (rel) => {
357
- const { dir, source } = resolveEngineDir({ env, home });
358
- const chainedStop = (err) => {
359
- logError(`[inject-methodology] reconcile STOP — ${err.message}`);
360
- throw stop(1);
361
- };
362
- if (detectEngine(dir, { source, rel }).ok) {
363
- try {
364
- return { fragment: readEngineFragment(dir, { source, rel }) };
365
- } catch (err) {
366
- chainedStop(err);
367
- }
368
- }
369
- if (detectEngine(dir, { source }).ok) {
370
- return { skip: 'the installed engine is too old to supply it — refresh with `npx @sabaiway/agent-workflow-engine@latest init`' };
371
- }
372
- try {
373
- readEngineFragment(dir, { source, rel }); // throws the canonical install-me error
374
- } catch (err) {
375
- chainedStop(err);
376
- }
377
- };
378
-
177
+ const target = resolve(argv[1]);
379
178
  const writeAtomic = async (out) => {
380
- const tmp = join(dirname(resolve(agentsPath)), `.${basename(agentsPath)}.tmp-${process.pid}-${Date.now()}`);
179
+ const tmp = join(dirname(target), `.${basename(target)}.tmp-${process.pid}-${Date.now()}`);
381
180
  try {
382
181
  await writeFile(tmp, out, 'utf8');
383
- await rename(tmp, resolve(agentsPath));
182
+ await rename(tmp, target);
384
183
  } catch (err) {
385
- await rm(tmp, { force: true }).catch(() => {}); // never leave a temp file behind on failure
184
+ await rm(tmp, { force: true }).catch(() => {});
386
185
  throw err;
387
186
  }
388
187
  };
389
-
390
- if (mode === 'reconcile') {
391
- // ── Slot 1: methodology (the engine read for a slot the ensure can place, then reconcile) ──
392
- const methFragment = markerSlotEnsurable(text, METHODOLOGY_DESCRIPTOR) ? await sourceFragmentOrStop('reconcile STOP', ENGINE_FRAGMENT_REL) : '';
393
- const methResult = reconcileSlot(text, methFragment, { maxLines: AGENTS_MD_CAP });
394
- if (methResult.status === 'error') {
395
- // cap-refusal OR malformed/anchor STOP — preserve the single-slot classification (SKILL.md
396
- // distinguishes by the message); the file is byte-for-byte unchanged either way.
397
- logError(`[inject-methodology] reconcile refused — ${methResult.error}`);
398
- return result(1);
399
- }
400
- const afterMeth = methResult.text; // === text when the methodology slot was already current
401
- const describeMeth = describeSlot(METHODOLOGY_DESCRIPTOR, methResult.status);
402
- // One pointer note when a pointer was written over a different one; the row note follows it.
403
- let pointerWritten = methResult.status === 'reconciled-written';
404
- const reportNotes = (rowWritten = false) => {
405
- if (pointerWritten) log(`[inject-methodology] note: ${POINTER_ROUTE}.`);
406
- if (rowWritten) log(`[inject-methodology] note: ${ROW_ROUTE}.`);
407
- };
408
-
409
- // ── Explicit [fragment.md] binds methodology ONLY → skip the orchestration + autonomy reconciles ──
410
- if (explicitFragmentArg) {
411
- if (afterMeth === text) {
412
- log('[inject-methodology] methodology slot already present and filled — nothing to do (zero-diff).');
413
- return result(0);
414
- }
415
- await writeAtomic(afterMeth);
416
- log(`[inject-methodology] reconcile: ${describeMeth}.`);
417
- reportNotes();
418
- return result(0);
419
- }
420
-
421
- // ── Slot 2: orchestration, reconciled on the methodology-reconciled text (the cap-check then guards
422
- // the COMBINED ≤100). The engine is read whenever the ensure can place the slot. ──
423
- let finalText = afterMeth;
424
- let describeOrch;
425
- let orchSkipped = false;
426
-
427
- const orchSource = markerSlotEnsurable(afterMeth, ORCHESTRATION_DESCRIPTOR)
428
- ? await sourceChainedFragment(ORCHESTRATION_FRAGMENT_REL)
429
- : { fragment: '' };
430
- if (orchSource.skip) {
431
- // Engine too old to supply the recipes pointer → SOFT skip, parallel to the cap-skip: the
432
- // methodology result is written; the recipes pointer is reported as withheld.
433
- orchSkipped = true;
434
- describeOrch = `orchestration-recipes pointer skipped — ${orchSource.skip}`;
435
- } else {
436
- const orchResult = reconcileMarkerSlot(afterMeth, ORCHESTRATION_DESCRIPTOR, orchSource.fragment, { maxLines: AGENTS_MD_CAP });
437
- if (orchResult.status === 'error') {
438
- if (isCapRefusal(orchResult.error)) {
439
- // SOFT skip — keep the methodology result, report the orchestration cap-skip loudly (not
440
- // silent); the orchestration slot is unchanged.
441
- orchSkipped = true;
442
- describeOrch = `orchestration-recipes pointer skipped — ${orchResult.error}`;
443
- } else {
444
- // Malformed orchestration slot/anchor → a hard STOP. No partial write.
445
- logError(`[inject-methodology] reconcile refused (orchestration) — ${orchResult.error}`);
446
- return result(1);
447
- }
448
- } else {
449
- finalText = orchResult.text;
450
- describeOrch = describeSlot(ORCHESTRATION_DESCRIPTOR, orchResult.status);
451
- pointerWritten ||= orchResult.status === 'reconciled-written';
452
- }
453
- }
454
-
455
- // ── Slot 3: autonomy, chained on the orchestration-reconciled text (same combined ≤100 guard).
456
- // D4 invariant: every failure lane SPECIFIC to this slot is a LOUD soft skip that writes the
457
- // earlier slots' results and exits 0 — (i) a too-old engine (no autonomy fragment), (ii) a
458
- // fill-overflow cap refusal, (iii) an ABSENT anchor (the orchestration pair is absent or was
459
- // itself skipped above — a 0-anchors ensure error must not discard the methodology result).
460
- // Malformed autonomy markers, an already-over-cap file, a present-but-unreadable
461
- // fragment, and a fully absent/invalid engine stay hard STOPs. ──
462
- let describeAut;
463
- let autSkipped = false;
464
- const autSlot = findMarkerSlot(finalText, AUTONOMY_DESCRIPTOR);
465
- if (autSlot.state === 'malformed') {
466
- // Malformed markers are a hard STOP on EVERY lane — validated before the soft-skip
467
- // short-circuits so a duplicate/reversed autonomy pair can never ride out as a "skip"
468
- // alongside a partial (methodology) write.
469
- logError(`[inject-methodology] reconcile refused (autonomy) — ${autSlot.reason}`);
188
+ try {
189
+ const text = await readFile(target, 'utf8');
190
+ const { fragments, lacking } = readEngineParts({ env, home, logError });
191
+ const block = composeKitBlock({ fragments, themes: THEMES, lacking });
192
+ const judged = reconcileKitBlock(text, block);
193
+ if (judged.status === 'refused') {
194
+ logError(refusalLine(judged.lines));
470
195
  return result(1);
471
196
  }
472
- if (orchSkipped) {
473
- // The chain is CAUSAL, not merely positional: a pointer never lands in a run that withheld
474
- // the pointer it chains below (cap or too-old) — otherwise a partially-shipped engine could
475
- // fill autonomy under an unfilled recipes pointer, and a near-cap file could spend its last
476
- // lines on the less-critical pointer. LOUD soft skip. This branch also subsumes the D4 (iii)
477
- // anchor-absent lane: after a non-skipped orchestration reconcile the orchestration pair —
478
- // the autonomy anchor — is present by construction, so orchSkipped is the ONLY route to a
479
- // missing anchor (a separate anchor check would be dead code; coverage proved it).
480
- autSkipped = true;
481
- describeAut =
482
- 'autonomy pointer skipped — chained below the orchestration pointer, which was itself skipped this run; re-run once it lands';
483
- } else {
484
- const autSource = markerSlotEnsurable(finalText, AUTONOMY_DESCRIPTOR)
485
- ? await sourceChainedFragment(AUTONOMY_FRAGMENT_REL)
486
- : { fragment: '' };
487
- if (autSource.skip) {
488
- autSkipped = true;
489
- describeAut = `autonomy pointer skipped — ${autSource.skip}`;
490
- } else {
491
- const autResult = reconcileMarkerSlot(finalText, AUTONOMY_DESCRIPTOR, autSource.fragment, { maxLines: AGENTS_MD_CAP });
492
- if (autResult.status === 'error') {
493
- if (isFillCapRefusal(autResult.error)) {
494
- // SOFT skip — only the genuine fill-overflow withholds the pointer; an already-over-cap
495
- // file keeps its distinct over-cap report via the hard-STOP branch below.
496
- autSkipped = true;
497
- describeAut = `autonomy pointer skipped — ${autResult.error}`;
498
- } else {
499
- logError(`[inject-methodology] reconcile refused (autonomy) — ${autResult.error}`);
500
- return result(1);
501
- }
502
- } else {
503
- finalText = autResult.text;
504
- describeAut = describeSlot(AUTONOMY_DESCRIPTOR, autResult.status);
505
- pointerWritten ||= autResult.status === 'reconciled-written';
506
- }
507
- }
508
- }
509
-
510
- // ── The Memory Map rows on the three-slot text, then one atomic write ──
511
- const rows = reconcileMemoryMapRows(finalText, { maxLines: AGENTS_MD_CAP });
512
- const describeRows = rows.outcomes.map((o) => `the ${o.theme} Memory Map row ${ROW_WORDS[o.status] ?? `skipped — ${o.note}`}`).join('; ');
513
- const rowWritten = rows.outcomes.some((o) => o.status === 'written');
514
- if (rows.text === text) {
515
- // Byte-unchanged. Still report a skip (it is not "nothing to do" — a pointer was withheld).
516
- if (orchSkipped || autSkipped) log(`[inject-methodology] reconcile: ${describeMeth}; ${describeOrch}; ${describeAut}; ${describeRows}.`);
517
- else log(`[inject-methodology] reconcile: all three pointers already present and filled; ${describeRows} — nothing to do (zero-diff).`);
518
- return result(0);
519
- }
520
- await writeAtomic(rows.text);
521
- log(`[inject-methodology] reconcile: ${describeMeth}; ${describeOrch}; ${describeAut}; ${describeRows}.`);
522
- reportNotes(rowWritten);
523
- return result(0);
524
- }
525
-
526
- // Legacy inject-into-existing-slot mode (METHODOLOGY only). injectMethodology no-ops on absent markers
527
- // and errors on a malformed slot WITHOUT reading the fragment, so resolve+read the engine only when
528
- // there is a present (ok) slot to fill — a markerless legacy AGENTS.md stays a no-op without the engine.
529
- const fragment = findSlot(text).state === 'ok' ? await sourceFragmentOrStop('STOP', ENGINE_FRAGMENT_REL) : '';
530
- const injected = injectMethodology(text, fragment, { maxLines: AGENTS_MD_CAP });
531
- if (injected.status === 'error') {
532
- logError(`[inject-methodology] malformed slot — refusing to edit: ${injected.error}`);
533
- return result(1);
534
- }
535
- if (injected.status === 'noop-absent') {
536
- log('[inject-methodology] no methodology markers found — nothing to inject (legacy AGENTS.md).');
197
+ if (judged.status !== 'current') await writeAtomic(judged.text);
198
+ log(OUTCOME[judged.status]);
199
+ const skipped = [...FRAGMENTS.filter(({ id }) => typeof fragments[id] !== 'string').map(({ name }) => name), ...lacking.map(themeName)];
200
+ skipped.forEach((name) => log(noteLine(name)));
537
201
  return result(0);
538
- }
539
- await writeAtomic(injected.text);
540
- log('[inject-methodology] injected the bounded methodology fragment into the slot.');
541
- return result(0);
542
202
  } catch (err) {
543
203
  if (err[EXIT] !== undefined) return result(err[EXIT]);
544
204
  throw err;