@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
@@ -2,7 +2,6 @@
2
2
  import { lstatSync, readFileSync } from 'node:fs';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { AGENTS_MD_CAP } from './inject-methodology.mjs';
6
5
  import { writeContainedFileAtomic } from './atomic-write.mjs';
7
6
  import { isDirectRun } from './direct-run.mjs';
8
7
 
@@ -22,7 +21,6 @@ const CONTROL_BYTES = /[\x00-\x1f\x7f\u2028\u2029]/u;
22
21
  const makeResult = (code, stdout = '', stderr = '') => ({ code, stdout, stderr });
23
22
  const renderDetail = (detail) => String(detail).replace(/[\r\n\u2028\u2029]+/gu, ' ');
24
23
  const refuse = (name, detail) => makeResult(1, '', detail ? `${name}: ${renderDetail(detail)}` : name);
25
- const countLines = (text) => text.split(LF).length - Number(text.endsWith(LF));
26
24
  const findHeadings = (lines, heading) => lines.flatMap((line, index) => line.trimEnd() === heading ? [index] : []);
27
25
 
28
26
  const parseArgs = (argv) => {
@@ -121,10 +119,6 @@ const insertBlocks = (text, lines, blocks) => {
121
119
  const anchors = lines.flatMap((line, index) => line.replace(/\r$/u, '') === ANCHOR ? [index] : []);
122
120
  if (anchors.length === 0) return { error: refuse('anchor-absent', ANCHOR) };
123
121
  if (anchors.length !== 1) return { error: refuse('anchor-repeated', ANCHOR) };
124
- const total = countLines(text) + planned.reduce((count, block) => count + countLines(block.body), 0);
125
- if (total > AGENTS_MD_CAP) {
126
- return { error: refuse('cap', `${total} lines exceed ${AGENTS_MD_CAP}; trim AGENTS.md and re-run`) };
127
- }
128
122
  const anchor = anchors[0];
129
123
  const attribution = blocks.find((block) => block.name === 'attribution');
130
124
  const insertions = planned.map((block) => ({
@@ -85,7 +85,7 @@ export const refreshReadme = (config) => {
85
85
  return { config: withCurrentReadme(config), changed: true };
86
86
  };
87
87
 
88
- export const NOTE_ROUTE = 'a note of your own goes in AGENTS.md, outside the two <!-- workflow: --> comment lines around the orchestration pointer';
88
+ export const NOTE_ROUTE = "a note of your own goes in AGENTS.md, outside the kit block's two workflow:kit comment lines";
89
89
 
90
90
  export const readmeState = (config) => {
91
91
  if (!Object.hasOwn(config, '_README')) return 'absent';
@@ -1,4 +1,4 @@
1
- import { lstatSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';
1
+ import { lstatSync, readdirSync, readFileSync, rmdirSync, unlinkSync } from 'node:fs';
2
2
  import { resolve, sep } from 'node:path';
3
3
  import { assertContainedRealPath } from './fs-safe.mjs';
4
4
  import { lstatNoFollowRead } from './fs-read-nofollow.mjs';
@@ -107,9 +107,7 @@ const readTree = (root, entry, reports, directoryOnly = false) => {
107
107
  return entries;
108
108
  };
109
109
 
110
- // The walk lists a directory before its children, so a kept directory's line covers the directories beneath it.
111
- const planSubtree = (carried, installed, orphans, reports) => {
112
- const keptDirectories = [];
110
+ const planSubtree = (carried, installed, orphans, directories, reports) => {
113
111
  for (const [path, kind] of installed) {
114
112
  if (carried.has(path)) {
115
113
  const packageKind = carried.get(path);
@@ -121,10 +119,9 @@ const planSubtree = (carried, installed, orphans, reports) => {
121
119
  }
122
120
  } else if (kind === 'file') {
123
121
  orphans.push(path);
124
- } else if (kind === 'directory' && keptDirectories.some((kept) => path.startsWith(`${kept}/`))) {
125
- continue;
122
+ } else if (kind === 'directory') {
123
+ directories.push(path);
126
124
  } else {
127
- if (kind === 'directory') keptDirectories.push(path);
128
125
  reports.push({
129
126
  ok: true,
130
127
  line: `${PREFIX} kept ${path} (a ${kind} the package does not carry — yours to remove by hand)`,
@@ -151,9 +148,50 @@ const removeOrphan = (home, path, remove) => {
151
148
  }
152
149
  };
153
150
 
151
+ const removeEmptyDirectory = (home, path, remove) => {
152
+ const absolute = resolve(home, path);
153
+ try {
154
+ remove.assertContainedRealPath(home, absolute);
155
+ const stat = remove.lstatNoFollowRead(absolute);
156
+ if (stat === null) {
157
+ return { state: 'absent' };
158
+ }
159
+ if (!stat.isDirectory()) {
160
+ throw new Error('the path is no longer a real directory');
161
+ }
162
+ remove.rmdirSync(absolute);
163
+ return { state: 'removed' };
164
+ } catch (error) {
165
+ const settled = { ENOTEMPTY: 'kept', EEXIST: 'kept', ENOENT: 'absent' }[error.code];
166
+ return settled ? { state: settled } : { state: 'failed', report: reportFailure(path, error) };
167
+ }
168
+ };
169
+
170
+ // The walk lists a directory before its children: reversed, a child is removed before its parent.
171
+ const removeEmptyDirectories = (home, directories, remove) => {
172
+ const outcomes = new Map([...directories].reverse().map((path) => [path, removeEmptyDirectory(home, path, remove)]));
173
+ const isTop = (path) => !directories.some((other) => path.startsWith(`${other}/`));
174
+ return directories.flatMap((path) => {
175
+ const { state, report } = outcomes.get(path);
176
+ if (state === 'failed') {
177
+ return [report];
178
+ }
179
+ if (!isTop(path) || state === 'absent') {
180
+ return [];
181
+ }
182
+ return [{
183
+ ok: true,
184
+ line: state === 'removed'
185
+ ? `${PREFIX} removed ${path} (not in the package)`
186
+ : `${PREFIX} kept ${path} (a directory the package does not carry that still holds an entry)`,
187
+ }];
188
+ });
189
+ };
190
+
154
191
  export const prunePayload = ({ packageRoot, home, payload }, deps = {}) => {
155
192
  const reports = [];
156
193
  const orphans = [];
194
+ const directories = [];
157
195
  for (const entry of new Set(payload)) {
158
196
  const path = entry.split(sep).join('/');
159
197
  const carried = readTree(packageRoot, path, reports, true);
@@ -161,7 +199,7 @@ export const prunePayload = ({ packageRoot, home, payload }, deps = {}) => {
161
199
  continue;
162
200
  }
163
201
  const installed = readTree(home, path, reports);
164
- planSubtree(carried, installed, orphans, reports);
202
+ planSubtree(carried, installed, orphans, directories, reports);
165
203
  }
166
204
  if (reports.some((report) => !report.ok)) {
167
205
  return finishReport(reports);
@@ -170,9 +208,11 @@ export const prunePayload = ({ packageRoot, home, payload }, deps = {}) => {
170
208
  assertContainedRealPath: deps.assertContainedRealPath ?? assertContainedRealPath,
171
209
  lstatNoFollowRead: deps.lstatNoFollowRead ?? lstatNoFollowRead,
172
210
  unlinkSync: deps.unlinkSync ?? unlinkSync,
211
+ rmdirSync: deps.rmdirSync ?? rmdirSync,
173
212
  };
174
213
  for (const path of orphans) {
175
214
  reports.push(...removeOrphan(home, path, remove));
176
215
  }
216
+ reports.push(...removeEmptyDirectories(home, directories, remove));
177
217
  return finishReport(reports);
178
218
  };
@@ -1,19 +1,15 @@
1
1
  import { lstatSync, readFileSync } from 'node:fs';
2
2
  import { refuseDirectRun } from './direct-run.mjs';
3
- import { GAP_STATES, NO_COMMAND_SENTENCE, STORY_REGION_ABSENT, judgeProfileGaps } from './profile-gaps.mjs';
3
+ import { GAP_STATES, NO_COMMAND_SENTENCE, judgeProfileGaps } from './profile-gaps.mjs';
4
4
  import { readDeclines, readShippedProfile } from './reference-profile.mjs';
5
5
 
6
- const SESSION_RULES_ID = 'session-close-rules';
7
6
  const NOT_IN_PROFILE = 'not in the shipped profile';
8
7
 
9
8
  const refused = (reason) => ({ gaps: [], skips: [reason] });
10
9
 
11
10
  const disposeOf = ({ entry, state, reason }, root, hasById) => {
12
11
  if (state === GAP_STATES.present || state === GAP_STATES.declined) return {};
13
- if (state === GAP_STATES.undecidable) {
14
- if (entry.id === SESSION_RULES_ID && reason === STORY_REGION_ABSENT) return {};
15
- return { skip: `${entry.id}: ${reason}` };
16
- }
12
+ if (state === GAP_STATES.undecidable) return { skip: `${entry.id}: ${reason}` };
17
13
  const has = hasById.get(entry.id);
18
14
  if (has === undefined) return { skip: `${entry.id}: ${NOT_IN_PROFILE}` };
19
15
  const apply = entry.apply(root);
@@ -1,52 +1,35 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { CANDIDATE_STATES, isDeployed, judgeCheckerGates } from './checker-gates-read.mjs';
4
- import { normalizeLensBody, reconcileCommsText, reconcileStoryText } from './lens-region.mjs';
5
4
  import { CONFIG_REL, validateConfig } from './orchestration-config.mjs';
6
5
  import { TIER_TARGETS, isDeclineCurrent } from './reference-profile.mjs';
7
- import {
8
- RULES_REGIONS,
9
- extractRegionBy,
10
- readTemplateSpan,
11
- planInsert,
12
- frontmatterMaxLines,
13
- decodeUtf8Strict,
14
- buildInsertPreview,
15
- } from './rules-regions.mjs';
16
6
 
17
- const GAP_ID = 'story-sessions-section';
18
7
  const SLOTS_ID = 'epic-task-slots';
19
8
  const STORE_ID = 'epic-store-seeded';
20
9
  const STORE_PATH = 'docs/ai/epics';
21
10
  const CHECKER_GATES_ID = 'checker-gates-declared';
22
- const SESSION_RULES_ID = 'session-close-rules';
23
11
  const QUEUE_SEED_ID = 'named-queue-row-seed';
24
12
  const PLANS_PATH = 'docs/plans';
25
13
  const QUEUE_PATH = 'docs/plans/queue.md';
26
14
  const QUEUE_SEED_PATH = fileURLToPath(new URL('../references/authoring/QUEUE_TEMPLATE.md', import.meta.url));
27
15
  const ABSENT_ARM_CODES = new Set(['ENOENT', 'ENOTDIR']);
28
- const CURRENT_STATUS = 'current';
29
- const REFRESHED_STATUS = 'refreshed';
30
16
  const TIER_PREVIEW_PATH = fileURLToPath(new URL('./tier-preview.mjs', import.meta.url));
31
17
  const CHECKER_GATES_PATH = fileURLToPath(new URL('./checker-gates.mjs', import.meta.url));
32
18
  const UNDECIDED_STATES = [CANDIDATE_STATES.idTaken, CANDIDATE_STATES.probeUnreadable, CANDIDATE_STATES.withheld];
33
- const STORY_ID = 'story-sessions';
34
- const TEMPLATE_CANON = 'template';
35
- const ENCODING = 'utf8';
36
19
  const MISSING_FILE_CODE = 'ENOENT';
37
- const SINGLE_HEADING = 1;
38
- const TARGET_PATH = 'docs/ai/agent_rules.md';
39
- const TEMPLATE_PATH = fileURLToPath(new URL('../references/templates/agent_rules.md', import.meta.url));
20
+ const UTF8_LABEL = 'utf-8';
21
+ const UTF8_ENCODING = 'utf8';
22
+ const ROUND_TRIP_MESSAGE = 'the bytes read do not survive a UTF-8 round trip';
23
+ const COMMAND_UNSAFE_RE = /[\u0000-\u001f\u007f`]/;
24
+ const SHELL_PLAIN_RE = /^[A-Za-z0-9_./-]+$/;
25
+ const SINGLE_QUOTE = "'";
26
+ const QUOTE_ESCAPE = "'\\''";
40
27
  const VERDICTS = Object.freeze({
41
28
  present: 'present',
42
29
  absent: 'absent',
43
30
  undecidable: 'undecidable',
44
31
  });
45
32
  const REASONS = Object.freeze({
46
- template: 'template',
47
- fileAbsent: 'file-absent',
48
- fileSymlink: 'file-symlink',
49
- fileUnreadable: 'file-unreadable',
50
33
  noDeployment: 'no-deployment',
51
34
  configAbsent: 'config-absent',
52
35
  configSymlink: 'config-symlink',
@@ -56,9 +39,6 @@ const REASONS = Object.freeze({
56
39
  storeNotDirectory: 'store-not-directory',
57
40
  storeSymlink: 'store-symlink',
58
41
  storeUnreadable: 'store-unreadable',
59
- headingTwice: 'heading-twice',
60
- regionPrior: 'region-prior',
61
- regionCustomized: 'region-customized',
62
42
  plansSymlink: 'plans-symlink',
63
43
  plansNotDirectory: 'plans-not-directory',
64
44
  plansUnreadable: 'plans-unreadable',
@@ -67,59 +47,24 @@ const REASONS = Object.freeze({
67
47
  queueUnreadable: 'queue-unreadable',
68
48
  seedUnreadable: 'seed-unreadable',
69
49
  });
70
- export const STORY_REGION_ABSENT = 'story-sessions-absent';
71
- const REGION_ABSENT = Object.freeze({ communication: 'communication-absent', 'story-sessions': STORY_REGION_ABSENT });
72
- const JUDGEMENTS = Object.freeze({ communication: reconcileCommsText, 'story-sessions': reconcileStoryText });
73
- const TEMPLATE_REGIONS = RULES_REGIONS.filter(({ canon }) => canon === TEMPLATE_CANON);
74
- const STORY_REGION = RULES_REGIONS.find(({ id }) => id === STORY_ID);
75
50
 
76
51
  const reportUndecidable = (reason) => ({ verdict: VERDICTS.undecidable, reason });
77
52
 
78
- const readSpans = (deps) => {
79
- try {
80
- const template = deps.readFileSync(TEMPLATE_PATH, ENCODING);
81
- const entries = TEMPLATE_REGIONS.map(({ id, headingRe }) => [
82
- id, readTemplateSpan(template, headingRe),
83
- ]);
84
- const spans = Object.fromEntries(entries);
85
- if (Object.values(spans).some(({ defect }) => defect)) {
86
- return reportUndecidable(REASONS.template);
87
- }
88
- return { spans };
89
- } catch {
90
- return reportUndecidable(REASONS.template);
91
- }
53
+ // The bytes as text when they survive a strict UTF-8 round trip; a leading byte-order mark is kept.
54
+ export const decodeUtf8Strict = (bytes) => {
55
+ const text = new TextDecoder(UTF8_LABEL, { fatal: true, ignoreBOM: true }).decode(bytes);
56
+ if (!Buffer.from(text, UTF8_ENCODING).equals(bytes)) throw new Error(ROUND_TRIP_MESSAGE);
57
+ return text;
92
58
  };
93
59
 
94
- const readTarget = (root, deps) => {
95
- const target = resolve(root, TARGET_PATH);
96
- try {
97
- const stat = deps.lstatSync(target);
98
- if (stat.isSymbolicLink()) return reportUndecidable(REASONS.fileSymlink);
99
- if (!stat.isFile()) return reportUndecidable(REASONS.fileUnreadable);
100
- } catch (error) {
101
- const reason = error?.code === MISSING_FILE_CODE ? REASONS.fileAbsent : REASONS.fileUnreadable;
102
- return reportUndecidable(reason);
103
- }
104
- try {
105
- return { text: decodeUtf8Strict(deps.readFileSync(target)) };
106
- } catch {
107
- return reportUndecidable(REASONS.fileUnreadable);
108
- }
109
- };
60
+ const shellWord = (path) => (SHELL_PLAIN_RE.test(path)
61
+ ? path
62
+ : SINGLE_QUOTE + path.split(SINGLE_QUOTE).join(QUOTE_ESCAPE) + SINGLE_QUOTE);
110
63
 
111
- const detectStorySessions = ({ root, deps }) => {
112
- const template = readSpans(deps);
113
- if (template.verdict) return template;
114
- const target = readTarget(root, deps);
115
- if (target.verdict) return target;
116
- const { text } = target;
117
- if (extractRegionBy(text, STORY_REGION.headingRe).count === SINGLE_HEADING) {
118
- return { verdict: VERDICTS.present };
119
- }
120
- const result = planInsert({ text, spans: template.spans, cap: frontmatterMaxLines(text) });
121
- if (result.refusal) return reportUndecidable(result.refusal);
122
- return { verdict: VERDICTS.absent };
64
+ // The node line an entry's apply prints, or '' when the root or the tool path carries an unsafe byte.
65
+ export const buildInsertPreview = (root, toolPath) => {
66
+ if ([root, toolPath].some((path) => COMMAND_UNSAFE_RE.test(path))) return '';
67
+ return 'node ' + shellWord(toolPath) + ' --cwd ' + shellWord(root);
123
68
  };
124
69
 
125
70
  const parseConfig = (bytes) => {
@@ -184,30 +129,6 @@ const detectCheckerGates = ({ root, deps }) => {
184
129
  return undecided ? reportUndecidable(undecided.state) : { verdict: VERDICTS.present };
185
130
  };
186
131
 
187
- // A region is judged by the reconcile's own pure judgement, so this entry and the lens step agree.
188
- const judgeRegion = (text, spans, { id, headingRe, priors }) => {
189
- if (!extractRegionBy(text, headingRe).found) return REGION_ABSENT[id];
190
- const { status } = JUDGEMENTS[id](text, normalizeLensBody(spans[id].span), priors);
191
- if (status === CURRENT_STATUS) return null;
192
- return status === REFRESHED_STATUS ? REASONS.regionPrior : REASONS.regionCustomized;
193
- };
194
-
195
- const detectSessionRules = ({ root, deps }) => {
196
- const template = readSpans(deps);
197
- if (template.verdict) return template;
198
- const target = readTarget(root, deps);
199
- if (target.verdict) return target;
200
- const { text } = target;
201
- if (TEMPLATE_REGIONS.some(({ headingRe }) => extractRegionBy(text, headingRe).count > SINGLE_HEADING)) {
202
- return reportUndecidable(REASONS.headingTwice);
203
- }
204
- for (const region of TEMPLATE_REGIONS) {
205
- const reason = judgeRegion(text, template.spans, region);
206
- if (reason) return reportUndecidable(reason);
207
- }
208
- return { verdict: VERDICTS.present };
209
- };
210
-
211
132
  export const readQueueSeed = (deps) => {
212
133
  try {
213
134
  return { bytes: deps.readFileSync(QUEUE_SEED_PATH) };
@@ -244,11 +165,9 @@ const detectQueueSeed = ({ root, deps }) => {
244
165
  const tierPreview = (root) => buildInsertPreview(root, TIER_PREVIEW_PATH);
245
166
 
246
167
  export const PROFILE_GAPS = Object.freeze([
247
- Object.freeze({ id: GAP_ID, detect: detectStorySessions, apply: (root) => buildInsertPreview(root) }),
248
168
  Object.freeze({ id: SLOTS_ID, detect: detectSlots, apply: tierPreview }),
249
169
  Object.freeze({ id: STORE_ID, detect: detectStore, apply: tierPreview }),
250
170
  Object.freeze({ id: CHECKER_GATES_ID, detect: detectCheckerGates, apply: (root) => buildInsertPreview(root, CHECKER_GATES_PATH) }),
251
- Object.freeze({ id: SESSION_RULES_ID, detect: detectSessionRules, apply: (root) => buildInsertPreview(root) }),
252
171
  Object.freeze({ id: QUEUE_SEED_ID, detect: detectQueueSeed, apply: tierPreview }),
253
172
  ]);
254
173
 
@@ -1,5 +1,4 @@
1
1
  // The one door of the project-rules module. Contract: docs/ai/specs/kit/project-rules/index.md.
2
- export { THEMES } from './themes.mjs';
2
+ export { THEMES, themePaths, PRECEDENCE_LINE } from './themes.mjs';
3
3
  export { checkRules } from './rules-check.mjs';
4
4
  export { ensureRules } from './rules-ensure.mjs';
5
- export { reconcileMemoryMapRows, ROW_ROUTE } from './memory-map-row.mjs';
@@ -3,8 +3,10 @@
3
3
  // writes a local file and never merges two texts. Contract: docs/ai/specs/kit/project-rules/rules-ensure.md.
4
4
 
5
5
  import { readFileSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
6
7
  import { join } from 'node:path';
7
8
  import { writeDocsAiFileAtomic, writeProjectFileCreateOnly } from '../atomic-write.mjs';
9
+ import { detectEngine, readEngineFragment, resolveEngineDir } from '../engine-source.mjs';
8
10
  import { composeFailure, composeOutcome, tmpNote } from '../ensure-ops.mjs';
9
11
  import { shellQuoteArg } from '../repo-lex.mjs';
10
12
  import { digestOf, readRecord, readUnder } from './rules-check.mjs';
@@ -13,6 +15,7 @@ import { RULES_PRIORS, isKnownPrior } from './rules-priors.mjs';
13
15
  import { RECORD_PATH, THEMES, themePaths } from './themes.mjs';
14
16
 
15
17
  const OP = 'rules';
18
+ const ENGINE_INSTALL = 'npx @sabaiway/agent-workflow-engine@latest init';
16
19
  const FILE_ROLES = ['kit', 'local', 'effective'];
17
20
  const causeOf = (err) => String((err && err.message) || err);
18
21
 
@@ -26,6 +29,23 @@ const readTemplate = (readFile, path) => {
26
29
  }
27
30
  };
28
31
 
32
+ // An engine-homed template: absent when no valid installed engine supplies it, else its bytes, else the
33
+ // read's error (a present template that cannot be read or is blank after trim).
34
+ const readEngineTemplate = (rel, deps) => {
35
+ const { dir, source } = resolveEngineDir({ env: deps.env ?? process.env, home: deps.home ?? homedir() });
36
+ if (!detectEngine(dir, { source, rel }).ok) return { absent: true };
37
+ try {
38
+ return { bytes: Buffer.from(readEngineFragment(dir, { source, rel })) };
39
+ } catch (err) {
40
+ return { error: causeOf(err) };
41
+ }
42
+ };
43
+
44
+ const unsupplied = (theme, paths, kit) => {
45
+ const fate = kit.outcome === 'absent' ? 'not laid' : 'left as it is';
46
+ return `${paths.kit}: ${fate} — no installed engine supplies the ${theme.name} rules theme; install or refresh it with ${ENGINE_INSTALL}`;
47
+ };
48
+
29
49
  const unreadable = (rel, read) => {
30
50
  if (read.outcome === 'foreign') {
31
51
  return composeFailure(OP, 'wrong-node-kind', `${rel}: ${read.code ?? `it is a ${read.className}, not a regular file`} — nothing was read or written; resolve it by hand, then re-run`);
@@ -38,9 +58,16 @@ const survey = ({ themes, cwd, kitRoot, readFile, deps }) => {
38
58
  const surveyed = [];
39
59
  for (const theme of themes) {
40
60
  const paths = themePaths(theme.name);
41
- const template = readTemplate(readFile, join(kitRoot, theme.template));
61
+ const fromEngine = theme.home === 'engine';
62
+ const template = fromEngine ? readEngineTemplate(theme.template, deps) : readTemplate(readFile, join(kitRoot, theme.template));
42
63
  if (template.error !== undefined) {
43
- return { failure: composeFailure(OP, 'template-unreadable', `${paths.kit}: the bundled template ${theme.template} could not be read, so nothing was written — reinstall the kit. ${template.error}`) };
64
+ const remedy = fromEngine ? `the installed engine's template ${theme.template} could not be read, so nothing was written — ${template.error}`
65
+ : `the bundled template ${theme.template} could not be read, so nothing was written — reinstall the kit. ${template.error}`;
66
+ return { failure: composeFailure(OP, 'template-unreadable', `${paths.kit}: ${remedy}`) };
67
+ }
68
+ if (template.absent) {
69
+ surveyed.push({ theme, unsupplied: unsupplied(theme, paths, readUnder(cwd, paths.kit, deps)) });
70
+ continue;
44
71
  }
45
72
  const reads = Object.fromEntries(FILE_ROLES.map((role) => [role, readUnder(cwd, paths[role], deps)]));
46
73
  const failure = FILE_ROLES.map((role) => unreadable(paths[role], reads[role])).find(Boolean);
@@ -195,13 +222,17 @@ export const ensureRules = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
195
222
  const themes = deps.themes ?? THEMES;
196
223
  const surveyed = survey({ themes, cwd, kitRoot, readFile: deps.readFile ?? readFileSync, deps });
197
224
  if (surveyed.failure) return surveyed.failure;
198
- const plans = surveyed.surveyed.map((one) => planTheme(one, surveyed.record, deps.priors ?? RULES_PRIORS));
199
- const firstRecordWrite = plans.findIndex((plan) => plan.recordWrite);
200
- const replacing = (index) => (index === firstRecordWrite && !surveyed.record.ok ? surveyed.record.reason : null);
225
+ const priors = deps.priors ?? RULES_PRIORS;
226
+ const steps = surveyed.surveyed.map((one) => (one.unsupplied ? one : { plan: planTheme(one, surveyed.record, priors) }));
227
+ const plans = steps.filter((step) => step.plan).map((step) => step.plan);
228
+ const firstRecordWrite = plans.find((plan) => plan.recordWrite);
229
+ const replacing = (plan) => (plan === firstRecordWrite && !surveyed.record.ok ? surveyed.record.reason : null);
201
230
  const fates = new Map();
202
231
  const notes = [];
203
232
  const fateOf = (plan, role) => fates.get(`${plan.name}:${role}`) ?? 'would';
204
- const lines = () => plans.flatMap((plan, index) => themeLines({ plan, fateOf, kitRoot, cwd, dryRun, replacing: replacing(index) }));
233
+ const lines = () => steps.flatMap(({ plan, unsupplied: line }) => (plan
234
+ ? themeLines({ plan, fateOf, kitRoot, cwd, dryRun, replacing: replacing(plan) })
235
+ : [line]));
205
236
  if (dryRun) {
206
237
  const wouldWrite = (plan, role) => (role === 'kit' ? plan.kitWrite !== null : role === 'effective' ? plan.effectiveWrite !== null : plan.recordWrite);
207
238
  return composeOutcome(OP, tokenOf(plans, wouldWrite, true), lines(), false);
@@ -5,6 +5,7 @@ import { digestOf } from './rules-check.mjs';
5
5
 
6
6
  export const RULES_PRIORS = Object.freeze([
7
7
  Object.freeze({ theme: 'project-layout', release: '14.37.0', sha256: 'b79f19a9e0583f1e0619ee6aca06feb2c359b9655f1d260e87d8d5647bd1de19' }),
8
+ Object.freeze({ theme: 'project-layout', release: '19.4.0', sha256: 'ec4ef10c05ba365e73df96d175042314ea120f3fe1c946fdd94d3d1237de8be9' }),
8
9
  ]);
9
10
 
10
11
  // isKnownPrior(theme, bytes, catalog?) → true exactly when the bytes hash to an entry of that theme.
@@ -1,14 +1,22 @@
1
1
  // The theme registry: pure data and pure derivation. Every surface that names a theme or its files
2
2
  // reads this list, never a second copy. Contract: docs/ai/specs/kit/project-rules/themes.md.
3
3
 
4
+ const START = '**Start of every session**';
5
+ const BEFORE = '**Before any code change**';
6
+
7
+ const theme = (name, home, readWhen) => Object.freeze({ name, home, template: `references/rules/${name}.md`, readWhen });
8
+
9
+ // home: 'kit' → the template is the kit's own file; 'engine' → it is the installed engine's.
4
10
  export const THEMES = Object.freeze([
5
- Object.freeze({
6
- name: 'project-layout',
7
- template: 'references/rules/project-layout.md',
8
- readWhen: '**Start of every session**',
9
- }),
11
+ theme('project-layout', 'kit', START),
12
+ theme('communication', 'kit', BEFORE),
13
+ theme('story-sessions', 'kit', BEFORE),
14
+ theme('lens', 'engine', BEFORE),
10
15
  ]);
11
16
 
17
+ // The line that opens every theme template's body and the kit block's body; a suite pins every copy.
18
+ export const PRECEDENCE_LINE = "The kit block of AGENTS.md is the kit's and is rewritten on every upgrade; it and docs/ai/rules/effective/ govern over any copy of kit text elsewhere in this project's files; text of your own goes outside the block, and a change to a kit rule goes in its theme's file under docs/ai/rules/local/.";
19
+
12
20
  export const RECORD_PATH = 'docs/ai/rules/effective/sources.json';
13
21
 
14
22
  export const themePaths = (name) => Object.freeze({