@mvarble/mesearch-workflow 0.0.0-stage → 0.1.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/agents/reference/authoring.md +142 -0
  4. package/agents/reference/workflow.md +118 -0
  5. package/agents/skills/wf-abandon/SKILL.md +18 -0
  6. package/agents/skills/wf-approve/SKILL.md +24 -0
  7. package/agents/skills/wf-build/SKILL.md +45 -0
  8. package/agents/skills/wf-plan/SKILL.md +49 -0
  9. package/agents/skills/wf-publish/SKILL.md +42 -0
  10. package/agents/skills/wf-reopen/SKILL.md +22 -0
  11. package/agents/skills/wf-resume/SKILL.md +16 -0
  12. package/agents/skills/wf-start/SKILL.md +27 -0
  13. package/agents/skills/wf-status/SKILL.md +15 -0
  14. package/agents/skills/wf-writeup/SKILL.md +61 -0
  15. package/app/ambient.d.ts +71 -0
  16. package/app/lib/components/CopyCode.svelte +24 -0
  17. package/app/lib/components/DocumentMap.svelte +38 -0
  18. package/app/lib/components/DocumentPage.svelte +184 -0
  19. package/app/lib/components/Icon.svelte +35 -0
  20. package/app/lib/components/ImageFigure.svelte +213 -0
  21. package/app/lib/components/LinkList.svelte +46 -0
  22. package/app/lib/components/ModelGraph.svelte +169 -0
  23. package/app/lib/components/OpenEntry.svelte +35 -0
  24. package/app/lib/components/PageList.svelte +35 -0
  25. package/app/lib/components/PrevNext.svelte +24 -0
  26. package/app/lib/components/Proof.svelte +12 -0
  27. package/app/lib/components/Shell.svelte +55 -0
  28. package/app/lib/components/Sidebar.svelte +50 -0
  29. package/app/lib/components/StageRail.svelte +30 -0
  30. package/app/lib/components/Statement.svelte +41 -0
  31. package/app/lib/components/Tex.svelte +25 -0
  32. package/app/lib/components/ThemeToggle.svelte +17 -0
  33. package/app/lib/components/Timeline.svelte +31 -0
  34. package/app/lib/components/Toc.svelte +41 -0
  35. package/app/lib/components/TopBar.svelte +55 -0
  36. package/app/lib/components/TrackCard.svelte +19 -0
  37. package/app/lib/documents.ts +52 -0
  38. package/app/lib/graph/describe.ts +29 -0
  39. package/app/lib/graph/geometry.ts +296 -0
  40. package/app/lib/graph/spec.ts +158 -0
  41. package/app/lib/kit.ts +11 -0
  42. package/app/lib/load.ts +12 -0
  43. package/app/lib/map.ts +6 -0
  44. package/app/lib/nav.ts +59 -0
  45. package/app/lib/questions.ts +33 -0
  46. package/app/lib/server/document.ts +117 -0
  47. package/app/lib/server/map.ts +41 -0
  48. package/app/lib/server/markdown.ts +134 -0
  49. package/app/lib/server/open.ts +35 -0
  50. package/app/lib/server/repo.ts +6 -0
  51. package/app/lib/server/specs.ts +26 -0
  52. package/app/lib/server/title.ts +9 -0
  53. package/app/lib/state/persisted.svelte.ts +40 -0
  54. package/app/lib/state/theme.svelte.ts +24 -0
  55. package/app/lib/tex.ts +99 -0
  56. package/app/params/slug.ts +5 -0
  57. package/app/params/track.ts +5 -0
  58. package/app/routes/+layout.ts +2 -0
  59. package/app/routes/[...key].md/+server.ts +19 -0
  60. package/app/routes/[track=track]/+page.server.ts +14 -0
  61. package/app/routes/[track=track]/+page.svelte +24 -0
  62. package/app/routes/[track=track]/[slug=slug]/+page.server.ts +9 -0
  63. package/app/routes/[track=track]/[slug=slug]/+page.svelte +7 -0
  64. package/app/routes/[track=track]/[slug=slug]/+page.ts +4 -0
  65. package/app/routes/archive/+page.server.ts +18 -0
  66. package/app/routes/archive/+page.svelte +44 -0
  67. package/app/routes/archive/[entry=slug]/+page.server.ts +9 -0
  68. package/app/routes/archive/[entry=slug]/+page.svelte +7 -0
  69. package/app/routes/archive/[entry=slug]/+page.ts +4 -0
  70. package/app/routes/archive/[entry=slug]/[name=slug]/+page.server.ts +14 -0
  71. package/app/routes/archive/[entry=slug]/[name=slug]/+page.svelte +7 -0
  72. package/app/routes/archive/[entry=slug]/[name=slug]/+page.ts +4 -0
  73. package/app/routes/llms-full.txt/+server.ts +17 -0
  74. package/app/routes/llms.txt/+server.ts +50 -0
  75. package/app/routes/math/+page.server.ts +21 -0
  76. package/app/routes/math/+page.svelte +56 -0
  77. package/app/routes/math/[slug=slug]/+page.server.ts +8 -0
  78. package/app/routes/math/[slug=slug]/+page.svelte +7 -0
  79. package/app/routes/math/[slug=slug]/+page.ts +4 -0
  80. package/app/styles/base.css +98 -0
  81. package/app/styles/code.css +83 -0
  82. package/app/styles/index.css +17 -0
  83. package/app/styles/katex.css +14 -0
  84. package/app/styles/layout.css +526 -0
  85. package/app/styles/text.css +96 -0
  86. package/app/styles/tokens/dimensions.css +31 -0
  87. package/app/styles/tokens/typography.css +33 -0
  88. package/app/styles/tokens.css +2 -0
  89. package/app/styles/utils/archive.css +339 -0
  90. package/app/styles/utils/buttons.css +28 -0
  91. package/app/styles/utils/callouts.css +41 -0
  92. package/app/styles/utils/cards.css +95 -0
  93. package/app/styles/utils/graph.css +186 -0
  94. package/app/styles/utils/map.css +45 -0
  95. package/app/styles/utils/tables.css +25 -0
  96. package/dist/cli.d.ts +2 -0
  97. package/dist/cli.js +88 -0
  98. package/dist/cli.js.map +1 -0
  99. package/dist/engine/cli.d.ts +12 -0
  100. package/dist/engine/cli.js +744 -0
  101. package/dist/engine/cli.js.map +1 -0
  102. package/dist/engine/config.d.ts +40 -0
  103. package/dist/engine/config.js +16 -0
  104. package/dist/engine/config.js.map +1 -0
  105. package/dist/engine/lib.d.ts +108 -0
  106. package/dist/engine/lib.js +375 -0
  107. package/dist/engine/lib.js.map +1 -0
  108. package/dist/engine/main.d.ts +1 -0
  109. package/dist/engine/main.js +45 -0
  110. package/dist/engine/main.js.map +1 -0
  111. package/dist/index.d.ts +4 -0
  112. package/dist/index.js +3 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/site/hooks.d.ts +27 -0
  115. package/dist/site/hooks.js +2 -0
  116. package/dist/site/hooks.js.map +1 -0
  117. package/dist/site/index.d.ts +1 -0
  118. package/dist/site/index.js +2 -0
  119. package/dist/site/index.js.map +1 -0
  120. package/dist/site/preset/index.d.ts +15 -0
  121. package/dist/site/preset/index.js +556 -0
  122. package/dist/site/preset/index.js.map +1 -0
  123. package/dist/site/preset/runtime.d.ts +42 -0
  124. package/dist/site/preset/runtime.js +99 -0
  125. package/dist/site/preset/runtime.js.map +1 -0
  126. package/dist/site/preset/types.d.ts +87 -0
  127. package/dist/site/preset/types.js +2 -0
  128. package/dist/site/preset/types.js.map +1 -0
  129. package/dist/site/vite.d.ts +14 -0
  130. package/dist/site/vite.js +202 -0
  131. package/dist/site/vite.js.map +1 -0
  132. package/dist/sync/index.d.ts +17 -0
  133. package/dist/sync/index.js +175 -0
  134. package/dist/sync/index.js.map +1 -0
  135. package/dist/sync/init.d.ts +7 -0
  136. package/dist/sync/init.js +62 -0
  137. package/dist/sync/init.js.map +1 -0
  138. package/dist/sync/render.d.ts +3 -0
  139. package/dist/sync/render.js +115 -0
  140. package/dist/sync/render.js.map +1 -0
  141. package/dist/sync/site.d.ts +3 -0
  142. package/dist/sync/site.js +58 -0
  143. package/dist/sync/site.js.map +1 -0
  144. package/package.json +78 -3
  145. package/templates/.agents/reference/authoring.md +12 -0
  146. package/templates/.agents/reference/stages/README.md +5 -0
  147. package/templates/AGENTS.md +42 -0
  148. package/templates/site/content/landing.md +5 -0
  149. package/templates/site/katex.config.ts +5 -0
  150. package/templates/site/package.json +22 -0
  151. package/templates/site/src/app.d.ts +8 -0
  152. package/templates/site/src/app.html +23 -0
  153. package/templates/site/src/lib/components/Logo.svelte +12 -0
  154. package/templates/site/src/lib/site.ts +39 -0
  155. package/templates/site/src/routes/+layout.server.ts +3 -0
  156. package/templates/site/src/routes/+layout.svelte +11 -0
  157. package/templates/site/src/routes/+page.server.ts +3 -0
  158. package/templates/site/src/routes/+page.svelte +34 -0
  159. package/templates/site/src/routes/+page.ts +7 -0
  160. package/templates/site/src/styles/index.css +4 -0
  161. package/templates/site/src/styles/tokens/colors.css +107 -0
  162. package/templates/site/static/favicon.svg +1 -0
  163. package/templates/site/tsconfig.json +20 -0
  164. package/templates/site/vite.config.ts +4 -0
  165. package/templates/workflow.config.ts +40 -0
@@ -0,0 +1,744 @@
1
+ // `bin/wf`: the workflow's command line. See `.agents/reference/mesearch/workflow.md`.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { ACTIVE, activeSlug, amendKey, amendPath, amendTarget, changedSince, checkboxes, config, CONTENT, contentHash, currentBranch, defaultBase, documentHash, documentPath, entryDir, frontmatterList, git, hasDocument, hasTodo, headCommit, isCommitted, isKind, listEntries, pageExists, pageKey, placeOf, readManifest, readWorkflow, refusal, repoRoot, setActive, skillOf, stageConfig, stagesOf, today, tryGit, useConfig, WorkflowError, workflowFile, writeWorkflow, } from "./lib.js";
5
+ const usage = () => `usage: bin/wf <command>
6
+
7
+ status [--expect <stage>] where the active entry stands, and what comes next
8
+ path [<stage>] the file of a stage's document (the current stage's by default)
9
+ start <slug> --kind <kind> [--title <title>] [--revises <slug>,...]
10
+ open an entry on this branch; kinds: ${Object.keys(config().kinds).join(', ')}
11
+ kinds the kinds of entry, their stages, and when each is used
12
+ approve accept the current stage and move to the next
13
+ reopen <stage> --reason <text> go back to an earlier stage
14
+ abandon --reason <text> set the active entry aside; its documents stay
15
+ resume <slug> take up an abandoned entry again
16
+ check [--base <ref>] [--merge] verify the rules (run by CI); --merge also requires no active entry
17
+ guard a Claude Code PreToolUse hook: refuses edits the stage does not allow
18
+
19
+ At its publish stage an entry may change a done entry's documents and statements, to keep a
20
+ reference in them true; it lists them under "amends" in its index.md, and approve records each
21
+ in the amended entry's history.
22
+
23
+ approve, reopen, abandon and resume are the human's to ask for.`;
24
+ class Output {
25
+ out = [];
26
+ err = [];
27
+ say = (line = '') => void this.out.push(line);
28
+ warn = (line) => void this.err.push(line);
29
+ result = (code) => ({
30
+ code,
31
+ stdout: this.out.length ? this.out.join('\n') + '\n' : '',
32
+ stderr: this.err.length ? this.err.join('\n') + '\n' : '',
33
+ });
34
+ }
35
+ export function run(argv, options) {
36
+ const io = new Output();
37
+ useConfig(options.config);
38
+ try {
39
+ const [command, ...rest] = argv;
40
+ const args = parseArgs(rest);
41
+ const root = repoRoot(options.cwd);
42
+ switch (command) {
43
+ case 'kinds':
44
+ return kindsOf(io);
45
+ case 'status':
46
+ return status(root, args, io);
47
+ case 'path':
48
+ return pathOf(root, args, io);
49
+ case 'start':
50
+ return start(root, args, io);
51
+ case 'approve':
52
+ return approve(root, args, io);
53
+ case 'reopen':
54
+ return reopen(root, args, io);
55
+ case 'abandon':
56
+ return abandon(root, args, io);
57
+ case 'resume':
58
+ return resume(root, args, io);
59
+ case 'check':
60
+ return check(root, args, io);
61
+ case 'guard':
62
+ return guard(root, options.stdin ?? '', io);
63
+ case undefined:
64
+ case 'help':
65
+ case '--help':
66
+ io.say(usage());
67
+ return io.result(0);
68
+ default:
69
+ io.warn(`wf: no command '${command}'.\n\n${usage()}`);
70
+ return io.result(2);
71
+ }
72
+ }
73
+ catch (error) {
74
+ if (!(error instanceof WorkflowError))
75
+ throw error;
76
+ io.warn(`wf: ${error.message}`);
77
+ return io.result(1);
78
+ }
79
+ }
80
+ function parseArgs(argv) {
81
+ const args = { positional: [], flags: {} };
82
+ for (let i = 0; i < argv.length; i++) {
83
+ const arg = argv[i];
84
+ if (!arg.startsWith('--')) {
85
+ args.positional.push(arg);
86
+ continue;
87
+ }
88
+ const [name, inline] = arg.slice(2).split(/=(.*)/s);
89
+ const next = argv[i + 1];
90
+ if (inline !== undefined)
91
+ args.flags[name] = inline;
92
+ else if (next !== undefined && !next.startsWith('--')) {
93
+ args.flags[name] = next;
94
+ i++;
95
+ }
96
+ else
97
+ args.flags[name] = true;
98
+ }
99
+ return args;
100
+ }
101
+ const flag = (args, name) => typeof args.flags[name] == 'string' ? args.flags[name] : undefined;
102
+ function requireActive(root) {
103
+ const slug = activeSlug(root);
104
+ if (!slug) {
105
+ throw new WorkflowError('no entry is active on this branch; start one with `/wf-start`.');
106
+ }
107
+ return { slug, workflow: readWorkflow(root, slug) };
108
+ }
109
+ function stageOf(workflow) {
110
+ if (workflow.stage == 'done' || workflow.stage == 'abandoned') {
111
+ throw new WorkflowError(`the entry is ${workflow.stage}.`);
112
+ }
113
+ return workflow.stage;
114
+ }
115
+ // What `wf-start` and the reference documents say of the kinds: one line each.
116
+ function kindsOf(io) {
117
+ for (const [kind, { stages, describe }] of Object.entries(config().kinds)) {
118
+ io.say(`${kind}: ${stages.join(' → ')}`);
119
+ io.say(` ${describe}`);
120
+ }
121
+ return io.result(0);
122
+ }
123
+ // ---------------------------------------------------------------------------
124
+ // status, path
125
+ function status(root, args, io) {
126
+ const expect = flag(args, 'expect');
127
+ const slug = activeSlug(root);
128
+ if (!slug) {
129
+ if (expect) {
130
+ io.warn(`wf: this step needs an entry at the ${expect} stage, and none is active on this ` +
131
+ 'branch. Start one with `/wf-start`.');
132
+ return io.result(3);
133
+ }
134
+ io.say('No entry is active on this branch. Start one with `/wf-start <slug> <kind>`.');
135
+ const entries = listEntries(root);
136
+ if (entries.length) {
137
+ io.say();
138
+ io.say('Entries:');
139
+ for (const entry of entries) {
140
+ try {
141
+ const workflow = readWorkflow(root, entry);
142
+ io.say(` ${entry.padEnd(28)} ${workflow.kind.padEnd(9)} ${workflow.stage}`);
143
+ }
144
+ catch (error) {
145
+ io.say(` ${entry.padEnd(28)} (${error.message})`);
146
+ }
147
+ }
148
+ }
149
+ return io.result(0);
150
+ }
151
+ const workflow = readWorkflow(root, slug);
152
+ if (expect && workflow.stage != expect) {
153
+ io.warn(`wf: this step is for the ${expect} stage, but '${slug}' is at ${workflow.stage}. ` +
154
+ (workflow.stage in config().stages
155
+ ? `The step for it is ${skillOf(workflow.stage)}.`
156
+ : ''));
157
+ return io.result(3);
158
+ }
159
+ const stages = stagesOf(workflow.kind);
160
+ const line = stages
161
+ .map((stage) => {
162
+ if (stage == workflow.stage)
163
+ return `[${stage}]`;
164
+ const approval = workflow.approvals[stage];
165
+ if (approval && !approval.stale)
166
+ return `${stage} ✓`;
167
+ if (approval?.stale)
168
+ return `${stage} (reopened)`;
169
+ return stage;
170
+ })
171
+ .join(' → ');
172
+ io.say(`Entry: ${slug} (${workflow.kind}), ${entryDir(slug)}/`);
173
+ io.say(`Stage: ${line}`);
174
+ const stage = workflow.stage;
175
+ if (hasDocument(stage))
176
+ io.say(`Document: ${documentPath(root, slug, stage)}`);
177
+ for (const list of stages.filter((stage) => stageConfig(stage).checklist)) {
178
+ const file = path.join(root, documentPath(root, slug, list));
179
+ if (!fs.existsSync(file))
180
+ continue;
181
+ const boxes = checkboxes(fs.readFileSync(file, 'utf8'));
182
+ const label = `${list[0].toUpperCase()}${list.slice(1)}:`.padEnd(9);
183
+ io.say(`${label} ${boxes.ticked} of ${boxes.total} done`);
184
+ }
185
+ io.say(`Next: work with ${skillOf(stage)}; when it is right, \`/wf-approve\` moves on` +
186
+ (stage == stages.at(-1) ? ' and finishes the entry.' : ` to ${nextStage(workflow)}.`));
187
+ return io.result(0);
188
+ }
189
+ function nextStage(workflow) {
190
+ const stages = stagesOf(workflow.kind);
191
+ return stages[stages.indexOf(workflow.stage) + 1] ?? 'done';
192
+ }
193
+ function pathOf(root, args, io) {
194
+ const { slug, workflow } = requireActive(root);
195
+ const stage = (args.positional[0] ?? workflow.stage);
196
+ if (!hasDocument(stage) || !stagesOf(workflow.kind).includes(stage)) {
197
+ throw new WorkflowError(`the ${stage} stage of a ${workflow.kind} has no document.`);
198
+ }
199
+ io.say(documentPath(root, slug, stage));
200
+ return io.result(0);
201
+ }
202
+ // ---------------------------------------------------------------------------
203
+ // start
204
+ function start(root, args, io) {
205
+ const [slug] = args.positional;
206
+ const kind = flag(args, 'kind');
207
+ if (!slug || !kind)
208
+ throw new WorkflowError('usage: wf start <slug> --kind <kind>');
209
+ if (!isKind(kind)) {
210
+ throw new WorkflowError(`'${kind}' is not a kind; one of ${Object.keys(config().kinds).join(', ')}.`);
211
+ }
212
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) {
213
+ throw new WorkflowError(`'${slug}' is not a slug: lowercase words joined by hyphens.`);
214
+ }
215
+ const active = activeSlug(root);
216
+ if (active) {
217
+ const workflow = readWorkflow(root, active);
218
+ throw new WorkflowError(`'${active}' is active on this branch (at ${workflow.stage}). Finish it, abandon it, ` +
219
+ 'or start the new entry on another branch.');
220
+ }
221
+ const branch = currentBranch(root);
222
+ if (branch == 'main') {
223
+ throw new WorkflowError('entries are worked on in a branch of their own, not on main.');
224
+ }
225
+ if (fs.existsSync(path.join(root, entryDir(slug)))) {
226
+ throw new WorkflowError(`${entryDir(slug)} exists already. An abandoned entry is taken up with \`wf resume\`; ` +
227
+ 'a finished one is revised by a new entry with `--revises`.');
228
+ }
229
+ const revises = (flag(args, 'revises') ?? '').split(',').filter(Boolean);
230
+ for (const earlier of revises) {
231
+ if (!fs.existsSync(path.join(root, workflowFile(earlier)))) {
232
+ throw new WorkflowError(`--revises names '${earlier}', which is not an entry.`);
233
+ }
234
+ }
235
+ const title = flag(args, 'title') ?? slug;
236
+ const first = stagesOf(kind)[0];
237
+ const frontmatter = [
238
+ '---',
239
+ `title: ${JSON.stringify(title)}`,
240
+ 'pages: []',
241
+ ...Object.entries(config().entryFields ?? {}).map(([field, value]) => `${field}: ${value}`),
242
+ ...(revises.length ? [`revises: [${revises.join(', ')}]`] : []),
243
+ '---',
244
+ ];
245
+ const body = ['> [!TODO]', '> Say in a paragraph what this entry sets out to do, and why.'];
246
+ fs.mkdirSync(path.join(root, entryDir(slug)), { recursive: true });
247
+ fs.writeFileSync(path.join(root, entryDir(slug), 'index.md'), [...frontmatter, '', ...body, ''].join('\n'));
248
+ writeWorkflow(root, slug, {
249
+ kind,
250
+ stage: first,
251
+ started: today(),
252
+ events: [{ date: today(), action: 'start', stage: first }],
253
+ approvals: {},
254
+ });
255
+ setActive(root, slug);
256
+ io.say(`Started '${slug}', a ${kind}, at the ${first} stage.`);
257
+ io.say(` ${entryDir(slug)}/index.md`);
258
+ io.say(` ${workflowFile(slug)}`);
259
+ io.say(` ${ACTIVE}`);
260
+ io.say(`Next: ${skillOf(first)}.`);
261
+ return io.result(0);
262
+ }
263
+ // ---------------------------------------------------------------------------
264
+ // approve
265
+ function approve(root, args, io) {
266
+ const { slug, workflow } = requireActive(root);
267
+ const stage = stageOf(workflow);
268
+ const problems = [
269
+ ...lockProblems(root, slug, workflow),
270
+ ...readiness(root, slug, workflow, stage, flag(args, 'base')),
271
+ ];
272
+ if (problems.length) {
273
+ throw new WorkflowError(`the ${stage} stage of '${slug}' is not ready:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
274
+ }
275
+ const commit = headCommit(root);
276
+ const amended = stage == 'publish' ? recordAmendments(root, slug, commit) : [];
277
+ const doc = hasDocument(stage) ? documentPath(root, slug, stage) : undefined;
278
+ workflow.approvals[stage] = {
279
+ date: today(),
280
+ commit,
281
+ ...(doc ? { hash: documentHash(root, doc, stage) } : {}),
282
+ };
283
+ workflow.events.push({ date: today(), action: 'approve', stage, commit });
284
+ const next = nextStage(workflow);
285
+ if (next == 'done') {
286
+ workflow.stage = 'done';
287
+ workflow.finished = today();
288
+ setActive(root, undefined);
289
+ }
290
+ else {
291
+ workflow.stage = next;
292
+ }
293
+ writeWorkflow(root, slug, workflow);
294
+ io.say(`Approved the ${stage} stage of '${slug}' at ${commit}.`);
295
+ for (const other of amended) {
296
+ io.say(`Recorded its amendments of '${other}'. Commit ${workflowFile(other)}.`);
297
+ }
298
+ if (next == 'done') {
299
+ io.say(`'${slug}' is done, and no entry is active on this branch.`);
300
+ io.say(`Commit ${workflowFile(slug)} and the removal of ${ACTIVE}.`);
301
+ }
302
+ else {
303
+ io.say(`Now at ${next}: ${skillOf(next)}. Commit ${workflowFile(slug)}.`);
304
+ }
305
+ return io.result(0);
306
+ }
307
+ // What an entry lists under `amends` in its `index.md`: the documents and statements of done
308
+ // entries it changed, to keep their references into the math notes true.
309
+ function amendsOf(root, slug) {
310
+ const index = path.join(root, entryDir(slug), 'index.md');
311
+ if (!fs.existsSync(index))
312
+ return [];
313
+ return frontmatterList(fs.readFileSync(index, 'utf8'), 'amends') ?? [];
314
+ }
315
+ // What the entry `slug` may change in the others, for `refusal`.
316
+ function amendingOf(root, slug) {
317
+ return {
318
+ isDone: (other) => tryWorkflow(root, other)?.stage == 'done',
319
+ amends: slug ? amendsOf(root, slug) : [],
320
+ };
321
+ }
322
+ function tryWorkflow(root, slug) {
323
+ try {
324
+ return readWorkflow(root, slug);
325
+ }
326
+ catch {
327
+ return undefined;
328
+ }
329
+ }
330
+ // Writes each amendment into the amended entry's record: the document's new hash, which it is
331
+ // held to from now on, and an event that names the amending entry. The commit of the document's
332
+ // own approval stays, and is where its text before the amendment is found. Returns the entries
333
+ // amended.
334
+ function recordAmendments(root, slug, commit) {
335
+ const amended = new Map();
336
+ for (const key of amendsOf(root, slug)) {
337
+ const target = amendTarget(key);
338
+ const other = amended.get(target.slug) ?? readWorkflow(root, target.slug);
339
+ amended.set(target.slug, other);
340
+ const approval = target.stage && other.approvals[target.stage];
341
+ if (approval)
342
+ approval.hash = documentHash(root, amendPath(root, key), target.stage);
343
+ other.events.push({
344
+ date: today(),
345
+ action: 'amend',
346
+ ...(target.stage ? { stage: target.stage } : {}),
347
+ document: key,
348
+ by: slug,
349
+ commit,
350
+ });
351
+ }
352
+ for (const [other, workflow] of amended)
353
+ writeWorkflow(root, other, workflow);
354
+ return [...amended.keys()];
355
+ }
356
+ // What keeps a stage from being approved, beyond the locks.
357
+ function readiness(root, slug, workflow, stage, base) {
358
+ const problems = [];
359
+ const read = (rel) => fs.readFileSync(path.join(root, rel), 'utf8');
360
+ if (hasDocument(stage)) {
361
+ const doc = documentPath(root, slug, stage);
362
+ if (!fs.existsSync(path.join(root, doc)))
363
+ return [`${doc} does not exist.`];
364
+ const text = read(doc);
365
+ if (!isCommitted(root, doc))
366
+ problems.push(`${doc} has uncommitted changes.`);
367
+ if (!text.replace(/^---[\s\S]*?\n---/, '').trim())
368
+ problems.push(`${doc} is empty.`);
369
+ if (hasTodo(text))
370
+ problems.push(`${doc} still has a [!TODO]: open questions remain.`);
371
+ for (const section of stageConfig(stage).sections ?? []) {
372
+ if (!new RegExp(`^#{2,3} ${escape(section)}\\b`, 'm').test(text)) {
373
+ problems.push(`${doc} has no "## ${section}" section.`);
374
+ }
375
+ }
376
+ if (stageConfig(stage).checklist && checkboxes(text).total == 0) {
377
+ problems.push(`${doc} has no checklist (\`- [ ] ...\`).`);
378
+ }
379
+ }
380
+ if (stage == 'build') {
381
+ const lists = stagesOf(workflow.kind).filter((other) => stageConfig(other).checklist);
382
+ for (const list of lists) {
383
+ const file = documentPath(root, slug, list);
384
+ if (!fs.existsSync(path.join(root, file)))
385
+ continue;
386
+ const boxes = checkboxes(read(file));
387
+ if (boxes.open)
388
+ problems.push(`${file} has ${boxes.open} unticked items.`);
389
+ }
390
+ const dirty = uncommitted(root);
391
+ if (dirty)
392
+ problems.push(`the working tree has uncommitted changes:\n${dirty}`);
393
+ }
394
+ if (stage == 'publish') {
395
+ const index = `${entryDir(slug)}/index.md`;
396
+ const text = read(index);
397
+ if (hasTodo(text))
398
+ problems.push(`${index} still has a [!TODO].`);
399
+ if (!isCommitted(root, index))
400
+ problems.push(`${index} has uncommitted changes.`);
401
+ const listed = frontmatterList(text, 'pages') ?? [];
402
+ for (const key of listed) {
403
+ if (!pageExists(root, key))
404
+ problems.push(`${index} lists page '${key}', which does not exist.`);
405
+ }
406
+ const amends = amendsOf(root, slug);
407
+ for (const key of amends) {
408
+ const target = amendTarget(key);
409
+ const file = amendPath(root, key);
410
+ if (!target || !file || target.slug == slug) {
411
+ problems.push(`${index} lists '${key}' under \`amends\`, which names no document or statement of another entry.`);
412
+ }
413
+ else if (tryWorkflow(root, target.slug)?.stage != 'done') {
414
+ problems.push(`${index} amends '${key}', but '${target.slug}' is not a done entry.`);
415
+ }
416
+ else if (!fs.existsSync(path.join(root, file))) {
417
+ problems.push(`${index} amends '${key}', which does not exist.`);
418
+ }
419
+ else if (!isCommitted(root, file)) {
420
+ problems.push(`${file} has uncommitted changes.`);
421
+ }
422
+ }
423
+ const ref = base ?? defaultBase(root);
424
+ const changed = ref ? changedSince(root, ref) : undefined;
425
+ if (changed) {
426
+ // What it changed in other entries: only what it lists, and all of what it lists.
427
+ const amended = new Set();
428
+ for (const rel of changed) {
429
+ const place = placeOf(rel);
430
+ if (place.area != 'entry' || place.slug == slug)
431
+ continue;
432
+ const key = amendKey(rel);
433
+ if (!key) {
434
+ problems.push(`${rel} belongs to entry '${place.slug}', and is not a document or a statement an entry may amend.`);
435
+ }
436
+ else if (!amends.includes(key)) {
437
+ problems.push(`${rel} changed on this branch; list it as '${key}' under \`amends\` in ${index}.`);
438
+ }
439
+ else
440
+ amended.add(key);
441
+ }
442
+ for (const key of amends) {
443
+ if (!amended.has(key))
444
+ problems.push(`${index} amends '${key}', which this branch did not change.`);
445
+ }
446
+ const pages = new Set(changed.map(pageKey).filter((key) => key !== undefined));
447
+ for (const key of pages) {
448
+ if (!listed.includes(key) && pageExists(root, key)) {
449
+ problems.push(`page '${key}' changed on this branch; list it under \`pages\` in ${index}.`);
450
+ }
451
+ }
452
+ for (const key of listed) {
453
+ if (!pages.has(key))
454
+ problems.push(`${index} lists page '${key}', which this branch did not change.`);
455
+ }
456
+ const landingFile = `${CONTENT()}/${config().landing ?? 'landing'}`;
457
+ const landing = changed.some((rel) => rel == `${landingFile}.md` || rel == `${landingFile}.svx`);
458
+ const optional = config().pagesOptional ?? [];
459
+ if (!optional.includes(workflow.kind) && !pages.size && !landing) {
460
+ problems.push('no documentation page changed: say what this entry made true in the docs.');
461
+ }
462
+ }
463
+ }
464
+ // The project's own conditions for the stage.
465
+ const own = config().checks?.[stage];
466
+ if (own) {
467
+ const index = `${entryDir(slug)}/index.md`;
468
+ const text = fs.existsSync(path.join(root, index)) ? read(index) : '';
469
+ const ref = base ?? defaultBase(root);
470
+ problems.push(...own({
471
+ root,
472
+ slug,
473
+ index,
474
+ text,
475
+ changed: ref ? changedSince(root, ref) : undefined,
476
+ list: (field) => frontmatterList(text, field),
477
+ }));
478
+ }
479
+ return problems;
480
+ }
481
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
482
+ // What `git status` lists, indented to sit under a problem.
483
+ function uncommitted(root) {
484
+ return git(root, 'status', '--porcelain')
485
+ .split('\n')
486
+ .filter(Boolean)
487
+ .map((line) => ` ${line}`)
488
+ .join('\n');
489
+ }
490
+ // ---------------------------------------------------------------------------
491
+ // reopen, abandon, resume
492
+ function reopen(root, args, io) {
493
+ const { slug, workflow } = requireActive(root);
494
+ const current = stageOf(workflow);
495
+ const stage = args.positional[0];
496
+ const reason = flag(args, 'reason');
497
+ const stages = stagesOf(workflow.kind);
498
+ if (!stage || !reason)
499
+ throw new WorkflowError('usage: wf reopen <stage> --reason <text>');
500
+ if (!stages.includes(stage) || stages.indexOf(stage) >= stages.indexOf(current)) {
501
+ throw new WorkflowError(`'${stage}' is not a stage of this ${workflow.kind} before ${current}.`);
502
+ }
503
+ for (const earlier of stages.slice(stages.indexOf(stage), stages.indexOf(current))) {
504
+ const approval = workflow.approvals[earlier];
505
+ if (approval)
506
+ approval.stale = true;
507
+ }
508
+ workflow.stage = stage;
509
+ workflow.events.push({
510
+ date: today(),
511
+ action: 'reopen',
512
+ stage,
513
+ reason,
514
+ commit: headCommit(root),
515
+ });
516
+ writeWorkflow(root, slug, workflow);
517
+ io.say(`Reopened '${slug}' at ${stage}: ${reason}`);
518
+ if (hasDocument(stage)) {
519
+ io.say(`Revise ${documentPath(root, slug, stage)} with ${skillOf(stage)}, and say what changed ` +
520
+ 'and why under its "## Revisions" heading.');
521
+ }
522
+ io.say(`Every stage from ${stage} to ${current} is approved again on the way back.`);
523
+ return io.result(0);
524
+ }
525
+ function abandon(root, args, io) {
526
+ const { slug, workflow } = requireActive(root);
527
+ const stage = stageOf(workflow);
528
+ const reason = flag(args, 'reason');
529
+ if (!reason)
530
+ throw new WorkflowError('usage: wf abandon --reason <text>');
531
+ workflow.events.push({
532
+ date: today(),
533
+ action: 'abandon',
534
+ stage,
535
+ reason,
536
+ commit: headCommit(root),
537
+ });
538
+ workflow.stage = 'abandoned';
539
+ writeWorkflow(root, slug, workflow);
540
+ setActive(root, undefined);
541
+ io.say(`Set '${slug}' aside at ${stage}. Its documents stay in the archive; \`wf resume ${slug}\` takes it up again.`);
542
+ return io.result(0);
543
+ }
544
+ function resume(root, args, io) {
545
+ const [slug] = args.positional;
546
+ if (!slug)
547
+ throw new WorkflowError('usage: wf resume <slug>');
548
+ const active = activeSlug(root);
549
+ if (active)
550
+ throw new WorkflowError(`'${active}' is active on this branch.`);
551
+ const workflow = readWorkflow(root, slug);
552
+ if (workflow.stage != 'abandoned') {
553
+ throw new WorkflowError(`'${slug}' is ${workflow.stage}, not abandoned.`);
554
+ }
555
+ const left = workflow.events.findLast((event) => event.action == 'abandon')?.stage ??
556
+ stagesOf(workflow.kind)[0];
557
+ workflow.stage = left;
558
+ workflow.events.push({ date: today(), action: 'resume', stage: left });
559
+ writeWorkflow(root, slug, workflow);
560
+ setActive(root, slug);
561
+ io.say(`Took up '${slug}' again at ${left}: ${skillOf(left)}.`);
562
+ return io.result(0);
563
+ }
564
+ // ---------------------------------------------------------------------------
565
+ // check, guard
566
+ // Documents changed after they were approved, documents written before their
567
+ // stage, and drafts changed while the entry was reopened at an earlier stage.
568
+ function lockProblems(root, slug, workflow, amended = []) {
569
+ const problems = [];
570
+ const stages = stagesOf(workflow.kind);
571
+ const current = workflow.stage;
572
+ for (const stage of stages.filter(hasDocument)) {
573
+ const doc = documentPath(root, slug, stage);
574
+ const exists = fs.existsSync(path.join(root, doc));
575
+ const approval = workflow.approvals[stage];
576
+ if (stage == current)
577
+ continue;
578
+ if (approval?.hash) {
579
+ // A document the entry at publish amends is held to its new hash once that entry's
580
+ // publish is approved.
581
+ const amending = current == 'done' && amended.includes(`archive/${slug}/${stage}`);
582
+ if (!amending && documentHash(root, doc, stage) != approval.hash) {
583
+ problems.push(`${doc} changed after it was approved at ${approval.commit}; reopen ${stage} to change it.`);
584
+ }
585
+ }
586
+ else if (exists && current != 'done') {
587
+ // A draft the entry had reached before it was reopened waits, unchanged, for its
588
+ // stage to come round again.
589
+ const reopened = workflow.events.findLast((event) => event.action == 'reopen')?.commit;
590
+ const kept = reopened && tryGit(root, 'cat-file', '-e', `${reopened}:${doc}`) != undefined;
591
+ if (!kept) {
592
+ problems.push(`${doc} was written before its stage; '${slug}' is at ${current}.`);
593
+ }
594
+ else if (tryGit(root, 'diff', '--quiet', reopened, '--', doc) == undefined) {
595
+ problems.push(`${doc} changed after '${slug}' was reopened at ${reopened}; it waits for its stage.`);
596
+ }
597
+ }
598
+ if (current == 'done' && (!approval || approval.stale)) {
599
+ problems.push(`'${slug}' is done, but its ${stage} stage was never approved.`);
600
+ }
601
+ }
602
+ return problems;
603
+ }
604
+ // Whether `rel` was in the tree at `commit` and is unchanged since.
605
+ function keptSince(root, commit, rel) {
606
+ return (tryGit(root, 'cat-file', '-e', `${commit}:${rel}`) != undefined &&
607
+ tryGit(root, 'diff', '--quiet', commit, '--', rel) != undefined);
608
+ }
609
+ function check(root, args, io) {
610
+ const problems = [];
611
+ const active = activeSlug(root);
612
+ const workflows = new Map();
613
+ const publishing = active && tryWorkflow(root, active)?.stage == 'publish';
614
+ const amended = publishing ? amendsOf(root, active) : [];
615
+ for (const slug of listEntries(root)) {
616
+ try {
617
+ const workflow = readWorkflow(root, slug);
618
+ workflows.set(slug, workflow);
619
+ problems.push(...lockProblems(root, slug, workflow, amended));
620
+ }
621
+ catch (error) {
622
+ problems.push(error.message);
623
+ }
624
+ }
625
+ if (active) {
626
+ const workflow = workflows.get(active);
627
+ if (!workflow)
628
+ problems.push(`${ACTIVE} names '${active}', which is not an entry.`);
629
+ else if (workflow.stage == 'done' || workflow.stage == 'abandoned') {
630
+ problems.push(`${ACTIVE} names '${active}', which is ${workflow.stage}.`);
631
+ }
632
+ }
633
+ const base = flag(args, 'base') ?? defaultBase(root);
634
+ const changed = base ? changedSince(root, base) : undefined;
635
+ if (!changed) {
636
+ io.say(`Skipped the branch rules: no base to compare with${base ? ` ('${base}')` : ''}.`);
637
+ }
638
+ else {
639
+ const touched = [
640
+ ...new Set(changed
641
+ .map(placeOf)
642
+ .flatMap((place) => (place.area == 'entry' ? [place.slug] : []))),
643
+ ];
644
+ // The entry the branch works on: the active one, or else the one whose `amends` accounts
645
+ // for what the branch changed in the others.
646
+ const amendedBy = (other, by) => {
647
+ const amends = amendsOf(root, by);
648
+ return changed
649
+ .filter((rel) => {
650
+ const place = placeOf(rel);
651
+ return place.area == 'entry' && place.slug == other;
652
+ })
653
+ .every((rel) => amends.includes(amendKey(rel) ?? ''));
654
+ };
655
+ const slug = active ??
656
+ touched.find((by) => touched.every((other) => other == by || amendedBy(other, by))) ??
657
+ touched[0];
658
+ const own = touched.filter((other) => other == slug || !slug || !amendedBy(other, slug));
659
+ if (own.length > 1) {
660
+ problems.push(`this branch changes ${own.length} entries (${own.join(', ')}); one branch works on one.`);
661
+ }
662
+ const workflow = slug ? workflows.get(slug) : undefined;
663
+ const subject = slug && workflow ? { slug, workflow } : undefined;
664
+ const amending = amendingOf(root, slug);
665
+ // Code, math notes and pages written before a reopening wait, unchanged, for the stage
666
+ // that opens them to come round again, as a draft does.
667
+ const reopened = subject?.workflow.events.findLast((event) => event.action == 'reopen')?.commit;
668
+ for (const rel of changed) {
669
+ const why = refusal(rel, subject, false, amending);
670
+ if (!why)
671
+ continue;
672
+ if (reopened && placeOf(rel).area != 'entry' && keptSince(root, reopened, rel))
673
+ continue;
674
+ problems.push(why);
675
+ }
676
+ }
677
+ problems.push(...managedProblems(root));
678
+ if (args.flags.merge && active) {
679
+ const stage = workflows.get(active)?.stage;
680
+ problems.push(`'${active}' is still at ${stage}: finish it with \`/wf-approve\` or set it aside with ` +
681
+ '`/wf-abandon` before merging.');
682
+ }
683
+ if (problems.length) {
684
+ io.warn(`wf check found ${problems.length} problem${problems.length == 1 ? '' : 's'}:`);
685
+ for (const problem of problems)
686
+ io.warn(` - ${problem}`);
687
+ return io.result(1);
688
+ }
689
+ io.say(`wf check: ok${active ? ` ('${active}' at ${workflows.get(active)?.stage})` : ''}.`);
690
+ return io.result(0);
691
+ }
692
+ // Managed files changed since `mesearch-wf sync` wrote them: they are the package's, and a change
693
+ // to one is made upstream.
694
+ function managedProblems(root) {
695
+ const manifest = readManifest(root);
696
+ if (!manifest)
697
+ return [];
698
+ const problems = [];
699
+ for (const [rel, hash] of Object.entries(manifest.files)) {
700
+ const file = path.join(root, rel);
701
+ if (!fs.existsSync(file)) {
702
+ problems.push(`${rel} is managed by ${manifest.package}, and is missing; run \`mesearch-wf sync\`.`);
703
+ }
704
+ else if (contentHash(fs.readFileSync(file, 'utf8')) != hash) {
705
+ problems.push(`${rel} is managed by ${manifest.package} ${manifest.version}, and was changed here: ` +
706
+ `change it in ${manifest.package} instead, and run \`mesearch-wf sync\` to restore it.`);
707
+ }
708
+ }
709
+ return problems;
710
+ }
711
+ // A Claude Code PreToolUse hook. The tool call arrives on stdin as JSON; exit
712
+ // code 2 refuses it and shows stderr to the agent.
713
+ function guard(root, stdin, io) {
714
+ let input;
715
+ try {
716
+ input = JSON.parse(stdin || '{}');
717
+ }
718
+ catch {
719
+ return io.result(0);
720
+ }
721
+ const target = input.tool_input?.file_path ?? input.tool_input?.notebook_path;
722
+ if (typeof target != 'string')
723
+ return io.result(0);
724
+ const rel = path.relative(root, path.resolve(input.cwd ?? root, target));
725
+ if (rel.startsWith('..') || path.isAbsolute(rel))
726
+ return io.result(0);
727
+ let subject;
728
+ const slug = activeSlug(root);
729
+ if (slug) {
730
+ try {
731
+ subject = { slug, workflow: readWorkflow(root, slug) };
732
+ }
733
+ catch (error) {
734
+ io.warn(`wf guard: ${error.message}`);
735
+ return io.result(0);
736
+ }
737
+ }
738
+ const why = refusal(rel, subject, true, amendingOf(root, slug), readManifest(root));
739
+ if (!why)
740
+ return io.result(0);
741
+ io.warn(`wf: ${why}`);
742
+ return io.result(2);
743
+ }
744
+ //# sourceMappingURL=cli.js.map