@sabaiway/agent-workflow-kit 23.11.0 → 24.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 (159) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +4 -4
  3. package/SKILL.md +1 -1
  4. package/bridges/codex-cli-bridge/SKILL.md +7 -2
  5. package/bridges/codex-cli-bridge/bin/codex-exec-jev.test.mjs +11 -6
  6. package/bridges/codex-cli-bridge/bin/codex-exec.sh +72 -33
  7. package/bridges/codex-cli-bridge/bin/codex-exec.test.mjs +111 -3
  8. package/bridges/codex-cli-bridge/bin/codex-fixtures-harness.test.mjs +16 -1
  9. package/bridges/codex-cli-bridge/bin/codex-model-posture.test.mjs +5 -3
  10. package/bridges/codex-cli-bridge/bin/codex-review.sh +1 -1
  11. package/bridges/codex-cli-bridge/capability.json +2 -2
  12. package/capability.json +1 -1
  13. package/package.json +1 -1
  14. package/references/advisor-writers.md +2 -0
  15. package/references/agents/author.md +21 -0
  16. package/references/agents/executor.md +12 -6
  17. package/references/contracts.md +4 -4
  18. package/references/hooks/gate-approve.mjs +7 -8
  19. package/references/hooks/stage-write-guard.mjs +314 -0
  20. package/references/modes/agents.md +6 -4
  21. package/references/modes/bootstrap.md +1 -1
  22. package/references/modes/control-bytes.md +38 -32
  23. package/references/modes/flow-writer.md +10 -2
  24. package/references/modes/hook.md +4 -1
  25. package/references/modes/now.md +1 -1
  26. package/references/modes/procedures.md +49 -10
  27. package/references/modes/recipes.md +7 -7
  28. package/references/modes/recommendations.md +5 -4
  29. package/references/modes/robustness-brief.md +9 -8
  30. package/references/modes/set-recipe.md +1 -1
  31. package/references/modes/state-block-guard.md +4 -3
  32. package/references/modes/status.md +1 -1
  33. package/references/modes/upgrade.md +1 -1
  34. package/references/modes/worktrees.md +28 -5
  35. package/references/rules/story-sessions.md +2 -2
  36. package/references/scripts/archives/archive-caps.mjs +1 -1
  37. package/references/scripts/archives/archive-changelog.mjs +8 -8
  38. package/references/scripts/archives/archive-decisions.mjs +7 -7
  39. package/references/scripts/archives/archive-issues.mjs +5 -5
  40. package/references/scripts/archives/rotation-conservation.mjs +2 -1
  41. package/references/scripts/docs-size/check-docs-size.mjs +15 -15
  42. package/references/scripts/family.json +2 -0
  43. package/references/scripts/gates/kit-command-gates.mjs +7 -8
  44. package/references/scripts/gates/migrate-gates.mjs +10 -10
  45. package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
  46. package/references/scripts/run.mjs +1 -2
  47. package/references/scripts/shared/index.mjs +2 -0
  48. package/references/scripts/shared/locations.mjs +103 -0
  49. package/references/scripts/spec-schema/spec-schema.mjs +2 -1
  50. package/references/templates/orchestration.json +1 -1
  51. package/tools/ack-store.mjs +2 -1
  52. package/tools/advisor-matrix.mjs +2 -1
  53. package/tools/advisor-skip/index.mjs +73 -0
  54. package/tools/apply-danger-check.mjs +20 -6
  55. package/tools/atomic-write.mjs +3 -2
  56. package/tools/attribution.mjs +2 -1
  57. package/tools/autonomy-config.mjs +2 -1
  58. package/tools/bridge-wiring.mjs +13 -11
  59. package/tools/carriers.mjs +54 -14
  60. package/tools/cheap-agents-read.mjs +28 -7
  61. package/tools/cheap-agents.mjs +15 -10
  62. package/tools/checker-gates-read.mjs +6 -5
  63. package/tools/commands.mjs +2 -2
  64. package/tools/control-bytes.mjs +43 -20
  65. package/tools/coverage-declared/config.mjs +2 -1
  66. package/tools/coverage-producer.mjs +10 -9
  67. package/tools/delegation.mjs +7 -6
  68. package/tools/detect-backends.mjs +1 -1
  69. package/tools/dispatch-baseline.mjs +2 -1
  70. package/tools/distribution-files/scripts.mjs +4 -4
  71. package/tools/doc-parity/index.mjs +46 -0
  72. package/tools/doc-parity.mjs +27 -47
  73. package/tools/ensure-configs.mjs +2 -2
  74. package/tools/ensure-ops.mjs +24 -24
  75. package/tools/ensure-specs.mjs +7 -7
  76. package/tools/epic-shape-cli.mjs +2 -2
  77. package/tools/epic-shape-ledger.mjs +5 -5
  78. package/tools/epic-shape.mjs +5 -3
  79. package/tools/epic-store.mjs +2 -1
  80. package/tools/family-members.mjs +7 -5
  81. package/tools/family-registry.mjs +36 -30
  82. package/tools/feedback-record-cli.mjs +4 -5
  83. package/tools/flow-writer.mjs +26 -15
  84. package/tools/gate-hook.mjs +33 -28
  85. package/tools/gates-declaration.mjs +2 -1
  86. package/tools/gates-init.mjs +6 -5
  87. package/tools/git-hooks.mjs +64 -41
  88. package/tools/grounding.mjs +3 -2
  89. package/tools/hide-footprint.mjs +2 -1
  90. package/tools/hook-writer/index.mjs +147 -0
  91. package/tools/init-preflight.mjs +5 -4
  92. package/tools/init-project.mjs +12 -11
  93. package/tools/inject-methodology.mjs +3 -2
  94. package/tools/jev-guide.mjs +2 -2
  95. package/tools/known-footprint.mjs +27 -25
  96. package/tools/mcp-registration.mjs +6 -5
  97. package/tools/migration-blocks.mjs +2 -1
  98. package/tools/migration-notes.mjs +2 -2
  99. package/tools/node-evidence.mjs +4 -4
  100. package/tools/now-facts.mjs +5 -5
  101. package/tools/now-status.mjs +1 -5
  102. package/tools/orchestration-config.mjs +2 -1
  103. package/tools/orchestration-readme.mjs +7 -2
  104. package/tools/plan-approval/cli.mjs +45 -0
  105. package/tools/plan-approval/entries.mjs +109 -0
  106. package/tools/plan-approval/index.mjs +2 -0
  107. package/tools/plan-approval/record.mjs +198 -0
  108. package/tools/plan-files.mjs +6 -4
  109. package/tools/plan-shape-cli.mjs +10 -64
  110. package/tools/plan-shape-facts.mjs +240 -83
  111. package/tools/plan-shape.mjs +173 -160
  112. package/tools/plan-structure/cli.mjs +79 -0
  113. package/tools/plan-structure/index.mjs +67 -0
  114. package/tools/procedures.mjs +21 -17
  115. package/tools/profile-gaps.mjs +4 -6
  116. package/tools/project-rules/rules-priors.mjs +2 -0
  117. package/tools/project-rules/themes.mjs +6 -4
  118. package/tools/recipes.mjs +44 -29
  119. package/tools/recommendations.mjs +90 -39
  120. package/tools/reference-profile.mjs +2 -2
  121. package/tools/release-scan/index.mjs +30 -0
  122. package/tools/release-scan.mjs +46 -25
  123. package/tools/renderers.mjs +14 -8
  124. package/tools/repo-lex.mjs +84 -0
  125. package/tools/robustness-brief.mjs +14 -11
  126. package/tools/sandbox-masks.mjs +6 -4
  127. package/tools/satellite-locator.mjs +3 -2
  128. package/tools/script-priors.mjs +3 -2
  129. package/tools/session-close-check.mjs +71 -15
  130. package/tools/set-flow.mjs +2 -2
  131. package/tools/set-recipe.mjs +17 -9
  132. package/tools/source-size/help.mjs +4 -4
  133. package/tools/source-size/layout.mjs +2 -1
  134. package/tools/source-size/piles.mjs +2 -2
  135. package/tools/source-size-config.mjs +3 -3
  136. package/tools/source-size-refusal.mjs +4 -3
  137. package/tools/source-size-report.mjs +41 -13
  138. package/tools/spec-check-cli.mjs +159 -21
  139. package/tools/spec-check-ops.mjs +74 -5
  140. package/tools/spec-check.mjs +54 -45
  141. package/tools/spec-coverage-cli.mjs +3 -2
  142. package/tools/stage-render/cli.mjs +231 -0
  143. package/tools/stage-render/index.mjs +340 -0
  144. package/tools/stage-render/stages.json +115 -0
  145. package/tools/stage-write-guard/cli.mjs +64 -0
  146. package/tools/stage-write-guard/index.mjs +56 -0
  147. package/tools/state-block-hook.mjs +38 -163
  148. package/tools/task-brief.mjs +8 -13
  149. package/tools/task-thread.mjs +3 -1
  150. package/tools/tier-guide-facts.mjs +23 -9
  151. package/tools/tier-preview.mjs +15 -19
  152. package/tools/transition/index.mjs +10 -9
  153. package/tools/uninstall.mjs +26 -12
  154. package/tools/vehicle-settings.mjs +2 -1
  155. package/tools/velocity-profile.mjs +5 -6
  156. package/tools/view-model.mjs +7 -4
  157. package/tools/worktree-prompt.mjs +7 -3
  158. package/tools/worktrees.mjs +235 -159
  159. package/tools/write-lanes.mjs +20 -14
@@ -1,72 +1,103 @@
1
1
  import { lstatSync, readdirSync, realpathSync } from 'node:fs';
2
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
- import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
2
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from 'node:path';
3
+ import { PACKAGE_JSON, SOURCE_SIZE } from '../references/scripts/shared/index.mjs';
4
+ import { readSpecDocument, SPEC_SCHEMA } from '../references/scripts/spec-schema/index.mjs';
5
+ import { lstatNoFollowRead, readRegularFileNoFollow } from './fs-read-nofollow.mjs';
4
6
  import { classIds, readShippedRobustnessLiterals } from './robustness-literals.mjs';
5
7
  import { KIT_FOLDER_ROOT, segmentPrefixOf, validateSourceSizeConfig } from './source-size-config.mjs';
6
- import { getLineCount, isSweep, resolveAnchorCandidates, unique } from './plan-shape.mjs';
8
+ import { checkPlanStructure, isSweep, parseLedger, PLAN_TITLE_PREFIX, resolveAnchorCandidates, unique } from './plan-shape.mjs';
9
+ import { plansInFlight, PLANS_REL } from './plan-files.mjs';
7
10
  import { listStories } from './claim-relation.mjs';
8
11
  import { EPICS_REL, readEpicStore } from './epic-store.mjs';
9
12
  import { sweepSiblings } from './epic-shape-ledger.mjs';
10
13
  import { PIN_FILE } from './plan-shape-ownership.mjs';
11
14
  import { NEVER_WALKED } from './repo-lex.mjs';
15
+ export { isSweep };
12
16
 
13
- const SOURCE_SIZE_REL = 'docs/ai/source-size.json';
14
- const PACKAGE_FILE = 'package.json';
15
17
  const NEGATED_CLASS = /\[[!^]/;
16
18
  const UNSUPPORTED_GLOB = /[()\\\u0000-\u001f]/;
17
19
  const STORE_REFUSED = 'refused';
18
20
  const FINDING_SEPARATOR = '; ';
21
+ const READ_OK = 'ok';
22
+ const READ_ABSENT = 'absent';
23
+ const MISSING_FILE_CODE = 'ENOENT';
24
+ const PLAN_TITLE_LEVEL = 1;
25
+ const { storePrefix } = SPEC_SCHEMA;
19
26
 
20
27
  const usageError = (message, scope = 'repository') => Object.assign(new Error(message), { exitCode: 2, scope });
21
28
  const planError = (message) => usageError(message, 'plan');
22
29
  const toPosix = (path) => path.split(sep).join('/');
23
- const isInside = (root, path) => path === root || path.startsWith(`${root}${sep}`);
30
+ const isInside = (root, path) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
24
31
  const isLexicallySafe = (path) => typeof path === 'string' && path.length > 0 && !isAbsolute(path) &&
25
32
  !path.startsWith('/') && !path.includes('\\') && !path.split('/').includes('..');
26
33
 
27
- const getLstat = (path, fail = usageError) => {
34
+ const remember = (cache, key, read) => {
35
+ if (!cache.has(key)) {
36
+ try {
37
+ cache.set(key, { value: read() });
38
+ } catch (error) {
39
+ cache.set(key, { error });
40
+ }
41
+ }
42
+ const result = cache.get(key);
43
+ if (Object.hasOwn(result, 'error')) throw result.error;
44
+ return result.value;
45
+ };
46
+
47
+ const readOnce = (repo, read, key, ...args) => {
48
+ if (!repo.reads.has(read)) repo.reads.set(read, new Map());
49
+ return remember(repo.reads.get(read), key, () => read(key, ...args));
50
+ };
51
+
52
+ const inspectPath = (repo, path, fail = usageError, read = lstatSync) => {
28
53
  try {
29
- return lstatSync(path);
54
+ return readOnce(repo, read, path);
30
55
  } catch (error) {
31
56
  if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return null;
32
57
  throw fail(`cannot inspect ${path} (${error.message})`);
33
58
  }
34
59
  };
35
60
 
36
- const walkRegularFiles = (root, directory = root) => readdirSync(directory, { withFileTypes: true })
37
- .sort((left, right) => left.name.localeCompare(right.name))
61
+ const readEntries = (path) => readdirSync(path, { withFileTypes: true });
62
+ const walkRegularFiles = (directory, repo, root) => readRepositoryPath(directory, 'list', (path) => readOnce(repo, readEntries, path))
63
+ .toSorted((left, right) => left.name.localeCompare(right.name))
38
64
  .flatMap((entry) => {
39
65
  const path = join(directory, entry.name);
40
66
  const rel = toPosix(relative(root, path));
41
- if (entry.isDirectory() && !NEVER_WALKED.includes(entry.name)) return walkRegularFiles(root, path);
67
+ if (entry.isDirectory() && !NEVER_WALKED.includes(entry.name)) return walkRegularFiles(path, repo, root);
42
68
  return entry.isFile() ? [rel] : [];
43
69
  });
44
70
 
45
- const getRealpath = (path) => {
46
- try {
47
- return realpathSync(path);
48
- } catch {
49
- return null;
50
- }
51
- };
52
-
53
- const resolveAbsentLeaf = (root, path) => {
54
- const rootReal = realpathSync(root);
71
+ const getRepoRoot = (repo, allowAbsent) => readRepositoryPath(repo.root, 'resolve', (path) => readOnce(repo, realpathSync, path), allowAbsent);
72
+ const resolveAbsentLeaf = (repo, path) => {
73
+ const root = getRepoRoot(repo);
55
74
  const lexical = resolve(root, path);
56
- if (!isInside(resolve(root), lexical)) return { contained: false, resolved: lexical };
75
+ if (!isInside(root, lexical)) return false;
57
76
  const findExisting = (candidate, missing) => {
58
- const real = getLstat(candidate, planError) ? getRealpath(candidate) : null;
77
+ const real = inspectPath(repo, candidate, planError) ? inspectPath(repo, candidate, planError, realpathSync) : null;
59
78
  if (real) return join(real, ...missing);
60
79
  const parent = dirname(candidate);
61
80
  if (parent === candidate) return candidate;
62
81
  return findExisting(parent, [basename(candidate), ...missing]);
63
82
  };
64
- const resolved = findExisting(lexical, []);
65
- return { contained: isInside(rootReal, resolved), resolved };
83
+ return isInside(root, findExisting(lexical, []));
66
84
  };
67
85
 
68
- const readJsonNoFollow = (path, label) => {
69
- const result = readRegularFileNoFollow(path);
86
+ const probeListedPath = (repo, segments) => {
87
+ if (segments.some((segment) => !segment || segment === '.' || segment === '..' || NEVER_WALKED.includes(segment))) return null;
88
+ const root = getRepoRoot(repo);
89
+ if (!segments.slice(0, -1).every((_, index) => inspectPath(repo, join(root, ...segments.slice(0, index + 1)))?.isDirectory())) return null;
90
+ return inspectPath(repo, join(root, ...segments));
91
+ };
92
+
93
+ const listFiles = (repo, start = []) => {
94
+ if (start.length && !probeListedPath(repo, start)?.isDirectory()) return [];
95
+ const root = getRepoRoot(repo);
96
+ return readOnce(repo, walkRegularFiles, join(root, ...start), repo, root);
97
+ };
98
+
99
+ const readJsonNoFollow = (repo, path, label) => {
100
+ const result = readOnce(repo, readRegularFileNoFollow, path);
70
101
  if (result.outcome === 'absent') return null;
71
102
  if (result.outcome !== 'ok') throw usageError(`${label} must be a readable regular file (${result.className ?? result.code ?? result.outcome})`);
72
103
  try {
@@ -78,14 +109,13 @@ const readJsonNoFollow = (path, label) => {
78
109
  }
79
110
  };
80
111
 
81
- const loadPractice = (root) => {
82
- const parsed = readJsonNoFollow(join(root, SOURCE_SIZE_REL), SOURCE_SIZE_REL);
83
- if (parsed === null) return { capDeclared: false, cap: null, config: null };
112
+ const loadSourceScope = (root, repo) => {
113
+ const parsed = readJsonNoFollow(repo, join(root, SOURCE_SIZE), SOURCE_SIZE);
114
+ if (parsed === null) return null;
84
115
  try {
85
- const config = validateSourceSizeConfig(parsed);
86
- return { capDeclared: true, cap: config.defaults.maxLines, config };
116
+ return validateSourceSizeConfig(parsed);
87
117
  } catch (error) {
88
- throw usageError(`${SOURCE_SIZE_REL} is malformed (${error.message})`);
118
+ throw usageError(`${SOURCE_SIZE} is malformed (${error.message})`);
89
119
  }
90
120
  };
91
121
 
@@ -126,11 +156,26 @@ const compileGlob = (pattern) => {
126
156
  }
127
157
  };
128
158
 
129
- export const expandPatterns = (repoFiles, patterns) => Object.fromEntries(patterns.map((pattern) => {
130
- const compiled = compileGlob(pattern);
131
- if (!compiled) throw planError(`unsupported glob in plan path: ${pattern}`);
132
- return [pattern, repoFiles.filter((path) => compiled.test(path))];
133
- }));
159
+ const sweepStart = (pattern) => {
160
+ const segments = pattern.split('/');
161
+ return segments.slice(0, segments.findIndex(isSweep));
162
+ };
163
+
164
+ const getExpansions = (patterns, list, addPath = () => {}) => {
165
+ const cache = new Map();
166
+ const descriptors = unique(patterns).map((pattern) => {
167
+ const compiled = compileGlob(pattern);
168
+ if (!compiled) throw planError(`unsupported glob in plan path: ${pattern}`);
169
+ return [pattern, { enumerable: true, get: () => remember(cache, pattern, () => {
170
+ const paths = list(pattern).filter((path) => compiled.test(path));
171
+ paths.forEach(addPath);
172
+ return paths;
173
+ }) }];
174
+ });
175
+ return Object.defineProperties({}, Object.fromEntries(descriptors));
176
+ };
177
+
178
+ export const expandPatterns = (repoFiles, patterns) => ({ ...getExpansions(patterns, () => repoFiles) });
134
179
 
135
180
  const matchFilesEntry = (entry, ownedPath) => {
136
181
  const normalized = entry.replace(/^\.\//, '').replace(/\/$/, '');
@@ -153,25 +198,25 @@ const getShipped = (packageJson, ownedPath) => {
153
198
  }, false);
154
199
  };
155
200
 
156
- const findPackage = (root, path, cache) => {
201
+ const findPackage = (path, repo) => {
202
+ const root = getRepoRoot(repo);
157
203
  const start = resolve(root, dirname(path));
158
204
  const visit = (directory) => {
159
- if (!isInside(resolve(root), directory)) return null;
160
- const packagePath = join(directory, PACKAGE_FILE);
161
- if (getLstat(packagePath)) {
205
+ if (!isInside(root, directory)) return null;
206
+ const packagePath = join(directory, PACKAGE_JSON);
207
+ if (inspectPath(repo, packagePath)) {
162
208
  const relRoot = toPosix(relative(root, directory)) || '.';
163
- if (!cache.has(relRoot)) cache.set(relRoot, readJsonNoFollow(packagePath, toPosix(relative(root, packagePath))));
164
- return { root: relRoot, json: cache.get(relRoot) };
209
+ const json = remember(repo.packageCache, relRoot, () => readJsonNoFollow(repo, packagePath, toPosix(relative(root, packagePath))));
210
+ return { root: relRoot, json };
165
211
  }
166
- return directory === resolve(root) ? null : visit(dirname(directory));
212
+ return directory === root ? null : visit(dirname(directory));
167
213
  };
168
214
  return visit(start);
169
215
  };
170
216
 
171
- const getPin = (root, owner, repoFiles, cache) => {
172
- const prefix = owner.root === '.' ? '' : `${owner.root}/`;
173
- const pins = repoFiles.filter((path) => path.startsWith(prefix) && basename(path) === PIN_FILE &&
174
- findPackage(root, path, cache)?.root === owner.root);
217
+ const getPin = (repo, owner) => {
218
+ const pins = listFiles(repo, owner.root === '.' ? [] : owner.root.split('/')).filter((path) =>
219
+ basename(path) === PIN_FILE && readOnce(repo, findPackage, path, repo)?.root === owner.root);
175
220
  if (pins.length > 1) throw usageError(`package ${owner.root} has several ${PIN_FILE} files: ${pins.join(', ')}`);
176
221
  return pins[0] ?? null;
177
222
  };
@@ -183,31 +228,44 @@ const describePinSkip = (owner, shipped, pinTest) => {
183
228
  return shipped === true && pinTest === null ? `no ${PIN_FILE} under package ${owner.root}` : null;
184
229
  };
185
230
 
186
- const describePath = (root, path, practice, repoFiles, packageCache) => {
231
+ const describeContract = (path, text) => {
232
+ const { kind, status, structure, errors } = readSpecDocument(text, path.slice(storePrefix.length));
233
+ const resolveTargets = (entries = []) => entries.map(({ target }) => posix.join(posix.dirname(path), target));
234
+ return { kind, status, children: resolveTargets(structure?.children), parts: resolveTargets(structure?.parts), refused: errors.length > 0 };
235
+ };
236
+
237
+ const getPathFacts = (repo, path, sourceScope, withContract) => {
187
238
  const safe = isLexicallySafe(path);
188
- const containment = safe ? resolveAbsentLeaf(root, path) : { contained: false, resolved: resolve(root, path) };
189
- const stat = safe ? getLstat(resolve(root, path), planError) : null;
190
- const read = stat?.isFile() ? readRegularFileNoFollow(resolve(root, path)) : null;
191
- if (read && read.outcome !== 'ok') throw planError(`${path} cannot be read without following it (${read.className ?? read.code ?? read.outcome})`);
192
- const kind = stat === null ? 'absent' : stat.isFile() ? 'regular' : 'other';
193
- const owner = safe && containment.contained && !isSweep(path) ? findPackage(root, path, packageCache) : null;
194
- const ownedPath = owner ? toPosix(relative(owner.root === '.' ? root : join(root, owner.root), resolve(root, path))) : null;
195
- const shipped = owner ? getShipped(owner.json, ownedPath) : 'unknown';
196
- const pinTest = owner && shipped === true ? getPin(root, owner, repoFiles, packageCache) : null;
197
- return {
198
- kind,
199
- lines: read?.outcome === 'ok' ? getLineCount(read.content) : 0,
200
- recordedLines: practice.config?.baseline?.[path]?.lines ?? null,
201
- inScope: isInScope(path, practice.config),
202
- shipped,
203
- pinTest,
204
- pinSkip: describePinSkip(owner, shipped, pinTest),
205
- contained: containment.contained,
239
+ const absolute = () => resolve(getRepoRoot(repo), path);
240
+ const stat = () => safe ? inspectPath(repo, absolute(), planError) : null;
241
+ const read = () => {
242
+ if (!stat()?.isFile()) return null;
243
+ const result = readOnce(repo, readRegularFileNoFollow, absolute());
244
+ if (result.outcome !== 'ok') throw planError(`${path} cannot be read without following it (${result.className ?? result.code ?? result.outcome})`);
245
+ return result;
206
246
  };
247
+ const owner = () => !isSweep(path) && facts.contained ? readOnce(repo, findPackage, path, repo) : null;
248
+ const facts = {
249
+ get kind() { return read() ? 'regular' : stat() ? 'other' : 'absent'; },
250
+ get inScope() { return isInScope(path, sourceScope()); },
251
+ get shipped() {
252
+ const pkg = owner();
253
+ return pkg ? getShipped(pkg.json, toPosix(relative(join(getRepoRoot(repo), pkg.root), absolute()))) : 'unknown';
254
+ },
255
+ get pinTest() { return facts.shipped === true ? getPin(repo, owner()) : null; },
256
+ get pinSkip() { return describePinSkip(owner(), facts.shipped, facts.pinTest); },
257
+ get contained() { return safe && resolveAbsentLeaf(repo, path); },
258
+ get contract() {
259
+ const document = path.startsWith(storePrefix) && path.endsWith('.md') ? read() : null;
260
+ return document ? describeContract(path, document.content) : undefined;
261
+ },
262
+ };
263
+ if (!withContract) delete facts.contract;
264
+ return facts;
207
265
  };
208
266
 
209
- const readStoryFacts = (root) => {
210
- const store = readEpicStore(root);
267
+ const readStoryFacts = (root, repo) => {
268
+ const store = readEpicStore(root, (path) => readOnce(repo, readRegularFileNoFollow, path));
211
269
  if (store.outcome === STORE_REFUSED) return { stories: [], landedEpics: [], storeRefusal: `${EPICS_REL}: ${store.reason}` };
212
270
  const sweep = sweepSiblings(store.entries, EPICS_REL);
213
271
  return {
@@ -217,20 +275,119 @@ const readStoryFacts = (root) => {
217
275
  };
218
276
  };
219
277
 
220
- export const openRepo = (root, { robustnessDeps } = {}) => {
221
- const repoRoot = realpathSync(root);
222
- return { repoRoot, repoFiles: walkRegularFiles(repoRoot), practice: loadPractice(repoRoot), robustClasses: loadRobustClasses(robustnessDeps),
223
- packageCache: new Map(), ...readStoryFacts(repoRoot) };
278
+ export const openRepo = (root, { robustnessDeps } = {}) => ({ root: resolve(root), robustnessDeps, reads: new Map(), packageCache: new Map() });
279
+
280
+ export const expandSweepPaths = (root, patterns) => {
281
+ const repo = openRepo(root);
282
+ return { ...getExpansions(patterns, (pattern) => listFiles(repo, sweepStart(pattern))) };
283
+ };
284
+
285
+ const readRepositoryPath = (path, action, read, allowAbsent = false) => {
286
+ try {
287
+ return read(path);
288
+ } catch (error) {
289
+ if (allowAbsent && error?.code === 'ENOENT') return null;
290
+ const cause = ['EACCES', 'EPERM'].includes(error?.code) ? error.code : error?.message ?? String(error);
291
+ throw usageError(`cannot ${action} ${error?.path ?? path} (${cause})`);
292
+ }
293
+ };
294
+
295
+ const formatPlanReadError = (path, { outcome, className, code }, absentCause = outcome) =>
296
+ `${path} must be a readable regular plan file (${className ?? code ?? (outcome === READ_ABSENT ? absentCause : outcome)})`;
297
+
298
+ const parsePlanDocument = (identity, text, requiresPlanTitle = false) => {
299
+ try {
300
+ const { document: { headings: [first] }, rows } = parseLedger(text);
301
+ if (requiresPlanTitle && (first?.level !== PLAN_TITLE_LEVEL || !first.text.startsWith(PLAN_TITLE_PREFIX))) return null;
302
+ return { identity, text, rows: rows.filter((row) => row.valid) };
303
+ } catch {
304
+ return { identity, text, rows: [] };
305
+ }
306
+ };
307
+
308
+ export const readPlanDocument = (cwd, operand) => {
309
+ const path = resolve(cwd, operand);
310
+ const result = readRegularFileNoFollow(path);
311
+ if (result.outcome !== READ_OK) throw new Error(formatPlanReadError(path, result));
312
+ const identity = toPosix(relative(cwd, path));
313
+ return parsePlanDocument(identity, result.content);
314
+ };
315
+
316
+ const readFlightPlan = (repo, root, name) => {
317
+ const identity = `${PLANS_REL}/${name}`;
318
+ const result = readOnce(repo, readRegularFileNoFollow, join(root, identity));
319
+ if (result.outcome !== READ_OK) throw usageError(formatPlanReadError(identity, result, MISSING_FILE_CODE));
320
+ return parsePlanDocument(identity, result.content, true);
321
+ };
322
+
323
+ // A facts failure scoped to the plan's own paths is that plan's listed finding, so the other plans
324
+ // are still judged; a repository-level refusal (the practice, a package, its pins) keeps its usage class.
325
+ export const judgePlan = (root, { identity, text, rows }, { rules = checkPlanStructure, ...options } = {}) => {
326
+ const paths = [...rows.map((row) => row.path), ...rows.map((row) => row.anchorPath).filter(Boolean)];
327
+ try {
328
+ const result = rules(text, getFacts(root, { paths, ...options }));
329
+ return { identity, text, rows, result, accepted: result.findings.length === 0 };
330
+ } catch (error) {
331
+ if (error?.scope !== 'plan') throw error;
332
+ return { identity, text, rows, accepted: false, result: { findings: [{ line: 1, code: 'facts', message: error.message, rowId: null }], skips: [] } };
333
+ }
334
+ };
335
+
336
+ const readFlight = (root, repo) => {
337
+ if (root === null) return { plans: [] };
338
+ for (const directory of [dirname(PLANS_REL), PLANS_REL]) {
339
+ const status = readRepositoryPath(join(root, directory), 'inspect', (path) => lstatNoFollowRead(path, (target) => readOnce(repo, lstatSync, target)));
340
+ if (status === null) return { plans: [] };
341
+ if (!status.isDirectory()) throw usageError(`${directory} could not be read (${status.isSymbolicLink() ? 'symlink' : 'ENOTDIR'})`);
342
+ }
343
+ const entries = readRepositoryPath(join(root, PLANS_REL), 'list', (path) => readOnce(repo, readEntries, path));
344
+ const names = plansInFlight(root, () => entries);
345
+ const documents = names.map((name) => readFlightPlan(repo, root, name)).filter(Boolean);
346
+ return { plans: documents.map((document) => judgePlan(root, document, { repo })), skipped: names.length - documents.length, repo };
224
347
  };
225
348
 
226
- export const expandSweepPaths = (root, patterns) => expandPatterns(walkRegularFiles(realpathSync(root)), patterns);
349
+ export const readPlansInFlight = (root, { robustnessDeps, repo = openRepo(root, { robustnessDeps }) } = {}) =>
350
+ readOnce(repo, readFlight, getRepoRoot(repo, true), repo);
351
+
352
+ const getFacts = (root, { paths = [], robustnessDeps, repo = openRepo(root, { robustnessDeps }), plan } = {}) => {
353
+ const sourceScope = () => readOnce(repo, loadSourceScope, getRepoRoot(repo), repo);
354
+ const storyFacts = () => readOnce(repo, readStoryFacts, getRepoRoot(repo), repo);
355
+ const pathFacts = Object.create(null);
356
+ const addPath = (path) => {
357
+ pathFacts[path] ??= getPathFacts(repo, path, sourceScope, plan !== undefined);
358
+ };
359
+ const expansions = getExpansions(paths.filter(isSweep), (pattern) => listFiles(repo, sweepStart(pattern)), addPath);
360
+ paths.forEach(addPath);
361
+ const candidates = (suffix, precedingPaths = []) => {
362
+ if (isLexicallySafe(suffix) && probeListedPath(repo, suffix.split('/'))?.isFile()) return [suffix];
363
+ const above = resolveAnchorCandidates([], suffix, precedingPaths);
364
+ return above.length ? above : resolveAnchorCandidates([], suffix, listFiles(repo));
365
+ };
366
+ const facts = {
367
+ get robustClasses() { return readOnce(repo, loadRobustClasses, repo.robustnessDeps); },
368
+ get pathFacts() { return pathFacts; },
369
+ get expansions() { return expansions; },
370
+ get repoFiles() { return listFiles(repo); },
371
+ get candidates() { return candidates; },
372
+ get stories() { return storyFacts().stories; },
373
+ get landedEpics() { return storyFacts().landedEpics; },
374
+ get storeRefusal() { return storyFacts().storeRefusal; },
375
+ get otherPlanCreates() {
376
+ return readPlansInFlight(root, { repo }).plans.filter(({ identity, accepted }) => accepted && identity !== plan)
377
+ .flatMap(({ rows }) => rows.filter(({ verb, path }) => verb === 'create' && path.startsWith(storePrefix)).map(({ path }) => path));
378
+ },
379
+ };
380
+ if (plan === undefined) delete facts.otherPlanCreates;
381
+ return facts;
382
+ };
227
383
 
228
- export const buildFacts = (root, { paths = [], robustnessDeps, repo = openRepo(root, { robustnessDeps }) } = {}) => {
229
- const { repoRoot, repoFiles, practice, robustClasses, packageCache, stories, landedEpics, storeRefusal } = repo;
230
- const expansions = expandPatterns(repoFiles, paths.filter(isSweep));
231
- const allPaths = unique([...paths, ...Object.values(expansions).flat()]);
232
- const pathFacts = Object.fromEntries(allPaths.map((path) => [path, describePath(repoRoot, path, practice, repoFiles, packageCache)]));
233
- const candidates = (suffix, precedingPaths = []) => resolveAnchorCandidates(repoFiles, suffix, precedingPaths);
234
- return { capDeclared: practice.capDeclared, cap: practice.cap, robustClasses, pathFacts, expansions, repoFiles, candidates,
235
- stories, landedEpics, storeRefusal };
384
+ export const buildFacts = (root, { paths = [], robustnessDeps, repo, plan } = {}) => {
385
+ const facts = { ...getFacts(root, { paths, robustnessDeps, repo, plan }) };
386
+ facts.expansions = { ...facts.expansions };
387
+ facts.pathFacts = Object.fromEntries(Object.entries(facts.pathFacts).map(([path, getters]) => {
388
+ const fact = { ...getters };
389
+ if (fact.contract === undefined) delete fact.contract;
390
+ return [path, fact];
391
+ }));
392
+ return facts;
236
393
  };