@sabaiway/agent-workflow-kit 19.4.0 → 20.0.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 +64 -0
- package/README.md +17 -9
- package/SKILL.md +6 -6
- 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/scripts/spec-schema.mjs +1 -3
- package/references/scripts/spec-schema.test.mjs +6 -6
- 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/references/templates/specs/index.md +1 -1
- 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/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/script-priors.mjs +2 -0
- 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
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
|
-
};
|
package/tools/rules-insert.mjs
DELETED
|
@@ -1,203 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { lstatSync, readFileSync } from 'node:fs';
|
|
3
|
-
import { dirname, resolve } from 'node:path';
|
|
4
|
-
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { writeContainedFileAtomic } from './atomic-write.mjs';
|
|
6
|
-
import { isDirectRun } from './direct-run.mjs';
|
|
7
|
-
import { OUTCOME_LINES as LENS_OUTCOME_LINES } from './lens-region.mjs';
|
|
8
|
-
import {
|
|
9
|
-
RULES_REGIONS, readTemplateSpan, planInsert, frontmatterMaxLines, decodeUtf8Strict,
|
|
10
|
-
} from './rules-regions.mjs';
|
|
11
|
-
|
|
12
|
-
const LF = String.fromCharCode(10);
|
|
13
|
-
const BACKSLASH = String.fromCharCode(92);
|
|
14
|
-
const BACKTICK = String.fromCharCode(96);
|
|
15
|
-
const JSON_RADIX = 16;
|
|
16
|
-
const JSON_ESCAPE_WIDTH = 4;
|
|
17
|
-
const JSON_ESCAPE_PAD = '0';
|
|
18
|
-
const FIRST_CODE_POINT = 0;
|
|
19
|
-
const ARGV_OFFSET = 2;
|
|
20
|
-
const UTF8 = 'utf8';
|
|
21
|
-
const ABSENT_CODE = 'ENOENT';
|
|
22
|
-
const EXIT_SUCCESS = 0;
|
|
23
|
-
const EXIT_REFUSAL = 1;
|
|
24
|
-
const EXIT_USAGE = 2;
|
|
25
|
-
const FLAG_PREFIX = '--';
|
|
26
|
-
const CWD_FLAG = '--cwd';
|
|
27
|
-
const APPLY_FLAG = '--apply';
|
|
28
|
-
const FLAGS = Object.freeze({ [CWD_FLAG]: 'cwd', [APPLY_FLAG]: 'apply' });
|
|
29
|
-
const TEMPLATE_CANON = 'template';
|
|
30
|
-
const REGIONS = RULES_REGIONS.filter(({ canon }) => canon === TEMPLATE_CANON);
|
|
31
|
-
const TARGET_RELATIVE = 'docs/ai/agent_rules.md';
|
|
32
|
-
const TEMPLATE_PATH = resolve(
|
|
33
|
-
dirname(fileURLToPath(import.meta.url)), '..', 'references', 'templates', 'agent_rules.md',
|
|
34
|
-
);
|
|
35
|
-
const REINSTALL = 'npx @sabaiway/agent-workflow-kit@latest init';
|
|
36
|
-
const USAGE = 'usage: rules-insert.mjs --cwd <project> [--apply]';
|
|
37
|
-
const NON_REGULAR_CAUSE = 'Target is not a regular file';
|
|
38
|
-
const REFUSALS = Object.freeze({
|
|
39
|
-
fileAbsent: 'file-absent',
|
|
40
|
-
fileSymlink: 'file-symlink',
|
|
41
|
-
fileUnreadable: 'file-unreadable',
|
|
42
|
-
templateDefect: 'template',
|
|
43
|
-
headingTwice: 'heading-twice',
|
|
44
|
-
anchorAbsent: 'anchor-absent',
|
|
45
|
-
capRefused: 'cap',
|
|
46
|
-
writeFailed: 'write-failed',
|
|
47
|
-
});
|
|
48
|
-
const COMPOSERS = Object.fromEntries(Object.entries(REFUSALS).map(([key, name]) => [name, key]));
|
|
49
|
-
const DIAGNOSTIC_REFUSALS = new Set([
|
|
50
|
-
REFUSALS.templateDefect, REFUSALS.fileUnreadable, REFUSALS.writeFailed,
|
|
51
|
-
]);
|
|
52
|
-
const UNICODE_UNSAFE_RANGE = BACKSLASH + 'u007f-' + BACKSLASH + 'u009f'
|
|
53
|
-
+ BACKSLASH + 'u2028' + BACKSLASH + 'u2029';
|
|
54
|
-
const LINE_UNSAFE = new RegExp('[' + UNICODE_UNSAFE_RANGE + ']', 'g');
|
|
55
|
-
const HUMAN_UNSAFE = new RegExp(
|
|
56
|
-
'[' + BACKSLASH + 'u0000-' + BACKSLASH + 'u001f' + UNICODE_UNSAFE_RANGE + ']+', 'g',
|
|
57
|
-
);
|
|
58
|
-
|
|
59
|
-
const escapeUnsafe = (character) => BACKSLASH + 'u'
|
|
60
|
-
+ character.codePointAt(FIRST_CODE_POINT).toString(JSON_RADIX).padStart(JSON_ESCAPE_WIDTH, JSON_ESCAPE_PAD);
|
|
61
|
-
const renderOneLine = (value) => String(value).replace(HUMAN_UNSAFE, ' ');
|
|
62
|
-
const readCause = (error) => String(error?.message ?? error);
|
|
63
|
-
const makeResult = (code, stdout = '', stderr = '') => ({ code, stdout, stderr });
|
|
64
|
-
|
|
65
|
-
export const OUTCOME_LINES = Object.freeze({
|
|
66
|
-
regionPresent: (id) => `${renderOneLine(id)}: present`,
|
|
67
|
-
regionPlanned: (id) => `${renderOneLine(id)}: planned`,
|
|
68
|
-
regionInserted: (id) => `${renderOneLine(id)}: inserted`,
|
|
69
|
-
fileAbsent: (target) => `${renderOneLine(target)} is absent; the file is seeded at bootstrap.`,
|
|
70
|
-
fileSymlink: (target) => `${renderOneLine(target)} is a symbolic link; no changes were made.`,
|
|
71
|
-
fileUnreadable: (target) => `${renderOneLine(target)} cannot be read as a regular file; no changes were made.`,
|
|
72
|
-
templateDefect: () => 'The bundled rules cannot be used; reinstall the kit with '
|
|
73
|
-
+ BACKTICK + REINSTALL + BACKTICK + '.',
|
|
74
|
-
headingTwice: (label, target) => `The heading "${renderOneLine(label)}" occurs more than once in ${renderOneLine(target)}; no changes were made.`,
|
|
75
|
-
anchorAbsent: (target) => `${renderOneLine(target)} has no numbered section in part 2 to insert after; no changes were made.`,
|
|
76
|
-
capRefused: (target, count, cap) => `${renderOneLine(target)} would contain ${renderOneLine(count)} lines, exceeding its limit of ${renderOneLine(cap)}; trim the file and try again.`,
|
|
77
|
-
writeFailed: (target) => `${renderOneLine(target)} could not be replaced; its contents were not changed.`,
|
|
78
|
-
refusalLine: (name) => `[rules-insert] refusal=${renderOneLine(name)}`,
|
|
79
|
-
errorDetail: (raw) => `[rules-insert] error=${JSON.stringify(String(raw)).replace(LINE_UNSAFE, escapeUnsafe)}`,
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
const refuse = (name, args = [], cause) => {
|
|
83
|
-
const lines = [OUTCOME_LINES[COMPOSERS[name]](...args), OUTCOME_LINES.refusalLine(name)];
|
|
84
|
-
if (DIAGNOSTIC_REFUSALS.has(name)) lines.push(OUTCOME_LINES.errorDetail(cause));
|
|
85
|
-
return makeResult(EXIT_REFUSAL, '', lines.join(LF));
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
const parseArgs = (argv) => {
|
|
89
|
-
const parsed = argv.reduce((state, argument) => {
|
|
90
|
-
if (state.pending) {
|
|
91
|
-
if (!argument || argument.startsWith(FLAG_PREFIX)) {
|
|
92
|
-
throw new Error(`${state.pending} needs a value`);
|
|
93
|
-
}
|
|
94
|
-
return { options: { ...state.options, [FLAGS[state.pending]]: argument }, pending: null };
|
|
95
|
-
}
|
|
96
|
-
if (!Object.hasOwn(FLAGS, argument)) throw new Error(`unknown argument ${argument}`);
|
|
97
|
-
const key = FLAGS[argument];
|
|
98
|
-
if (Object.hasOwn(state.options, key)) throw new Error(`${argument} repeated`);
|
|
99
|
-
if (argument === APPLY_FLAG) return { options: { ...state.options, apply: true }, pending: null };
|
|
100
|
-
return { options: state.options, pending: argument };
|
|
101
|
-
}, { options: {}, pending: null });
|
|
102
|
-
if (parsed.pending) throw new Error(`${parsed.pending} needs a value`);
|
|
103
|
-
if (!parsed.options.cwd) throw new Error(`${CWD_FLAG} is required`);
|
|
104
|
-
return parsed.options;
|
|
105
|
-
};
|
|
106
|
-
|
|
107
|
-
const readTemplate = (deps) => {
|
|
108
|
-
try {
|
|
109
|
-
const read = deps.readFileSync ?? readFileSync;
|
|
110
|
-
const text = read(deps.templatePath ?? TEMPLATE_PATH, UTF8);
|
|
111
|
-
const spans = Object.fromEntries(REGIONS.map(({ id, headingRe }) => [
|
|
112
|
-
id, readTemplateSpan(text, headingRe),
|
|
113
|
-
]));
|
|
114
|
-
const defective = REGIONS.find(({ id }) => spans[id].defect);
|
|
115
|
-
if (defective) {
|
|
116
|
-
return { error: refuse(REFUSALS.templateDefect, [], `${defective.id}: ${spans[defective.id].defect}`) };
|
|
117
|
-
}
|
|
118
|
-
return { spans };
|
|
119
|
-
} catch (error) {
|
|
120
|
-
return { error: refuse(REFUSALS.templateDefect, [], readCause(error)) };
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
const readDocument = (target, deps) => {
|
|
125
|
-
const probe = deps.lstatSync ?? lstatSync;
|
|
126
|
-
const read = deps.readFileSync ?? readFileSync;
|
|
127
|
-
const status = (() => {
|
|
128
|
-
try {
|
|
129
|
-
return { stat: probe(target) };
|
|
130
|
-
} catch (error) {
|
|
131
|
-
const name = error?.code === ABSENT_CODE ? REFUSALS.fileAbsent : REFUSALS.fileUnreadable;
|
|
132
|
-
return { error: refuse(name, [target], readCause(error)) };
|
|
133
|
-
}
|
|
134
|
-
})();
|
|
135
|
-
if (status.error) return status;
|
|
136
|
-
if (status.stat.isSymbolicLink()) return { error: refuse(REFUSALS.fileSymlink, [target]) };
|
|
137
|
-
if (!status.stat.isFile()) {
|
|
138
|
-
return { error: refuse(REFUSALS.fileUnreadable, [target], NON_REGULAR_CAUSE) };
|
|
139
|
-
}
|
|
140
|
-
try {
|
|
141
|
-
return { text: decodeUtf8Strict(read(target)) };
|
|
142
|
-
} catch (error) {
|
|
143
|
-
return { error: refuse(REFUSALS.fileUnreadable, [target], readCause(error)) };
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
const refusePlan = (plan, target) => {
|
|
148
|
-
if (plan.refusal === REFUSALS.headingTwice) {
|
|
149
|
-
const region = REGIONS.find(({ id }) => id === plan.region);
|
|
150
|
-
return refuse(plan.refusal, [region.label, target]);
|
|
151
|
-
}
|
|
152
|
-
if (plan.refusal === REFUSALS.capRefused) return refuse(plan.refusal, [target, plan.count, plan.cap]);
|
|
153
|
-
return refuse(plan.refusal, [target]);
|
|
154
|
-
};
|
|
155
|
-
|
|
156
|
-
const runInsert = (options, deps) => {
|
|
157
|
-
const template = readTemplate(deps);
|
|
158
|
-
if (template.error) return template.error;
|
|
159
|
-
const root = resolve(options.cwd);
|
|
160
|
-
const target = resolve(root, TARGET_RELATIVE);
|
|
161
|
-
const document = readDocument(target, deps);
|
|
162
|
-
if (document.error) return document.error;
|
|
163
|
-
const cap = frontmatterMaxLines(document.text);
|
|
164
|
-
const plan = planInsert({ text: document.text, spans: template.spans, cap });
|
|
165
|
-
if (plan.refusal) return refusePlan(plan, target);
|
|
166
|
-
const planned = new Set(plan.planned.map(({ id }) => id));
|
|
167
|
-
const hasPlanned = Boolean(planned.size);
|
|
168
|
-
if (options.apply && hasPlanned) {
|
|
169
|
-
try {
|
|
170
|
-
writeContainedFileAtomic(root, target, plan.text, {
|
|
171
|
-
writeFile: deps.writeFile,
|
|
172
|
-
rename: deps.rename,
|
|
173
|
-
rm: deps.rm,
|
|
174
|
-
});
|
|
175
|
-
} catch (error) {
|
|
176
|
-
return refuse(REFUSALS.writeFailed, [target], readCause(error));
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
const composePlanned = options.apply ? OUTCOME_LINES.regionInserted : OUTCOME_LINES.regionPlanned;
|
|
180
|
-
const stdout = REGIONS.map(({ id }) => (
|
|
181
|
-
planned.has(id) ? composePlanned(id) : OUTCOME_LINES.regionPresent(id)
|
|
182
|
-
)).join(LF);
|
|
183
|
-
const stderr = hasPlanned && cap === null ? LENS_OUTCOME_LINES.capSkipNote() : '';
|
|
184
|
-
return makeResult(EXIT_SUCCESS, stdout, stderr);
|
|
185
|
-
};
|
|
186
|
-
|
|
187
|
-
export const main = (argv, deps = {}) => {
|
|
188
|
-
const parsed = (() => {
|
|
189
|
-
try {
|
|
190
|
-
return { options: parseArgs(argv) };
|
|
191
|
-
} catch (error) {
|
|
192
|
-
return { error: makeResult(EXIT_USAGE, '', OUTCOME_LINES.errorDetail(`${USAGE}; ${readCause(error)}`)) };
|
|
193
|
-
}
|
|
194
|
-
})();
|
|
195
|
-
return parsed.error ?? runInsert(parsed.options, deps);
|
|
196
|
-
};
|
|
197
|
-
|
|
198
|
-
if (isDirectRun(import.meta.url)) {
|
|
199
|
-
const result = await main(process.argv.slice(ARGV_OFFSET));
|
|
200
|
-
if (result.stdout) console.log(result.stdout);
|
|
201
|
-
if (result.stderr) console.error(result.stderr);
|
|
202
|
-
process.exitCode = result.code;
|
|
203
|
-
}
|