@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.
Files changed (50) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +17 -9
  3. package/SKILL.md +6 -6
  4. package/capability.json +1 -1
  5. package/migrations/1.1.0-communication-language.md +2 -4
  6. package/migrations/1.2.0-agent-attribution.md +1 -3
  7. package/migrations/5.0.0-kit-text-in-kit-files.md +30 -0
  8. package/migrations/README.md +2 -2
  9. package/package.json +1 -1
  10. package/references/advisor-writers.md +1 -1
  11. package/references/contracts.md +9 -11
  12. package/references/modes/bootstrap.md +2 -4
  13. package/references/modes/hook.md +1 -1
  14. package/references/modes/procedures.md +1 -1
  15. package/references/modes/recommendations.md +1 -1
  16. package/references/modes/rules.md +4 -3
  17. package/references/modes/upgrade.md +23 -49
  18. package/references/modes/velocity.md +1 -1
  19. package/references/reference-profile.json +0 -6
  20. package/references/rules/communication.md +22 -0
  21. package/references/rules/project-layout.md +2 -0
  22. package/references/rules/story-sessions.md +14 -0
  23. package/references/scripts/spec-schema.mjs +1 -3
  24. package/references/scripts/spec-schema.test.mjs +6 -6
  25. package/references/shared/composition-handoff.md +24 -59
  26. package/references/shared/deploy-tail.md +2 -2
  27. package/references/templates/AGENTS.md +0 -10
  28. package/references/templates/agent_rules.md +0 -33
  29. package/references/templates/specs/index.md +1 -1
  30. package/tools/cheap-agents-read.mjs +1 -1
  31. package/tools/delegation.mjs +5 -8
  32. package/tools/engine-source.mjs +13 -11
  33. package/tools/family-registry.mjs +4 -5
  34. package/tools/inject-methodology.mjs +153 -493
  35. package/tools/migration-blocks.mjs +0 -6
  36. package/tools/orchestration-readme.mjs +1 -1
  37. package/tools/profile-gap-screen.mjs +2 -6
  38. package/tools/profile-gaps.mjs +19 -100
  39. package/tools/project-rules/index.mjs +1 -2
  40. package/tools/project-rules/rules-ensure.mjs +37 -6
  41. package/tools/project-rules/rules-priors.mjs +1 -0
  42. package/tools/project-rules/themes.mjs +13 -5
  43. package/tools/script-priors.mjs +2 -0
  44. package/tools/transition/index.mjs +214 -0
  45. package/tools/upgrade-runlist.mjs +2 -17
  46. package/tools/velocity-profile.mjs +1 -1
  47. package/tools/lens-region.mjs +0 -281
  48. package/tools/project-rules/memory-map-row.mjs +0 -81
  49. package/tools/rules-insert.mjs +0 -203
  50. 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,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({
@@ -60,6 +60,8 @@ export const SCRIPT_PRIORS = Object.freeze([
60
60
  prior('install-git-hooks.test.mjs', '8.3.0', '8.3.0', '058ac6de4dd5f83c4f09c8afd72ef2bfda365a9aea55bddd0089ce89a4e941e2'),
61
61
  prior('install-git-hooks-repo-exec.test.mjs', '8.3.0', '8.3.0', 'd5a3253fa0cd088733b927f2a7187c6484298f11dec48f6f63953e380b071c9a'),
62
62
  prior('archive-decisions.mjs', '8.1.3', '8.4.0', '2e1c378fe8a395440dc17a712643a549487e87f958f9d6ec5922dced876421ad'),
63
+ prior('spec-schema.mjs', '8.0.0', '8.6.3', '238e9a0ab3839f56b9f488b8c3232e8289c90d9808c772864dd5a95405b8488c'),
64
+ prior('spec-schema.test.mjs', '8.0.0', '8.6.3', '192661dd459c130004b2639d506676ee023fb24e862aad09656adc8c1418af04'),
63
65
  ]);
64
66
 
65
67
  export const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -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
- 'pointers',
23
+ 'entry-block',
24
24
  'node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md',
25
25
  null,
26
- ['added', 'already present', 'written over a different one', 'skipped', 'STOP'],
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 = '4.0.0';
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';