@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.
- package/CHANGELOG.md +67 -0
- package/README.md +18 -10
- package/SKILL.md +6 -6
- package/bin/install.mjs +1 -1
- package/capability.json +1 -1
- package/migrations/1.1.0-communication-language.md +2 -4
- package/migrations/1.2.0-agent-attribution.md +1 -3
- package/migrations/5.0.0-kit-text-in-kit-files.md +30 -0
- package/migrations/README.md +2 -2
- package/package.json +1 -1
- package/references/advisor-writers.md +1 -1
- package/references/contracts.md +9 -11
- package/references/modes/bootstrap.md +2 -4
- package/references/modes/hook.md +1 -1
- package/references/modes/procedures.md +1 -1
- package/references/modes/recommendations.md +1 -1
- package/references/modes/rules.md +4 -3
- package/references/modes/upgrade.md +23 -49
- package/references/modes/velocity.md +1 -1
- package/references/reference-profile.json +0 -6
- package/references/rules/communication.md +22 -0
- package/references/rules/project-layout.md +2 -0
- package/references/rules/story-sessions.md +14 -0
- package/references/shared/composition-handoff.md +24 -59
- package/references/shared/deploy-tail.md +2 -2
- package/references/templates/AGENTS.md +0 -10
- package/references/templates/agent_rules.md +0 -33
- package/tools/cheap-agents-read.mjs +1 -1
- package/tools/delegation.mjs +5 -8
- package/tools/engine-source.mjs +13 -11
- package/tools/family-registry.mjs +4 -5
- package/tools/inject-methodology.mjs +153 -493
- package/tools/migration-blocks.mjs +0 -6
- package/tools/orchestration-readme.mjs +1 -1
- package/tools/payload-prune.mjs +48 -8
- package/tools/profile-gap-screen.mjs +2 -6
- package/tools/profile-gaps.mjs +19 -100
- package/tools/project-rules/index.mjs +1 -2
- package/tools/project-rules/rules-ensure.mjs +37 -6
- package/tools/project-rules/rules-priors.mjs +1 -0
- package/tools/project-rules/themes.mjs +13 -5
- package/tools/transition/index.mjs +214 -0
- package/tools/upgrade-runlist.mjs +2 -17
- package/tools/velocity-profile.mjs +1 -1
- package/tools/lens-region.mjs +0 -281
- package/tools/project-rules/memory-map-row.mjs +0 -81
- package/tools/rules-insert.mjs +0 -203
- package/tools/rules-regions.mjs +0 -190
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The lineage 5.0.0 transition: once per deployment, after upgrade step 3 wrote the kit block and the
|
|
3
|
+
// rules themes, it removes the kit's old copies from AGENTS.md and docs/ai/agent_rules.md, found by the
|
|
4
|
+
// kit's old landmarks, which live only here and in the migration note. While a replacement is missing it
|
|
5
|
+
// refuses with nothing written. Never asks; main returns and never exits. Dependency-free, Node >= 22.
|
|
6
|
+
// Contract: docs/ai/specs/kit/transition/.
|
|
7
|
+
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
import { tokenizeMarkdown } from '../../references/scripts/markdown-blocks.mjs';
|
|
10
|
+
import { writeContainedFileAtomic } from '../atomic-write.mjs';
|
|
11
|
+
import { isDirectRun } from '../direct-run.mjs';
|
|
12
|
+
import { probeRegularFileNoFollow, readRegularFileNoFollow } from '../fs-read-nofollow.mjs';
|
|
13
|
+
import { findKitBlock, SKIP_PREFIX } from '../inject-methodology.mjs';
|
|
14
|
+
|
|
15
|
+
const LF = '\n';
|
|
16
|
+
const BOM = '';
|
|
17
|
+
const AGENTS_REL = 'AGENTS.md';
|
|
18
|
+
const RULES_REL = 'docs/ai/agent_rules.md';
|
|
19
|
+
const LENS_REL = 'docs/ai/rules/lens.md';
|
|
20
|
+
const USAGE = 'usage: transition/index.mjs --cwd <project>';
|
|
21
|
+
const UPGRADE_AGAIN = 'run the upgrade again: its step 3 writes the kit block or names its malformed lines';
|
|
22
|
+
const ENGINE_REFRESH = 'run npx @sabaiway/agent-workflow-engine@latest init, then run the upgrade again';
|
|
23
|
+
|
|
24
|
+
// The kit's old landmarks (lineage below 5.0.0): three pointer pairs, the Memory Map row of each rules
|
|
25
|
+
// theme and the line-cap footer in AGENTS.md; the title words of three sections in the rules file.
|
|
26
|
+
const POINTERS = ['methodology', 'orchestration', 'autonomy'];
|
|
27
|
+
const MARKER_RE = new RegExp(`^<!-- workflow:(${POINTERS.join('|')}):(start|end) -->$`, 'u');
|
|
28
|
+
const THEME_ROW_RE = /^\| \[`docs\/ai\/rules\/effective\/([^`/\s]+)\.md`\]\(\.\/docs\/ai\/rules\/effective\/\1\.md\) \|/u;
|
|
29
|
+
const FOOTER = '**Rule:** This file stays CONCISE (≤100 lines). Details go to `docs/ai/`. Never bloat this file.';
|
|
30
|
+
const TITLES = ['Communication (user-facing messages)', 'Story sessions', 'Planning, review & process-fidelity'];
|
|
31
|
+
const HEADING_RE = /^ {0,3}#{1,6}[ \t]+(.*)$/u;
|
|
32
|
+
const NUMBER_PREFIX_RE = /^[0-9.]+ +/u;
|
|
33
|
+
|
|
34
|
+
const REFUSAL = Symbol('transition.refusal');
|
|
35
|
+
const shown = (text) => text.replace(/[\u0000-\u001f\u007f]/gu, ' ');
|
|
36
|
+
const refuse = (name, detail) => {
|
|
37
|
+
throw Object.assign(new Error(`${name}: ${shown(detail)}`), { [REFUSAL]: true });
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// ── reading: the no-follow read, then the tokenizer's one definition of fences and headings ─────────
|
|
41
|
+
|
|
42
|
+
const readProjectFile = (cwd, rel, io) => {
|
|
43
|
+
const read = readRegularFileNoFollow(join(cwd, rel), io);
|
|
44
|
+
if (read.outcome === 'absent') return null;
|
|
45
|
+
if (read.outcome === 'ok') {
|
|
46
|
+
const bom = read.content.startsWith(BOM) ? BOM : '';
|
|
47
|
+
return { rel, bom, text: read.content.slice(bom.length) };
|
|
48
|
+
}
|
|
49
|
+
if (read.className === 'symlink') {
|
|
50
|
+
refuse('file-symlink', `${rel} is a symbolic link; replace the link with a regular file holding its text, then run the upgrade again`);
|
|
51
|
+
}
|
|
52
|
+
const what = read.outcome === 'foreign' ? `is a ${read.className}` : `could not be read (${read.code})`;
|
|
53
|
+
return refuse('file-unreadable', `${rel} ${what}; make it a readable regular file, then run the upgrade again`);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// parse(file) → the file with its lines (each with its own ending), their contents, the opaque lines
|
|
57
|
+
// (frontmatter and fenced, never judged) and the heading lines by index with their levels.
|
|
58
|
+
const parse = (file) => {
|
|
59
|
+
let tokens;
|
|
60
|
+
try {
|
|
61
|
+
tokens = tokenizeMarkdown(file.text, file.rel);
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (err.exitCode === undefined) throw err;
|
|
64
|
+
refuse('file-unparseable', `${err.message} — close the fence or separate the leading --- block, then run the upgrade again`);
|
|
65
|
+
}
|
|
66
|
+
const { frontLines } = tokens;
|
|
67
|
+
const pieces = file.text === '' ? [] : file.text.split(/(?<=\n)/u);
|
|
68
|
+
const opaque = new Set([...Array(frontLines).keys(), ...[...tokens.fencedLines].map((at) => at + frontLines)]);
|
|
69
|
+
const headings = new Map(tokens.headings.map(({ index, level }) => [index + frontLines, level]));
|
|
70
|
+
const contents = pieces.map((piece) => piece.replace(/\n$/u, '').replace(/\r$/u, ''));
|
|
71
|
+
return { ...file, pieces, contents, opaque, headings };
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// ── the first step: nothing is removed while the replacement is not there ──────────────────────────
|
|
75
|
+
|
|
76
|
+
const firstStep = (agents, cwd, io) => {
|
|
77
|
+
if (agents === null) {
|
|
78
|
+
refuse('replacement-missing', 'no AGENTS.md; create AGENTS.md, then run the upgrade again: its step 3 writes the kit block');
|
|
79
|
+
}
|
|
80
|
+
const block = findKitBlock(agents.text);
|
|
81
|
+
if (block.state === 'absent') refuse('replacement-missing', `no kit block in AGENTS.md; ${UPGRADE_AGAIN}`);
|
|
82
|
+
if (block.state !== 'ok') refuse('replacement-missing', `a malformed kit block in AGENTS.md; ${UPGRADE_AGAIN}`);
|
|
83
|
+
if (agents.contents.slice(block.start - 1, block.end).some((line) => line.startsWith(SKIP_PREFIX))) {
|
|
84
|
+
refuse('replacement-missing', `a skipped engine text in the kit block; ${ENGINE_REFRESH}`);
|
|
85
|
+
}
|
|
86
|
+
if (probeRegularFileNoFollow(join(cwd, LENS_REL), io).outcome !== 'ok') {
|
|
87
|
+
refuse('replacement-missing', `no ${LENS_REL}; ${ENGINE_REFRESH}`);
|
|
88
|
+
}
|
|
89
|
+
return block;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// ── the removals: spans { from, to, what } of 0-based line indexes, both ends included ─────────────
|
|
93
|
+
|
|
94
|
+
const covers = (spans, at) => spans.some((span) => at >= span.from && at <= span.to);
|
|
95
|
+
|
|
96
|
+
// One run of AGENTS.md lines [from, to): the pointer pairs first, then the theme rows and the footer on
|
|
97
|
+
// the lines no pair removed. Nothing pairs across a run's edge.
|
|
98
|
+
const agentsRunSpans = (doc, from, to) => {
|
|
99
|
+
const judged = (at) => at >= from && at < to && !doc.opaque.has(at);
|
|
100
|
+
const open = Object.fromEntries(POINTERS.map((name) => [name, []]));
|
|
101
|
+
const pairs = [];
|
|
102
|
+
for (let at = from; at < to; at += 1) {
|
|
103
|
+
const marker = judged(at) && MARKER_RE.exec(doc.contents[at].trim());
|
|
104
|
+
if (!marker) continue;
|
|
105
|
+
const [, name, edge] = marker;
|
|
106
|
+
if (edge === 'start') open[name].push(at);
|
|
107
|
+
else if (open[name].length > 0) pairs.push({ from: open[name].pop(), to: at, what: `the ${name} pointer and its text` });
|
|
108
|
+
}
|
|
109
|
+
const spans = pairs.filter((pair) => !pairs.some((other) => other !== pair && other.from <= pair.from && other.to >= pair.to));
|
|
110
|
+
const free = (at) => judged(at) && !covers(pairs, at);
|
|
111
|
+
for (let at = from; at < to; at += 1) {
|
|
112
|
+
if (!free(at)) continue;
|
|
113
|
+
const row = THEME_ROW_RE.exec(doc.contents[at]);
|
|
114
|
+
if (row) spans.push({ from: at, to: at, what: `the Memory Map row of docs/ai/rules/effective/${row[1]}.md` });
|
|
115
|
+
else if (doc.contents[at].trim() === FOOTER) {
|
|
116
|
+
const placed = free(at - 1) && free(at - 2) && doc.contents[at - 1].trim() === '' && doc.contents[at - 2].trim() === '---';
|
|
117
|
+
spans.push({ from: placed ? at - 2 : at, to: at, what: 'the line-cap footer' });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return spans;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const agentsSpans = (doc, block) => [
|
|
124
|
+
...agentsRunSpans(doc, 0, block.start - 1),
|
|
125
|
+
...agentsRunSpans(doc, block.end, doc.pieces.length),
|
|
126
|
+
];
|
|
127
|
+
|
|
128
|
+
// The rules file: a heading whose title, its number prefix taken off, opens with kit title words opens a
|
|
129
|
+
// section that runs to the next heading of the same or a higher level or a --- line, outside fences.
|
|
130
|
+
const rulesSpans = (doc) => {
|
|
131
|
+
const ends = (at, level) => !doc.opaque.has(at) && (doc.contents[at].trim() === '---' || doc.headings.get(at) <= level);
|
|
132
|
+
const spans = [];
|
|
133
|
+
for (const [at, level] of doc.headings) {
|
|
134
|
+
if (covers(spans, at)) continue;
|
|
135
|
+
const title = HEADING_RE.exec(doc.contents[at].trimEnd())[1].replace(NUMBER_PREFIX_RE, '');
|
|
136
|
+
if (!TITLES.some((words) => title.startsWith(words))) continue;
|
|
137
|
+
let to = at + 1;
|
|
138
|
+
while (to < doc.pieces.length && !ends(to, level)) to += 1;
|
|
139
|
+
spans.push({ from: at, to: to - 1, what: `the section ${shown(title)}` });
|
|
140
|
+
}
|
|
141
|
+
return spans;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
// The output stays a text the tokenizer accepts: a --- line the removals would bring to the top of a
|
|
145
|
+
// file that did not open with one goes with the removed span directly above it.
|
|
146
|
+
const keepParseable = (doc, found) => {
|
|
147
|
+
const spans = found.map((span) => ({ ...span })).sort((a, b) => a.from - b.from);
|
|
148
|
+
if (doc.contents[0]?.trim() === '---') return spans;
|
|
149
|
+
for (;;) {
|
|
150
|
+
let first = 0;
|
|
151
|
+
while (first < doc.pieces.length && covers(spans, first)) first += 1;
|
|
152
|
+
if (first === 0 || first === doc.pieces.length || doc.contents[first].trim() !== '---') return spans;
|
|
153
|
+
spans.find((span) => span.to === first - 1).to = first;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const removedText = (doc, spans) => doc.bom + doc.pieces.filter((_, at) => !covers(spans, at)).join('');
|
|
158
|
+
|
|
159
|
+
const reportLines = (doc, rel, spans) => {
|
|
160
|
+
if (doc === null) return [`unchanged: ${rel}: absent`];
|
|
161
|
+
if (spans.length === 0) return [`unchanged: ${rel}: nothing of the old layout found`];
|
|
162
|
+
return spans.map(({ from, to, what }) =>
|
|
163
|
+
`removed: ${rel}: ${what} (${from === to ? `line ${from + 1}` : `lines ${from + 1}-${to + 1}`})`);
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// ── the command ──────────────────────────────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
// main(argv, deps) → { code, stdout, stderr }; deps is the bag of fs primitives the read and write
|
|
169
|
+
// guards take (readRegularFileNoFollow's io, writeContainedFileAtomic's deps).
|
|
170
|
+
export const main = async (argv, deps = {}) => {
|
|
171
|
+
const stdout = [];
|
|
172
|
+
const stderr = [];
|
|
173
|
+
const text = (lines) => (lines.length > 0 ? `${lines.join(LF)}${LF}` : '');
|
|
174
|
+
const result = (code) => ({ code, stdout: text(stdout), stderr: text(stderr) });
|
|
175
|
+
if (argv.length !== 2 || argv[0] !== '--cwd' || argv[1] === '' || argv[1].startsWith('--')) {
|
|
176
|
+
stderr.push(USAGE);
|
|
177
|
+
return result(2);
|
|
178
|
+
}
|
|
179
|
+
const cwd = resolve(argv[1]);
|
|
180
|
+
try {
|
|
181
|
+
const agentsFile = readProjectFile(cwd, AGENTS_REL, deps);
|
|
182
|
+
const rulesFile = readProjectFile(cwd, RULES_REL, deps);
|
|
183
|
+
const agents = agentsFile && parse(agentsFile);
|
|
184
|
+
const rules = rulesFile && parse(rulesFile);
|
|
185
|
+
const block = firstStep(agents, cwd, deps);
|
|
186
|
+
const judged = [
|
|
187
|
+
{ rel: AGENTS_REL, doc: agents, spans: keepParseable(agents, agentsSpans(agents, block)) },
|
|
188
|
+
{ rel: RULES_REL, doc: rules, spans: rules === null ? [] : keepParseable(rules, rulesSpans(rules)) },
|
|
189
|
+
];
|
|
190
|
+
const written = [];
|
|
191
|
+
for (const { rel, doc, spans } of judged) {
|
|
192
|
+
if (spans.length === 0) continue;
|
|
193
|
+
try {
|
|
194
|
+
writeContainedFileAtomic(cwd, join(cwd, rel), removedText(doc, spans), deps, { label: rel });
|
|
195
|
+
} catch (err) {
|
|
196
|
+
refuse('write-failed', `${rel}: ${err?.message ?? err} — already written: ${written.join(', ') || 'none'}, with no rollback; make it writable, then run the upgrade again`);
|
|
197
|
+
}
|
|
198
|
+
written.push(rel);
|
|
199
|
+
}
|
|
200
|
+
for (const { rel, doc, spans } of judged) stdout.push(...reportLines(doc, rel, spans));
|
|
201
|
+
return result(0);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
if (!err[REFUSAL]) throw err;
|
|
204
|
+
stderr.push(err.message);
|
|
205
|
+
return result(1);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
if (isDirectRun(import.meta.url)) {
|
|
210
|
+
const { code, stdout, stderr } = await main(process.argv.slice(2));
|
|
211
|
+
if (stdout) process.stdout.write(stdout);
|
|
212
|
+
if (stderr) process.stderr.write(stderr);
|
|
213
|
+
process.exitCode = code;
|
|
214
|
+
}
|
|
@@ -20,10 +20,10 @@ const entry = (id, command, consent, outcomes) =>
|
|
|
20
20
|
|
|
21
21
|
export const UPGRADE_RUNLIST = Object.freeze([
|
|
22
22
|
entry(
|
|
23
|
-
'
|
|
23
|
+
'entry-block',
|
|
24
24
|
'node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md',
|
|
25
25
|
null,
|
|
26
|
-
['added', 'already
|
|
26
|
+
['added', 'already current', 'written', 'refused', 'STOP'],
|
|
27
27
|
),
|
|
28
28
|
entry(
|
|
29
29
|
'footprint',
|
|
@@ -71,21 +71,6 @@ export const UPGRADE_RUNLIST = Object.freeze([
|
|
|
71
71
|
'could not refresh',
|
|
72
72
|
],
|
|
73
73
|
),
|
|
74
|
-
entry(
|
|
75
|
-
'lens',
|
|
76
|
-
'node ${CLAUDE_SKILL_DIR}/tools/lens-region.mjs reconcile <project>/docs/ai/agent_rules.md',
|
|
77
|
-
null,
|
|
78
|
-
[
|
|
79
|
-
'refreshed',
|
|
80
|
-
'already current',
|
|
81
|
-
'differing body written',
|
|
82
|
-
'file absent',
|
|
83
|
-
'engine too old',
|
|
84
|
-
'over the line cap — refused',
|
|
85
|
-
'section absent — noted',
|
|
86
|
-
'STOP',
|
|
87
|
-
],
|
|
88
|
-
),
|
|
89
74
|
entry(
|
|
90
75
|
'tier',
|
|
91
76
|
'node ${CLAUDE_SKILL_DIR}/tools/tier-preview.mjs --cwd <project>',
|
|
@@ -32,7 +32,7 @@ import { resolveDeclaredDir, dirCovers, isResolvableDeclaredEntry } from './decl
|
|
|
32
32
|
|
|
33
33
|
// Deployment-lineage head this velocity build targets; bump together with agent-workflow-memory
|
|
34
34
|
// LINEAGE_HEAD when the deployed docs/ai structure changes.
|
|
35
|
-
export const EXPECTED_WORKFLOW_VERSION = '
|
|
35
|
+
export const EXPECTED_WORKFLOW_VERSION = '5.0.0';
|
|
36
36
|
export const SETTINGS_FILE = '.claude/settings.json';
|
|
37
37
|
export const SETTINGS_LOCAL_FILE = '.claude/settings.local.json';
|
|
38
38
|
export const CLAUDE_DIR = '.claude';
|
package/tools/lens-region.mjs
DELETED
|
@@ -1,281 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// The only mutation of a deployed rules file the composition root runs WITHOUT a consent ask.
|
|
3
|
-
import { isDirectRun } from './direct-run.mjs';
|
|
4
|
-
import { normalizeCanonical } from './orchestration-config.mjs';
|
|
5
|
-
import { RULES_REGIONS, extractRegionBy, readTemplateSpan, frontmatterMaxLines, exceedsCap, buildInsertPreview, decodeUtf8Strict } from './rules-regions.mjs';
|
|
6
|
-
|
|
7
|
-
export { frontmatterMaxLines } from './rules-regions.mjs';
|
|
8
|
-
export const REGION_ROUTE = "text of your own goes under a ### heading of its own, titled unlike the kit's sections";
|
|
9
|
-
const [COMMUNICATION, STORY, LENS] = RULES_REGIONS;
|
|
10
|
-
export const LENS_HEADING_RE = LENS.headingRe;
|
|
11
|
-
export const COMMS_HEADING_RE = COMMUNICATION.headingRe;
|
|
12
|
-
export const COMMS_PRIORS = COMMUNICATION.priors;
|
|
13
|
-
const LF = String.fromCharCode(10);
|
|
14
|
-
const CR = String.fromCharCode(13);
|
|
15
|
-
const CRLF = CR + LF;
|
|
16
|
-
const BACKSLASH = String.fromCharCode(92);
|
|
17
|
-
const BACKTICK = String.fromCharCode(96);
|
|
18
|
-
const EM_DASH = String.fromCharCode(8212);
|
|
19
|
-
const EXIT_OK = 0;
|
|
20
|
-
const EXIT_STOP = 1;
|
|
21
|
-
const EXIT_USAGE = 2;
|
|
22
|
-
const CLI_ARG_COUNT = 2;
|
|
23
|
-
const SCRIPT_ARG_OFFSET = 2;
|
|
24
|
-
const SINGLE_HEADING = 1;
|
|
25
|
-
const HEX_RADIX = 16;
|
|
26
|
-
const UNICODE_WIDTH = 4;
|
|
27
|
-
const UTF8 = 'utf8';
|
|
28
|
-
const RECONCILE_COMMAND = 'reconcile';
|
|
29
|
-
const USAGE = 'usage: lens-region.mjs reconcile <path/to/agent_rules.md>';
|
|
30
|
-
const PRIOR_START = '<!-- prior';
|
|
31
|
-
const PRIOR_END = '-->';
|
|
32
|
-
const NUMBERED_HEADING_RE = /^### 2[.][0-9]+[.]/;
|
|
33
|
-
const NEUTRAL_HEADING = '### 2.x.';
|
|
34
|
-
const NEUTRAL_LENS_RE = /^### 2[.]x[.] Planning, review & process-fidelity/;
|
|
35
|
-
const NEUTRAL_COMMS_RE = /^### 2[.]x[.] Communication [(]user-facing messages[)]/;
|
|
36
|
-
const NEUTRAL_STORY_RE = /^### 2[.]x[.] Story sessions/;
|
|
37
|
-
const LINE_UNSAFE = new RegExp(`[${BACKSLASH}u007f-${BACKSLASH}u009f${BACKSLASH}u2028${BACKSLASH}u2029]`, 'g');
|
|
38
|
-
const HUMAN_UNSAFE = new RegExp(`[${BACKSLASH}u0000-${BACKSLASH}u001f${BACKSLASH}u007f-${BACKSLASH}u009f${BACKSLASH}u2028${BACKSLASH}u2029]+`, 'g');
|
|
39
|
-
const SERVED_TARGET = ['docs', 'ai', 'agent_rules.md'];
|
|
40
|
-
const insertNote = (command) => command ? [`[lens-region] note: preview the absent section with \`${command}\`; use \`--apply\` only after an explicit yes.`] : [];
|
|
41
|
-
const OUTCOME_PREFIXES = Object.freeze({ communication: 'comms', 'story-sessions': 'story', lens: 'lens' });
|
|
42
|
-
const stripCr = (line) => (line.endsWith(CR) ? line.slice(0, -1) : line);
|
|
43
|
-
const escUnsafe = (character) => `${BACKSLASH}u${character.codePointAt(0).toString(HEX_RADIX).padStart(UNICODE_WIDTH, '0')}`;
|
|
44
|
-
const errorDetail = (raw) => `[lens-region] error=${JSON.stringify(String(raw)).replace(LINE_UNSAFE, escUnsafe)}`;
|
|
45
|
-
const oneLine = (value) => String(value).replace(HUMAN_UNSAFE, ' ');
|
|
46
|
-
const spanFree = (value) => oneLine(value).replaceAll(BACKTICK, escUnsafe(BACKTICK));
|
|
47
|
-
|
|
48
|
-
export const parseLensPriors = (text) => {
|
|
49
|
-
const entries = [];
|
|
50
|
-
for (const line of String(text).split(LF)) {
|
|
51
|
-
const bare = stripCr(line);
|
|
52
|
-
if (bare.startsWith(PRIOR_START) && bare.endsWith(PRIOR_END)) {
|
|
53
|
-
entries.push([]);
|
|
54
|
-
} else if (entries.length) {
|
|
55
|
-
entries.at(-1).push(line);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return entries.map((entry) => normalizeCanonical(entry.join(LF))).filter((entry) => entry !== '');
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
const renderRegion = (fragment, number, headingRe) =>
|
|
62
|
-
normalizeCanonical(fragment).replace(headingRe, (heading) => heading.replace('2.x', `2.${number}`));
|
|
63
|
-
export const renderLens = (fragment, number) => renderRegion(fragment, number, NEUTRAL_LENS_RE);
|
|
64
|
-
export const renderComms = (fragment, number) => renderRegion(fragment, number, NEUTRAL_COMMS_RE);
|
|
65
|
-
export const renderStory = (fragment, number) => renderRegion(fragment, number, NEUTRAL_STORY_RE);
|
|
66
|
-
export const normalizeLensBody = (body) =>
|
|
67
|
-
normalizeCanonical(String(body).replace(NUMBERED_HEADING_RE, NEUTRAL_HEADING));
|
|
68
|
-
export const normalizeCommsBody = normalizeLensBody;
|
|
69
|
-
export const normalizeStoryBody = normalizeLensBody;
|
|
70
|
-
export const extractLensRegion = (text) => extractRegionBy(text, LENS_HEADING_RE);
|
|
71
|
-
export const extractCommsRegion = (text) => extractRegionBy(text, COMMS_HEADING_RE);
|
|
72
|
-
export const extractStoryRegion = (text) => extractRegionBy(text, STORY.headingRe);
|
|
73
|
-
|
|
74
|
-
export const replaceLensRegion = (text, region, renderedBody) => {
|
|
75
|
-
const lines = String(text).split(LF);
|
|
76
|
-
const crlf = String(text).includes(CRLF);
|
|
77
|
-
const regionLines = lines.slice(region.start, region.end);
|
|
78
|
-
const bodyEnd = regionLines.findLastIndex((line) => stripCr(line).trim() !== '') + 1;
|
|
79
|
-
const trailing = regionLines.slice(bodyEnd);
|
|
80
|
-
const newBody = renderedBody.split(LF).map((line) => (crlf ? line + CR : line));
|
|
81
|
-
const out = [...lines.slice(0, region.start), ...newBody, ...trailing, ...lines.slice(region.end)];
|
|
82
|
-
// At EOF without a newline, the final line must not gain a dangling CR.
|
|
83
|
-
if (crlf && trailing.length === 0 && region.end === lines.length) {
|
|
84
|
-
out[out.length - 1] = stripCr(out.at(-1));
|
|
85
|
-
}
|
|
86
|
-
return out.join(LF);
|
|
87
|
-
};
|
|
88
|
-
|
|
89
|
-
const reconcileRegionText = (text, fragment, priors, { extract, normalize, render }) => {
|
|
90
|
-
const region = extract(text);
|
|
91
|
-
if (!region.found) return { status: 'no-region', text };
|
|
92
|
-
if (region.count > SINGLE_HEADING) return { status: 'doubled', text };
|
|
93
|
-
const current = normalize(region.body);
|
|
94
|
-
const canon = normalize(fragment);
|
|
95
|
-
if (current === canon) return { status: 'current', text };
|
|
96
|
-
const known = priors.map((prior) => normalize(prior));
|
|
97
|
-
const status = known.includes(current) ? 'refreshed' : 'custom';
|
|
98
|
-
return { status, text: replaceLensRegion(text, region, render(fragment, region.number)) };
|
|
99
|
-
};
|
|
100
|
-
export const reconcileLensText = (text, fragment, priors) =>
|
|
101
|
-
reconcileRegionText(text, fragment, priors, { extract: extractLensRegion, normalize: normalizeLensBody, render: renderLens });
|
|
102
|
-
export const reconcileCommsText = (text, fragment, priors) =>
|
|
103
|
-
reconcileRegionText(text, fragment, priors, { extract: extractCommsRegion, normalize: normalizeCommsBody, render: renderComms });
|
|
104
|
-
export const reconcileStoryText = (text, fragment, priors) =>
|
|
105
|
-
reconcileRegionText(text, fragment, priors, { extract: extractStoryRegion, normalize: normalizeStoryBody, render: renderStory });
|
|
106
|
-
const RECONCILERS = Object.freeze({ communication: reconcileCommsText, 'story-sessions': reconcileStoryText, lens: reconcileLensText });
|
|
107
|
-
|
|
108
|
-
const writtenLine = (section) => `[lens-region] the ${section} differed from the current canon ${EM_DASH} written with it; ${REGION_ROUTE}.`;
|
|
109
|
-
const capRefusedLine = (section, target, count, cap, capWord = 'cap') => `[lens-region] refused ${EM_DASH} writing the current ${section} would push ${oneLine(target)} to ${count} lines (${capWord} ${cap}); trim the file and re-run. The ${section} was not changed.`;
|
|
110
|
-
|
|
111
|
-
export const OUTCOME_LINES = Object.freeze({
|
|
112
|
-
errorDetail,
|
|
113
|
-
targetAbsent: (target) => `[lens-region] ${oneLine(target)} is absent ${EM_DASH} skipped (nothing to update; the file is seeded at bootstrap).`,
|
|
114
|
-
targetNotRegular: (target) => `[lens-region] ${oneLine(target)} is a link or not a regular file ${EM_DASH} left as it stands; nothing written.`,
|
|
115
|
-
targetUndecodable: (target) => `[lens-region] ${oneLine(target)} is not valid UTF-8 ${EM_DASH} nothing written; fix its encoding and re-run.`,
|
|
116
|
-
commsNoRegion: (target, command) => [
|
|
117
|
-
`[lens-region] no "${COMMUNICATION.label}" section in ${spanFree(target)} ${EM_DASH} left untouched.`,
|
|
118
|
-
...insertNote(command),
|
|
119
|
-
],
|
|
120
|
-
commsCurrent: () => `[lens-region] Communication section already current ${EM_DASH} nothing to do (zero-diff).`,
|
|
121
|
-
commsWritten: () => writtenLine('Communication section'),
|
|
122
|
-
capSkipNote: () => '[lens-region] note: no `maxLines` frontmatter on the target ' + EM_DASH + ' the line-cap guard is skipped.',
|
|
123
|
-
commsCapRefused: (target, count, cap) => capRefusedLine('Communication section', target, count, cap),
|
|
124
|
-
commsRefreshed: () => '[lens-region] refreshed the Communication section to the current canon.',
|
|
125
|
-
templateCanonStop: () => `[lens-region] STOP ${EM_DASH} the kit's bundled agent_rules.md template canon is unreadable; reinstall the kit: npx @sabaiway/agent-workflow-kit@latest init`,
|
|
126
|
-
storyNoRegion: (target, command) => [
|
|
127
|
-
`[lens-region] no "${STORY.label}" section in ${spanFree(target)} ${EM_DASH} left untouched.`,
|
|
128
|
-
...insertNote(command),
|
|
129
|
-
],
|
|
130
|
-
storyCurrent: () => `[lens-region] Story sessions section already current ${EM_DASH} nothing to do (zero-diff).`,
|
|
131
|
-
storyWritten: () => writtenLine('Story sessions section'),
|
|
132
|
-
storyCapRefused: (target, count, cap) => capRefusedLine('Story sessions section', target, count, cap, 'maxLines'),
|
|
133
|
-
storyRefreshed: () => '[lens-region] refreshed the Story sessions section to the current canon.',
|
|
134
|
-
regionHeadingTwice: (label, target) => [
|
|
135
|
-
`[lens-region] more than one "${oneLine(label)}" section in ${oneLine(target)} ${EM_DASH} none of them was changed.`,
|
|
136
|
-
"[lens-region] note: retitle every one of these headings but one so it no longer opens with the section's title words, then re-run.",
|
|
137
|
-
],
|
|
138
|
-
lensNoRegion: (target) => [
|
|
139
|
-
`[lens-region] no "${LENS.label}" section in ${oneLine(target)} ${EM_DASH} left untouched.`,
|
|
140
|
-
`[lens-region] note: the planning/review lens section is missing or renamed ${EM_DASH} it cannot be auto-refreshed; restore the canonical heading to re-enable refresh.`,
|
|
141
|
-
],
|
|
142
|
-
engineTooOld: () => '[lens-region] skipped ' + EM_DASH + ' the installed engine is too old (or incomplete) to supply the lens canon; refresh it with `npx @sabaiway/agent-workflow-engine@latest init`, then re-run.',
|
|
143
|
-
engineStop: (err) => {
|
|
144
|
-
const human = `[lens-region] STOP ${EM_DASH} ${oneLine(err?.stable ?? err?.message ?? String(err))}`;
|
|
145
|
-
return err?.reason ? [human, errorDetail(err.reason)] : [human];
|
|
146
|
-
},
|
|
147
|
-
lensCurrent: () => `[lens-region] lens section already current ${EM_DASH} nothing to do (zero-diff).`,
|
|
148
|
-
lensWritten: () => writtenLine('planning/review lens section'),
|
|
149
|
-
lensCapRefused: (target, count, cap) => capRefusedLine('planning/review lens section', target, count, cap),
|
|
150
|
-
lensRefreshed: () => '[lens-region] refreshed the planning/review lens section to the current canon.',
|
|
151
|
-
});
|
|
152
|
-
|
|
153
|
-
const readLensCanon = async (deps, log, logError) => {
|
|
154
|
-
const { homedir } = await import('node:os');
|
|
155
|
-
const { resolveEngineDir, detectEngine, readEngineFragment, LENS_FRAGMENT_REL, LENS_PRIORS_REL } = await import('./engine-source.mjs');
|
|
156
|
-
const { dir, source } = resolveEngineDir({ env: deps.env ?? process.env, home: deps.home ?? homedir() });
|
|
157
|
-
const lensPairPresent =
|
|
158
|
-
detectEngine(dir, { source, rel: LENS_FRAGMENT_REL }).ok && detectEngine(dir, { source, rel: LENS_PRIORS_REL }).ok;
|
|
159
|
-
if (!lensPairPresent) {
|
|
160
|
-
if (detectEngine(dir, { source }).ok) {
|
|
161
|
-
log(OUTCOME_LINES.engineTooOld());
|
|
162
|
-
return { code: EXIT_OK };
|
|
163
|
-
}
|
|
164
|
-
try {
|
|
165
|
-
readEngineFragment(dir, { source, rel: LENS_FRAGMENT_REL });
|
|
166
|
-
return { code: EXIT_STOP };
|
|
167
|
-
} catch (err) {
|
|
168
|
-
for (const line of OUTCOME_LINES.engineStop(err)) logError(line);
|
|
169
|
-
return { code: EXIT_STOP };
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
try {
|
|
173
|
-
const fragment = readEngineFragment(dir, { source, rel: LENS_FRAGMENT_REL, readFileSync: deps.engineRead });
|
|
174
|
-
const priors = parseLensPriors(readEngineFragment(dir, { source, rel: LENS_PRIORS_REL, readFileSync: deps.engineRead }));
|
|
175
|
-
return { fragment, priors };
|
|
176
|
-
} catch (err) {
|
|
177
|
-
for (const line of OUTCOME_LINES.engineStop(err)) logError(line);
|
|
178
|
-
return { code: EXIT_STOP };
|
|
179
|
-
}
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
export const runCli = async (argv, deps = {}) => {
|
|
183
|
-
const log = deps.log ?? console.log;
|
|
184
|
-
const logError = deps.logError ?? console.error;
|
|
185
|
-
if (argv[0] !== RECONCILE_COMMAND || !argv[1] || argv.length > CLI_ARG_COUNT) {
|
|
186
|
-
logError(USAGE);
|
|
187
|
-
return EXIT_USAGE;
|
|
188
|
-
}
|
|
189
|
-
const fs = deps.fs ?? (await import('node:fs/promises'));
|
|
190
|
-
const { dirname, basename, join, resolve, sep } = await import('node:path');
|
|
191
|
-
const { fileURLToPath } = await import('node:url');
|
|
192
|
-
const targetPath = resolve(argv[1]);
|
|
193
|
-
const served = targetPath.endsWith(sep + SERVED_TARGET.join(sep));
|
|
194
|
-
const command = served ? buildInsertPreview(resolve(targetPath, '..', '..', '..')) : '';
|
|
195
|
-
const stat = await fs.lstat(targetPath).catch((err) => {
|
|
196
|
-
if (err.code === 'ENOENT') return null;
|
|
197
|
-
throw err;
|
|
198
|
-
});
|
|
199
|
-
if (stat === null) {
|
|
200
|
-
log(OUTCOME_LINES.targetAbsent(argv[1]));
|
|
201
|
-
return EXIT_OK;
|
|
202
|
-
}
|
|
203
|
-
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
204
|
-
log(OUTCOME_LINES.targetNotRegular(argv[1]));
|
|
205
|
-
return EXIT_OK;
|
|
206
|
-
}
|
|
207
|
-
const bytes = await fs.readFile(targetPath);
|
|
208
|
-
const text = (() => {
|
|
209
|
-
try {
|
|
210
|
-
return decodeUtf8Strict(bytes);
|
|
211
|
-
} catch {
|
|
212
|
-
return null;
|
|
213
|
-
}
|
|
214
|
-
})();
|
|
215
|
-
if (text === null) {
|
|
216
|
-
log(OUTCOME_LINES.targetUndecodable(argv[1]));
|
|
217
|
-
return EXIT_OK;
|
|
218
|
-
}
|
|
219
|
-
const templatePath = join(dirname(fileURLToPath(import.meta.url)), '..', 'references', 'templates', 'agent_rules.md');
|
|
220
|
-
const template = await (async () => {
|
|
221
|
-
try {
|
|
222
|
-
const source = await fs.readFile(templatePath, UTF8);
|
|
223
|
-
const spans = RULES_REGIONS.filter((region) => region.canon === 'template')
|
|
224
|
-
.map((region) => [region.id, readTemplateSpan(source, region.headingRe)]);
|
|
225
|
-
return { spans: Object.fromEntries(spans), defect: spans.some(([, span]) => span.defect) };
|
|
226
|
-
} catch (err) {
|
|
227
|
-
return { defect: true, error: err?.message ?? String(err) };
|
|
228
|
-
}
|
|
229
|
-
})();
|
|
230
|
-
if (template.defect) {
|
|
231
|
-
logError(OUTCOME_LINES.templateCanonStop());
|
|
232
|
-
if (template.error) logError(OUTCOME_LINES.errorDetail(template.error));
|
|
233
|
-
return EXIT_STOP;
|
|
234
|
-
}
|
|
235
|
-
const atomicWrite = async (content) => {
|
|
236
|
-
const tmp = join(dirname(targetPath), `.${basename(targetPath)}.tmp-${process.pid}-${Date.now()}`);
|
|
237
|
-
try {
|
|
238
|
-
await fs.writeFile(tmp, content, UTF8);
|
|
239
|
-
await fs.rename(tmp, targetPath);
|
|
240
|
-
} catch (err) {
|
|
241
|
-
await fs.rm(tmp, { force: true }).catch(() => {});
|
|
242
|
-
throw err;
|
|
243
|
-
}
|
|
244
|
-
};
|
|
245
|
-
const outcome = await RULES_REGIONS.reduce(async (previous, descriptor) => {
|
|
246
|
-
const state = await previous;
|
|
247
|
-
if (state.code !== EXIT_OK) return state;
|
|
248
|
-
const region = extractRegionBy(state.text, descriptor.headingRe);
|
|
249
|
-
const prefix = OUTCOME_PREFIXES[descriptor.id];
|
|
250
|
-
if (region.count > SINGLE_HEADING) {
|
|
251
|
-
for (const line of OUTCOME_LINES.regionHeadingTwice(descriptor.label, argv[1])) log(line);
|
|
252
|
-
return state;
|
|
253
|
-
}
|
|
254
|
-
if (!region.found) {
|
|
255
|
-
for (const line of OUTCOME_LINES[`${prefix}NoRegion`](argv[1], command)) log(line);
|
|
256
|
-
return state;
|
|
257
|
-
}
|
|
258
|
-
const canon = descriptor.canon === 'template'
|
|
259
|
-
? { fragment: normalizeLensBody(template.spans[descriptor.id].span), priors: descriptor.priors }
|
|
260
|
-
: await readLensCanon(deps, log, logError);
|
|
261
|
-
if (canon.code !== undefined) return { text: state.text, code: canon.code };
|
|
262
|
-
const result = RECONCILERS[descriptor.id](state.text, canon.fragment, canon.priors);
|
|
263
|
-
if (result.status === 'current') {
|
|
264
|
-
log(OUTCOME_LINES[`${prefix}Current`]());
|
|
265
|
-
return state;
|
|
266
|
-
}
|
|
267
|
-
const cap = frontmatterMaxLines(state.text);
|
|
268
|
-
const decision = exceedsCap(result.text, cap);
|
|
269
|
-
if (decision.skipped) log(OUTCOME_LINES.capSkipNote());
|
|
270
|
-
if (decision.over) {
|
|
271
|
-
log(OUTCOME_LINES[`${prefix}CapRefused`](argv[1], decision.count, cap));
|
|
272
|
-
return state;
|
|
273
|
-
}
|
|
274
|
-
await atomicWrite(result.text);
|
|
275
|
-
log(OUTCOME_LINES[`${prefix}${result.status === 'custom' ? 'Written' : 'Refreshed'}`]());
|
|
276
|
-
return { text: result.text, code: EXIT_OK };
|
|
277
|
-
}, Promise.resolve({ text, code: EXIT_OK }));
|
|
278
|
-
return outcome.code;
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
if (isDirectRun(import.meta.url)) process.exitCode = await runCli(process.argv.slice(SCRIPT_ARG_OFFSET));
|
|
@@ -1,81 +0,0 @@
|
|
|
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
|
-
'| [`docs/ai/rules/effective/project-layout.md`](./docs/ai/rules/effective/project-layout.md) | Creating, moving or naming a file, a module or a spec | Only through `/agent-workflow-kit rules` |',
|
|
11
|
-
]);
|
|
12
|
-
|
|
13
|
-
// The route the reconcile's row note names when it wrote a row with other text.
|
|
14
|
-
export const ROW_ROUTE = 'a row of your own goes on a line of its own, its first cell a path of your own';
|
|
15
|
-
|
|
16
|
-
const ANCHOR_PATH = 'docs/ai/agent_rules.md';
|
|
17
|
-
const opening = (path) => `| [\`${path}\`](./${path}) |`;
|
|
18
|
-
const rowOf = (theme) => {
|
|
19
|
-
const { effective } = themePaths(theme.name);
|
|
20
|
-
return `${opening(effective)} ${theme.readWhen} | Only through \`/agent-workflow-kit rules\` |`;
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
// The lines of a text, each keeping its own ending, so joining them gives the text back byte for byte.
|
|
24
|
-
const splitLines = (text) => text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
25
|
-
const bodyOf = (line) => line.replace(/\r?\n$/, '');
|
|
26
|
-
const endingOf = (line) => line.slice(bodyOf(line).length);
|
|
27
|
-
// A table line that does not close its last cell goes on over the next line.
|
|
28
|
-
const isWhole = (line) => bodyOf(line).trimEnd().endsWith('|');
|
|
29
|
-
// One whole row: at least four | that no backslash escapes, the last of them closing the line.
|
|
30
|
-
const isOneRow = (line) => {
|
|
31
|
-
const body = bodyOf(line).trimEnd();
|
|
32
|
-
return (body.match(/(?<!\\)\|/g) ?? []).length >= 4 && /(?<!\\)\|$/.test(body);
|
|
33
|
-
};
|
|
34
|
-
|
|
35
|
-
// placeAfter(lines, i, row) → the lines with row on the line after i, taking line i's ending.
|
|
36
|
-
const placeAfter = (lines, i, row) => {
|
|
37
|
-
const ending = endingOf(lines[i]);
|
|
38
|
-
if (ending !== '') return lines.toSpliced(i + 1, 0, `${row}${ending}`);
|
|
39
|
-
return lines.toSpliced(i, 1, `${lines[i]}\n`, row);
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
// reconcileMemoryMapRows(text, { maxLines, priors }) → { text, outcomes }: one outcome
|
|
43
|
-
// { theme, status, note } per registry theme in registry order, status inserted, kept, refreshed,
|
|
44
|
-
// written or skipped; a skipped theme changes no byte and its note names the reason.
|
|
45
|
-
export const reconcileMemoryMapRows = (text, { maxLines, priors = MEMORY_MAP_PRIOR_ROWS } = {}) => {
|
|
46
|
-
let lines = splitLines(text);
|
|
47
|
-
let last = -1;
|
|
48
|
-
const outcomes = [];
|
|
49
|
-
for (const theme of THEMES) {
|
|
50
|
-
const row = rowOf(theme);
|
|
51
|
-
const path = themePaths(theme.name).effective;
|
|
52
|
-
const answer = (status, note = '') => outcomes.push({ theme: theme.name, status, note });
|
|
53
|
-
const found = lines.flatMap((line, i) => (line.startsWith(opening(path)) ? [i] : []));
|
|
54
|
-
if (found.length > 1) {
|
|
55
|
-
answer('skipped', `the Memory Map has more than one ${path} row — none of them was changed`);
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
if (found.length === 1) {
|
|
59
|
-
const at = found[0];
|
|
60
|
-
const body = bodyOf(lines[at]);
|
|
61
|
-
if (!isOneRow(lines[at])) answer('skipped', `the ${path} row does not close its cells on one line — left as it stands`);
|
|
62
|
-
else if (body === row) answer('kept');
|
|
63
|
-
else {
|
|
64
|
-
lines = lines.with(at, `${row}${endingOf(lines[at])}`);
|
|
65
|
-
answer(priors.includes(body) ? 'refreshed' : 'written');
|
|
66
|
-
}
|
|
67
|
-
continue;
|
|
68
|
-
}
|
|
69
|
-
const anchor = last !== -1 ? last : lines.findIndex((line) => line.startsWith(opening(ANCHOR_PATH)));
|
|
70
|
-
if (anchor === -1) answer('skipped', `the Memory Map has no ${ANCHOR_PATH} row to place it after`);
|
|
71
|
-
else if (!isWhole(lines[anchor])) answer('skipped', `the Memory Map's ${ANCHOR_PATH} row spans more than one line`);
|
|
72
|
-
else if (maxLines != null && lines.length + 1 > maxLines) {
|
|
73
|
-
answer('skipped', `adding it would take the file past its ${maxLines}-line limit`);
|
|
74
|
-
} else {
|
|
75
|
-
lines = placeAfter(lines, anchor, row);
|
|
76
|
-
last = anchor + 1;
|
|
77
|
-
answer('inserted');
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return { text: lines.join(''), outcomes };
|
|
81
|
-
};
|