@yairabf/engineering-workflows 0.0.0-stage → 1.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 (63) hide show
  1. package/.agents/skills/grill-me/SKILL.md +7 -0
  2. package/.agents/skills/grill-me/agents/openai.yaml +5 -0
  3. package/.agents/skills/grilling/SKILL.md +28 -0
  4. package/.agents/skills/grilling/agents/openai.yaml +3 -0
  5. package/engineering-workflows/.agents/skills/workflow-complete/SKILL.md +17 -0
  6. package/engineering-workflows/.agents/skills/workflow-implement/SKILL.md +17 -0
  7. package/engineering-workflows/.agents/skills/workflow-implement/references/implementation-handoff.md +17 -0
  8. package/engineering-workflows/.agents/skills/workflow-initiate/SKILL.md +49 -0
  9. package/engineering-workflows/.agents/skills/workflow-initiate/references/preparation.md +80 -0
  10. package/engineering-workflows/.agents/skills/workflow-initiate/references/prerequisites.json +53 -0
  11. package/engineering-workflows/.agents/skills/workflow-initiate/references/readiness.md +87 -0
  12. package/engineering-workflows/.agents/skills/workflow-initiate/scripts/marker.mjs +97 -0
  13. package/engineering-workflows/.agents/skills/workflow-investigate/SKILL.md +55 -0
  14. package/engineering-workflows/.agents/skills/workflow-investigate/references/investigation-brief.md +38 -0
  15. package/engineering-workflows/.agents/skills/workflow-plan/SKILL.md +46 -0
  16. package/engineering-workflows/.agents/skills/workflow-plan/references/implementation-plan.md +31 -0
  17. package/engineering-workflows/.agents/skills/workflow-pr/SKILL.md +20 -0
  18. package/engineering-workflows/.agents/skills/workflow-pr/scripts/check-pr.mjs +41 -0
  19. package/engineering-workflows/.agents/skills/workflow-review/SKILL.md +58 -0
  20. package/engineering-workflows/.agents/skills/workflow-review/references/independent-review.md +29 -0
  21. package/engineering-workflows/.claude/skills/workflow-complete/SKILL.md +6 -0
  22. package/engineering-workflows/.claude/skills/workflow-implement/SKILL.md +10 -0
  23. package/engineering-workflows/.claude/skills/workflow-initiate/SKILL.md +10 -0
  24. package/engineering-workflows/.claude/skills/workflow-investigate/SKILL.md +10 -0
  25. package/engineering-workflows/.claude/skills/workflow-plan/SKILL.md +10 -0
  26. package/engineering-workflows/.claude/skills/workflow-pr/SKILL.md +6 -0
  27. package/engineering-workflows/.claude/skills/workflow-review/SKILL.md +10 -0
  28. package/engineering-workflows/README.md +282 -0
  29. package/engineering-workflows/builder/delivery.mjs +177 -0
  30. package/engineering-workflows/builder/delivery.test.mjs +154 -0
  31. package/engineering-workflows/builder/drive.mjs +184 -0
  32. package/engineering-workflows/builder/drive.test.mjs +350 -0
  33. package/engineering-workflows/builder/handoff.mjs +40 -0
  34. package/engineering-workflows/builder/mission-role.mjs +294 -0
  35. package/engineering-workflows/builder/pi-session.mjs +45 -0
  36. package/engineering-workflows/builder/reader-guard.mjs +58 -0
  37. package/engineering-workflows/builder/role-session.mjs +42 -0
  38. package/engineering-workflows/builder/stage.mjs +446 -0
  39. package/engineering-workflows/builder/workspace-tool.mjs +20 -0
  40. package/engineering-workflows/builder-plan.mjs +174 -0
  41. package/engineering-workflows/builder-project.mjs +117 -0
  42. package/engineering-workflows/check-package-visibility.mjs +54 -0
  43. package/engineering-workflows/install.mjs +182 -0
  44. package/engineering-workflows/mission/README.md +281 -0
  45. package/engineering-workflows/mission/controller.mjs +54 -0
  46. package/engineering-workflows/mission/mission-controller.test.mjs +382 -0
  47. package/engineering-workflows/mission/mission-mcp.test.mjs +102 -0
  48. package/engineering-workflows/mission/status.mjs +113 -0
  49. package/engineering-workflows/mission/store.mjs +180 -0
  50. package/engineering-workflows/mission/tools.mjs +54 -0
  51. package/engineering-workflows/mission/transitions.mjs +269 -0
  52. package/engineering-workflows/mission-controller.mjs +72 -0
  53. package/engineering-workflows/mission-mcp.mjs +66 -0
  54. package/engineering-workflows/prerequisites.mjs +205 -0
  55. package/engineering-workflows/readiness.mjs +265 -0
  56. package/engineering-workflows/release-targets.mjs +12 -0
  57. package/engineering-workflows/setup.mjs +70 -0
  58. package/engineering-workflows/stage-release.mjs +43 -0
  59. package/engineering-workflows/upgrade.mjs +333 -0
  60. package/engineering-workflows/workflows/development.md +374 -0
  61. package/engineering-workflows/workflows/engineering-workflows.yml +90 -0
  62. package/package.json +21 -4
  63. package/README.md +0 -3
@@ -0,0 +1,54 @@
1
+ import { ticketIdentity } from '../builder-project.mjs'
2
+ import { digest, InputError, requireInput } from './store.mjs'
3
+ import { approve, issueUrl, record } from './transitions.mjs'
4
+
5
+ export function identity(repository, number) {
6
+ try {
7
+ return ticketIdentity(repository, number)
8
+ } catch (error) {
9
+ throw new InputError(error.message, 'invalid_input')
10
+ }
11
+ }
12
+
13
+ function submit(store, key, text) {
14
+ const file = store.saveArtifact('mission', '# Mission\n\n' + issueUrl(key) + '\n\n' + text)
15
+ return {
16
+ ...key, file, stage: 'preparation', notes: [], plans: [], candidates: [],
17
+ delivery: [], failedRepairs: 0, round: 0,
18
+ }
19
+ }
20
+
21
+ export function changeMission(store, command, payload, previous) {
22
+ requireInput(Number.isSafeInteger(previous) && previous >= 0 && previous < Number.MAX_SAFE_INTEGER,
23
+ 'Expected a valid revision in --at.', 'invalid_input')
24
+ const revisions = store.revisions()
25
+ const latest = revisions[0] ?? 0
26
+ const request = digest(JSON.stringify([command, ...payload]))
27
+ if (revisions.includes(previous + 1) && store.read(previous + 1).request === request) {
28
+ return { revision: previous + 1, replay: true }
29
+ }
30
+
31
+ requireInput(previous === latest, 'State advanced. Run status before trying again.', 'stale_revision')
32
+ let mission = latest ? store.read(latest).mission : null
33
+ if (command === 'submit') {
34
+ requireInput(!mission || mission.stage === 'delivered', 'A mission is already active. Run status to resume it.', 'active_mission')
35
+ mission = submit(store, ...payload)
36
+ } else {
37
+ requireInput(mission, 'No saved mission. Use submit first.')
38
+ if (command === 'record') record(mission, ...payload, store)
39
+ else approve(mission, payload[0], store)
40
+ }
41
+ if (store.save(latest + 1, request, mission)) return { revision: latest + 1, replay: false }
42
+ if (store.read(latest + 1).request === request) return { revision: latest + 1, replay: true }
43
+ throw new InputError('State advanced. Run status before trying again.', 'stale_revision')
44
+ }
45
+
46
+ export function findMission(store, key) {
47
+ const revisions = store.revisions()
48
+ for (const revision of revisions) {
49
+ const saved = store.read(revision)
50
+ if (!key || (saved.mission.repository === key.repository && saved.mission.number === key.number))
51
+ return { saved, current: revision === revisions[0] }
52
+ }
53
+ throw new InputError('No saved mission matches this request. Check --state and the ticket identity.', 'missing_mission')
54
+ }
@@ -0,0 +1,382 @@
1
+ import { callTool, tools } from './tools.mjs'
2
+ import assert from 'node:assert/strict'
3
+ import { spawn, spawnSync } from 'node:child_process'
4
+ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import test from 'node:test'
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ const cli = fileURLToPath(new URL('../mission-controller.mjs', import.meta.url))
11
+ const issue = 'https://github.com/example/demo/issues/7'
12
+ const commits = 'abcde'.split('').map((char) => char.repeat(40))
13
+
14
+ function fixture(t) {
15
+ const dir = mkdtempSync(join(tmpdir(), 'ew-mission-'))
16
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
17
+ const state = join(dir, 'mission-state')
18
+ const target = join(dir, 'checkout')
19
+ const worktree = join(dir, 'worktree')
20
+ mkdirSync(target)
21
+ mkdirSync(worktree)
22
+ let revision = 0
23
+ let index = 0
24
+ function file(text) {
25
+ const path = join(dir, 'input-' + ++index + '.md')
26
+ writeFileSync(path, issue + '\n\n' + text + '\n')
27
+ return path
28
+ }
29
+ function raw(args, options = []) {
30
+ return spawnSync(process.execPath, [...options, cli, '--state', state, ...args], { encoding: 'utf8' })
31
+ }
32
+ function accept(args, stage) {
33
+ const result = raw(['--at', String(revision), ...args])
34
+ assert.equal(result.status, 0, result.stderr)
35
+ assert.ok(result.stdout.includes(' · ' + stage + ' · revision ' + ++revision), result.stdout)
36
+ return result.stdout
37
+ }
38
+ function record(kind, input, stage) {
39
+ return accept(['record', kind, file(input)], stage)
40
+ }
41
+ function reject(kind, input, expected) {
42
+ const result = raw(['--at', String(revision), 'record', kind, file(input)])
43
+ assert.equal(result.status, 1)
44
+ assert.match(result.stderr, expected)
45
+ }
46
+ const setup = '# Readiness\n\n**Checkout:** ' + target + '\n**Base branch:** main\n\n## Readiness\n\nInitiate verified.'
47
+ const mission = file('Goal: Show a fixture option in help.\n\nAcceptance: Help lists the option.')
48
+ const submit = ['submit', 'example/demo', '7', mission]
49
+ function saved(prefix) {
50
+ return readdirSync(state).find((name) => name.startsWith(prefix + '-') && name.endsWith('.md'))
51
+ }
52
+ return { dir, state, target, worktree, raw, accept, record, reject, setup, submit, saved, file, get revision() { return revision } }
53
+ }
54
+
55
+ function prepare(f) {
56
+ f.accept(f.submit, 'preparation')
57
+ f.record('ready', f.setup, 'investigation')
58
+ f.record('brief', '# Investigation brief\n\n## Mission\n\nCLI help.\n\n## Repository context\n\nmain.\n\n## Verified findings\n\nThe help omits the option.', 'planning')
59
+ f.record('clarification', '# Clarification\n\nHelp must list the option value.', 'planning')
60
+ return [
61
+ '# Implementation plan',
62
+ '## Mission and evidence\n\nUse ' + f.saved('brief') + '.',
63
+ '## Planned changes\n\nUpdate help.',
64
+ '## Acceptance criteria\n\nHelp lists the option.',
65
+ '## Verification\n\nRun the CLI help command.',
66
+ '## Human approval\n\n**Decision:** Pending',
67
+ ].join('\n\n')
68
+ }
69
+
70
+ function filename(output, label) {
71
+ const match = output.match(new RegExp('^' + label + ': (.+)$', 'm'))
72
+ assert.ok(match, output)
73
+ return match[1].split('/').at(-1)
74
+ }
75
+
76
+ function implementation(f, revision, commit, repairDetails = '') {
77
+ return [
78
+ '# Implementation handoff',
79
+ '**Approved plan** — ' + revision,
80
+ '**Target:** example/demo',
81
+ '**Branch:** feature/help',
82
+ '**Worktree:** ' + f.worktree,
83
+ '**Candidate commit** — ' + commit,
84
+ '## Tasks\n\nPrivate developer notes.',
85
+ repairDetails,
86
+ '## Verification\n\nnode cli.mjs --help returned the option.',
87
+ ].join('\n\n')
88
+ }
89
+
90
+ function review(revision, commit, outcome, details = '') {
91
+ return [
92
+ '# Independent review',
93
+ '**Mission and approved plan** — ' + revision,
94
+ '**Target and base:** example/demo',
95
+ '**Base branch:** main',
96
+ '**Base commit:** ' + commits[4],
97
+ '**Candidate** — ' + commit,
98
+ '**Verdict** — ' + outcome,
99
+ details,
100
+ '## Acceptance criteria\n\nObserved the exact candidate.',
101
+ '## Thermo review and required changes\n\nFindings are in the verdict.',
102
+ ].join('\n\n')
103
+ }
104
+
105
+ function deliver(commit, ci, advisory) {
106
+ return [
107
+ '# GitHub delivery',
108
+ '**PR:** https://github.com/example/demo/pull/8',
109
+ '**Head:** ' + commit,
110
+ '**CI:** ' + ci,
111
+ '**Advisory review:** ' + advisory,
112
+ '## Evidence\n\nFixture check results.',
113
+ ].join('\n\n')
114
+ }
115
+
116
+ test('recovers the same mission, rejects competing creation, and ignores an interrupted transition', async (t) => {
117
+ const f = fixture(t)
118
+ const run = (args) => new Promise((resolve, reject) => {
119
+ const child = spawn(process.execPath, [cli, '--state', f.state, ...args], { stdio: 'ignore' })
120
+ child.on('error', reject)
121
+ child.on('close', resolve)
122
+ })
123
+ const second = ['submit', 'example/other', '7', f.file('Goal: other mission.')]
124
+ const winners = await Promise.all([run(f.submit), run(second)])
125
+ assert.deepEqual(winners.toSorted(), [0, 1])
126
+ const firstMission = winners[0] === 0 ? f.submit : second
127
+ const first = f.raw(['status', firstMission[1], '7'])
128
+ assert.match(first.stdout, /preparation · revision 1/)
129
+ const replay = f.raw(firstMission)
130
+ assert.equal(replay.status, 0, replay.stderr)
131
+ assert.match(replay.stdout, /Already accepted at revision 1/)
132
+ assert.match(f.raw(['status']).stdout, /preparation · revision 1/)
133
+ assert.equal(f.raw(['--at', '1', ...second]).status, 1)
134
+
135
+ const hook = join(f.dir, 'interrupt.mjs')
136
+ writeFileSync(hook, `
137
+ import fs from 'node:fs'
138
+ import { syncBuiltinESMExports } from 'node:module'
139
+ const link = fs.linkSync
140
+ fs.linkSync = (source, destination) => {
141
+ if (destination.endsWith('/mission-2.json')) process.exit(79)
142
+ return link(source, destination)
143
+ }
144
+ syncBuiltinESMExports()
145
+ `)
146
+ const ready = f.setup.replace('Initiate verified.',
147
+ 'Initiate verified for https://github.com/' + firstMission[1] + '/issues/7.')
148
+ const args = ['--at', '1', 'record', 'ready', f.file(ready)]
149
+ assert.equal(f.raw(args, ['--import', hook]).status, 79)
150
+ assert.match(f.raw(['status']).stdout, /preparation · revision 1/)
151
+ assert.match(f.raw(args).stdout, /investigation · revision 2/)
152
+ assert.match(f.raw(args).stdout, /Already accepted at revision 2/)
153
+ writeFileSync(join(f.state, 'mission-2.json'), '{broken')
154
+ assert.match(f.raw(['status']).stderr, /Invalid mission state at revision 2/)
155
+ })
156
+
157
+ test('requires approval of the current revision and fresh review when the PR head changes', (t) => {
158
+ const f = fixture(t)
159
+ const statusTool = tools.find(tool => tool.name === 'mission_status')
160
+ const status = (args = {}) => callTool(f.state, statusTool, args)
161
+ const plan = prepare(f)
162
+ const draft = filename(f.record('plan', plan, 'approval'), 'Pending plan')
163
+ assert.equal(status().pendingPlan, readFileSync(join(f.state, draft), 'utf8'))
164
+ f.record('plan-feedback', 'Clarify the example.', 'planning')
165
+ const restoredPlanning = f.raw(['status']).stdout
166
+ assert.equal(filename(restoredPlanning, 'Plan draft to revise'), draft)
167
+ assert.match(restoredPlanning, /Plan feedback:/)
168
+ assert.match(restoredPlanning, /Investigation brief:/)
169
+ assert.equal(filename(f.record('plan', plan, 'approval'), 'Pending plan'), draft)
170
+ f.record('plan-feedback', 'Revise the example now.', 'planning')
171
+ const pending = filename(f.record('plan', plan.replace('Update help.', 'Update help and clarify it.'), 'approval'), 'Pending plan')
172
+ f.reject('candidate', implementation(f, pending, commits[0]), /during approval/)
173
+ f.accept(['approve', pending], 'implementation')
174
+ const firstApproval = f.saved('approved-plan')
175
+ const revised = filename(f.record('plan', plan.replace('Update help.', 'Update help and its example.'), 'approval'), 'Pending plan')
176
+ assert.match(f.raw(['--at', String(f.revision), 'approve', pending]).stderr, /current pending plan/)
177
+ assert.equal(status().pendingPlan, readFileSync(join(f.state, revised), 'utf8'))
178
+ const approved = filename(f.accept(['approve', revised], 'implementation'), 'Approved plan')
179
+ assert.equal(status().pendingPlan, null)
180
+ assert.notEqual(approved, firstApproval)
181
+ assert.match(readFileSync(join(f.state, approved), 'utf8'), /\*\*Decision:\*\* Approved/)
182
+ assert.match(f.raw(['status']).stdout, new RegExp(approved))
183
+ f.reject('candidate', implementation(f, firstApproval, commits[0]), /current approved plan/)
184
+ const ambiguous = firstApproval + ' (also ' + approved + ')'
185
+ f.reject('candidate', implementation(f, ambiguous, commits[0]), /exactly one approved plan/)
186
+ for (const base of ['main', 'refs/heads/main']) {
187
+ f.reject('candidate', implementation(f, approved, commits[0]).replace('**Branch:** feature/help', '**Branch:** ' + base), /dedicated branch/)
188
+ }
189
+ const alias = join(f.dir, 'checkout-alias')
190
+ symlinkSync(f.target, alias, 'dir')
191
+ for (const checkout of [f.target, f.target + '/.', alias]) {
192
+ f.reject('candidate', implementation(f, approved, commits[0]).replace(f.worktree, checkout), /dedicated implementation worktree/)
193
+ }
194
+ const input = f.record('candidate', implementation(f, approved, commits[0]), 'review')
195
+ const evidence = filename(input, 'Test evidence')
196
+ assert.doesNotMatch(readFileSync(join(f.state, evidence), 'utf8'), /Private developer notes/)
197
+ f.reject('review', review(approved, commits[1], 'Pass — fixture passed'), /exact current candidate SHA/)
198
+ f.reject('review', review(ambiguous, commits[0], 'Pass — fixture passed'), /exactly one approved plan/)
199
+ f.record('review', review(approved, commits[0], 'Pass — fixture passed'), 'delivery')
200
+ f.record('delivery', deliver(commits[0], 'Failed', 'Pending'), 'delivery')
201
+ f.record('delivery', deliver(commits[1], 'Passed', 'Resolved'), 'delivery-head-changed')
202
+ f.reject('delivery', deliver(commits[0], 'Passed', 'Resolved'), /during delivery-head-changed/)
203
+ f.reject('candidate', implementation(f, approved, commits[2]), /newly reported PR head/)
204
+ f.record('head-changed', deliver(commits[0], 'Passed', 'Resolved'), 'delivery-head-changed')
205
+ f.reject('candidate', implementation(f, approved, commits[1]), /newly reported PR head/)
206
+ const returned = f.record('candidate', implementation(f, approved, commits[0]), 'review')
207
+ assert.doesNotMatch(returned, /Review \(Pass\)/)
208
+ f.record('review', review(approved, commits[0], 'Pass — reviewed the returned head'), 'delivery')
209
+ f.record('head-changed', deliver(commits[1], 'Pending', 'Pending'), 'delivery-head-changed')
210
+ f.record('head-changed', deliver(commits[2], 'Pending', 'Pending'), 'delivery-head-changed')
211
+ f.reject('candidate', implementation(f, approved, commits[1]), /newly reported PR head/)
212
+ f.record('candidate', implementation(f, approved, commits[2]), 'review')
213
+ f.record('review', review(approved, commits[2], 'Pass — reviewed the new head'), 'delivery')
214
+ f.reject('delivery', deliver(commits[0], 'Passed', 'Resolved'), /superseded candidate SHA/)
215
+ f.record('delivery', deliver(commits[2], 'Passed', 'Resolved'), 'delivered')
216
+ assert.match(f.raw(['status']).stdout, /CI: Passed · Advisory review: Resolved/)
217
+ f.record('head-changed', deliver(commits[0], 'Passed', 'Resolved'), 'delivery-head-changed')
218
+ f.reject('delivery', deliver(commits[0], 'Passed', 'Resolved'), /during delivery-head-changed/)
219
+ f.record('candidate', implementation(f, approved, commits[0]), 'review')
220
+ f.record('head-changed', deliver(commits[1], 'Pending', 'Pending'), 'delivery-head-changed')
221
+ f.record('candidate', implementation(f, approved, commits[1]), 'review')
222
+ const blocked = f.record('review', review(approved, commits[1], 'Blocked — need verification'), 'review-blocked')
223
+ assert.match(blocked, /Unsuccessful repairs: 0/)
224
+ f.record('head-changed', deliver(commits[0], 'Pending', 'Pending'), 'delivery-head-changed')
225
+ f.reject('review', review(approved, commits[1], 'Pass — superseded head'), /during delivery-head-changed/)
226
+ const freshReview = f.record('candidate', implementation(f, approved, commits[0]), 'review')
227
+ assert.doesNotMatch(freshReview, /Review \(Pass\)/)
228
+ assert.match(freshReview, /Unsuccessful repairs: 0/)
229
+ const freshDelivery = f.record('review', review(approved, commits[0], 'Pass — reviewed the returning head'), 'delivery')
230
+ assert.doesNotMatch(freshDelivery, /CI: Passed/)
231
+ f.record('delivery', deliver(commits[0], 'Passed', 'Resolved'), 'delivered')
232
+ const delivered = status()
233
+ assert.equal(delivered.prUrl, 'https://github.com/example/demo/pull/8')
234
+ f.accept(['submit', 'example/new', '7', f.file('New goal.')], 'preparation')
235
+ const historical = status({ repository: 'example/demo', issue: 7 })
236
+ assert.deepEqual(historical, { ...delivered, nextAction: 'Historical record. Run status for the current mission.' })
237
+ assert.match(f.raw(['status', 'example/demo', '7']).stdout, /Historical record/)
238
+ })
239
+
240
+ test('preserves blocked reviews and counts only completed unsuccessful repairs', (t) => {
241
+ const f = fixture(t)
242
+ const pending = filename(f.record('plan', prepare(f), 'approval'), 'Pending plan')
243
+ const approved = filename(f.accept(['approve', pending], 'implementation'), 'Approved plan')
244
+ f.record('candidate', implementation(f, approved, commits[0]), 'review')
245
+ let output = f.record('review', review(approved, commits[0], 'Changes requested — add an example'), 'repair')
246
+ assert.match(output, /Unsuccessful repairs: 0/)
247
+ for (const round of [1, 2]) {
248
+ const requested = filename(output, 'Outstanding findings')
249
+ const repair = f.record('repair', implementation(f, approved, commits[round],
250
+ '## Repair details\n\nFollowing ' + requested + ' for ' + commits[round - 1] + '.'), 'review')
251
+ const repairReference = filename(repair, 'Repair handoff reference')
252
+ const details = '## Repair review\n\nReviewed ' + repairReference + ' for ' + requested + '.'
253
+ if (round === 1) {
254
+ const blockedReport = review(approved, commits[round], 'Blocked — need help output', details)
255
+ const blocked = f.record('review', blockedReport, 'review-blocked')
256
+ assert.match(blocked, /Unsuccessful repairs: 0/)
257
+ f.record('evidence', '**Candidate:** ' + commits[round] + '\n\nPartial help output attached.', 'review')
258
+ const stillBlocked = f.record('review', blockedReport, 'review-blocked')
259
+ assert.match(stillBlocked, /Unsuccessful repairs: 0/)
260
+ f.record('evidence', '**Candidate:** ' + commits[round] + '\n\nHelp output attached.', 'review')
261
+ assert.equal((f.raw(['status']).stdout.match(/Review \(Blocked\)/g) ?? []).length, 2)
262
+ }
263
+ const body = f.file(review(approved, commits[round], 'Changes requested — example still missing', details))
264
+ const at = String(f.revision)
265
+ output = f.accept(['record', 'review', body], round === 1 ? 'repair' : 'repair-paused')
266
+ assert.match(output, new RegExp('Unsuccessful repairs: ' + round))
267
+ assert.match(f.raw(['--at', at, 'record', 'review', body]).stdout, /Already accepted/)
268
+ }
269
+ assert.match(output, new RegExp('Repair 1 candidate: ' + commits[1]))
270
+ assert.match(output, new RegExp('Repair 2 candidate: ' + commits[2]))
271
+ assert.match(output, /Outstanding findings/)
272
+ f.reject('repair', implementation(f, approved, commits[3]), /during repair-paused/)
273
+ f.record('continue', 'Operator authorizes one more repair.', 'repair')
274
+ })
275
+
276
+ test('resumes investigation only with an answer to its saved question', t => {
277
+ const f = fixture(t)
278
+ f.accept(f.submit, 'preparation')
279
+ f.record('ready', f.setup, 'investigation')
280
+ f.record('investigation-question', '## Findings\nNo application code.\n## Question\nWhich cloud?\n## Why it matters\nThe deployment target changes the plan.', 'investigation-waiting')
281
+ f.reject('brief', 'premature brief', /during investigation-waiting/)
282
+ const question = f.saved('investigation-question')
283
+ f.reject('investigation-answer', '## Answer\nAzure', /current investigation question/)
284
+ const status = f.record('investigation-answer', question + '\n## Answer\nAzure', 'investigation')
285
+ assert.ok(status.includes('Operator answer:'))
286
+ })
287
+
288
+ test('planner questions survive restart and resume with the linked operator answer', async t => {
289
+ const {validatedKind} = await import('../builder/drive.mjs')
290
+ const {roleInputs} = await import('../builder/mission-role.mjs')
291
+ const {openStore} = await import('./store.mjs')
292
+ const f = fixture(t)
293
+ const plan = prepare(f)
294
+ const question = '## Question\nShould help show examples?\n## Why it matters\nThis changes scope.'
295
+ const kind = validatedKind({kind:'plan'}, null, issue+'\n'+question, issue)
296
+ const status = f.record(kind, question, 'planning-waiting')
297
+ const name = filename(status, 'Planner question')
298
+ assert.match(f.raw(['status']).stdout, /planning-waiting/)
299
+ f.reject('plan', plan, /during planning-waiting/)
300
+ f.reject('clarification', '## Answer\nInclude examples.', /current planning question/)
301
+ f.record('clarification', name+'\r\n## Answer\r\nInclude examples.', 'planning')
302
+ const store = openStore(f.state, process.cwd(), false)
303
+ const inputs = roleInputs(store.read(f.revision).mission,store)
304
+ assert.ok(inputs.includes('Should help show examples?') && inputs.includes('Include examples.'))
305
+ f.record('plan', plan, 'approval')
306
+ })
307
+
308
+ test('builder records identical CI evidence after fresh review and deduplicates later refreshes', async t => {
309
+ const { deliver: builderDelivery } = await import('../builder/mission-role.mjs')
310
+ const f = fixture(t)
311
+ const pending = filename(f.record('plan', prepare(f), 'approval'), 'Pending plan')
312
+ const approved = filename(f.accept(['approve', pending], 'implementation'), 'Approved plan')
313
+ f.record('candidate', implementation(f, approved, commits[0]), 'review')
314
+ f.record('review', review(approved, commits[0], 'Pass — verified'), 'delivery')
315
+ const evidence = deliver(commits[1], 'Passed', 'Resolved')
316
+ f.record('head-changed', evidence, 'delivery-head-changed')
317
+ f.record('candidate', implementation(f, approved, commits[1]), 'review')
318
+ f.record('review', review(approved, commits[1], 'Pass — verified again'), 'delivery')
319
+ const publish = () => ({ kind: 'delivery', document: readFileSync(join(f.state, f.saved('delivery')), 'utf8') })
320
+ const refresh = revision => builderDelivery(f.dir, {repository:'example/demo', number:7}, {revision}, publish)
321
+ const status = refresh(f.revision)
322
+ assert.match(status, /PR: https:\/\/github.com\/example\/demo\/pull\/8/)
323
+ assert.match(status, /CI: Passed · Advisory review: Resolved/)
324
+ assert.match(status, /Next: .*merge/i)
325
+ assert.equal(refresh(f.revision + 1), status)
326
+ })
327
+
328
+ test('resuming an approved empty repository revisits investigation and approval on its initial commit', async t => {
329
+ const { execFileSync } = await import('node:child_process')
330
+ const { missionPacket } = await import('../builder/mission-role.mjs')
331
+ const { openStore } = await import('./store.mjs')
332
+ const f = fixture(t)
333
+ const key = { repository: 'example/demo', number: 7 }
334
+ const git = (...args) => execFileSync('git', args, { cwd: f.target, encoding: 'utf8' }).trim()
335
+ git('init', '-qb', 'main')
336
+ f.setup += '\n**Starting commit:** unborn'
337
+ const pending = filename(f.record('plan', prepare(f), 'approval'), 'Pending plan')
338
+ f.accept(['approve', pending], 'implementation')
339
+ const packet = () => missionPacket(f.dir, key)
340
+ assert.throws(packet, /Initialize and publish branch main/)
341
+ git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '--allow-empty', '-qm', 'Initialize')
342
+ const head = git('rev-parse', 'HEAD')
343
+ const next = packet()
344
+ assert.equal(next.stage, 'investigation')
345
+ assert.equal(next.base, head)
346
+ assert.equal(next.revision, f.revision + 1)
347
+ assert.equal(packet().revision, next.revision)
348
+ assert.equal(execFileSync('git', ['-C', next.workspace, 'rev-parse', 'HEAD'], {encoding:'utf8'}).trim(), head)
349
+ const store = openStore(f.state, process.cwd(), false)
350
+ const { mission } = store.read(next.revision)
351
+ assert.deepEqual(mission.plans, [])
352
+ assert.equal(mission.brief, undefined)
353
+ assert.ok(next.prompt.includes('Help must list the option value.'))
354
+ assert.equal(f.raw(['approve', pending, '--at', String(next.revision)]).status, 1)
355
+ assert.ok(store.read(f.revision).mission.plans[0].approved)
356
+ const original = store.read(f.revision).mission
357
+ const oldBrief = readFileSync(store.artifact(original.brief), 'utf8')
358
+ const oldPlan = readFileSync(store.artifact(pending), 'utf8')
359
+ const submitAt = (revision, ...args) => {
360
+ const result = f.raw(['--at', String(revision), ...args])
361
+ assert.equal(result.status, 0, result.stderr)
362
+ return result.stdout
363
+ }
364
+ submitAt(next.revision, 'record', 'brief', f.file(oldBrief + '\nInspected ' + head))
365
+ const newBrief = store.read(next.revision + 1).mission.brief
366
+ const awaiting = submitAt(next.revision + 1, 'record', 'plan', f.file(oldPlan.replace(original.brief, newBrief)))
367
+ const newPlan = filename(awaiting, 'Pending plan')
368
+ assert.notEqual(newPlan, pending)
369
+ assert.match(submitAt(next.revision + 2, 'approve', newPlan), / · implementation · /)
370
+ })
371
+
372
+ test('inline submission and CLI retry share the original revision', async t => {
373
+ const { changeMission, identity } = await import('./controller.mjs')
374
+ const { normalizeMarkdown, openStore } = await import('./store.mjs')
375
+ const f = fixture(t)
376
+ const store = openStore(f.state, fileURLToPath(new URL('../../', import.meta.url)), true)
377
+ const text = readFileSync(f.submit[3], 'utf8').replaceAll('\n', '\r\n')
378
+ const result = changeMission(store, 'submit', [identity('Example/Demo', 7), normalizeMarkdown(text)], 0)
379
+ assert.equal(result.revision, 1)
380
+ assert.match(f.raw(f.submit).stdout, /Already accepted at revision 1/)
381
+ assert.deepEqual(store.revisions(), [1])
382
+ })
@@ -0,0 +1,102 @@
1
+ import assert from 'node:assert/strict'
2
+ import { execFile, execFileSync } from 'node:child_process'
3
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+ import test from 'node:test'
8
+
9
+ const script = name => fileURLToPath(new URL('../' + name, import.meta.url))
10
+ const ticket = { repository: 'example/demo', issue: 7 }
11
+ const submission = { ...ticket, markdown: 'Inspect the fixture command.\r\nPreserve this instruction.' }
12
+ const request = (method, params, id) => ({ jsonrpc: '2.0', method, params, id })
13
+ const call = (name, args) => request('tools/call', { name, arguments: args }, 3)
14
+ const initialize = request('initialize', { protocolVersion: '2025-06-18', capabilities: {},
15
+ clientInfo: { name: 'fixture', version: '1' } }, 1)
16
+
17
+ function fixture(t) {
18
+ const root = mkdtempSync(join(tmpdir(), 'ew-mcp-'))
19
+ t.after(() => rmSync(root, { recursive: true, force: true }))
20
+ const state = join(root, 'mission-state')
21
+ function session(...requests) {
22
+ const lines = [initialize, request('notifications/initialized'), ...requests].map(msg => JSON.stringify(msg))
23
+ return new Promise((resolve, reject) => {
24
+ const child = execFile(process.execPath, [script('mission-mcp.mjs'), '--state', state], (err, stdout) => {
25
+ if (err) return reject(err)
26
+ try {
27
+ const replies = stdout.trim().split('\n').map(line => JSON.parse(line))
28
+ assert.deepEqual(replies.shift().result.capabilities, { tools: {} })
29
+ resolve(replies)
30
+ } catch (cause) { reject(cause) }
31
+ })
32
+ child.stdin.end(lines.join('\n') + '\n')
33
+ })
34
+ }
35
+ async function tool(name, args) {
36
+ const [reply] = await session(call(name, args))
37
+ assert.deepEqual(JSON.parse(reply.result.content[0].text), reply.result.structuredContent)
38
+ return reply.result
39
+ }
40
+ return { root, state, session, tool }
41
+ }
42
+
43
+ test('discovers both tools and classifies protocol, input and store errors', async t => {
44
+ const f = fixture(t)
45
+ const [list, unknown] = await f.session(request('tools/list', {}, 2), call('approve', {}))
46
+ assert.deepEqual(list.result.tools.map(t => t.name), ['submit_mission', 'mission_status'])
47
+ assert.equal(unknown.error.code, -32602)
48
+ const malformed = await f.session(request('tools/list', { cursor: 7 }, 4),
49
+ call('mission_status', []), call('mission_status', null), call(7, {}))
50
+ assert.equal(malformed.length, 4)
51
+ for (const reply of malformed) assert.equal(reply.error.code, -32602)
52
+ for (const args of [{ issue: 7 }, { repository: 'a/b' }, { state: '/private/path' }]) {
53
+ assert.equal((await f.tool('mission_status', args)).structuredContent.code, 'invalid_input')
54
+ }
55
+ assert.equal((await f.tool('mission_status', {})).structuredContent.code, 'missing_mission')
56
+ assert.equal(existsSync(f.state), false)
57
+ for (const markdown of [' ', '\ud800', null]) {
58
+ assert.equal((await f.tool('submit_mission', { ...submission, markdown })).structuredContent.code, 'invalid_input')
59
+ }
60
+ writeFileSync(f.state, 'private fixture')
61
+ const failed = await f.tool('mission_status', {})
62
+ assert.equal(failed.isError, true)
63
+ assert.equal(failed.structuredContent.code, 'internal_failure')
64
+ assert.ok(!JSON.stringify(failed).includes(f.root))
65
+ })
66
+
67
+ test('concurrent client processes accept one distinct submission, replay after restart, and block another mission', async t => {
68
+ const f = fixture(t)
69
+ const requests = [submission, { ...submission, issue: 8 }]
70
+ const replies = await Promise.all(requests.map(args => f.tool('submit_mission', args)))
71
+ assert.deepEqual(replies.map(r => r.structuredContent.code ?? 'accepted').sort(), ['accepted', 'stale_revision'])
72
+ const winner = requests[replies.findIndex(r => !r.isError)]
73
+ assert.deepEqual((await f.tool('submit_mission', winner)).structuredContent, { revision: 1 })
74
+ assert.equal((await f.tool('submit_mission', { ...winner, expectedRevision: 1 })).structuredContent.code, 'active_mission')
75
+ assert.equal((await f.tool('mission_status', { ...ticket, issue: 9 })).structuredContent.code, 'missing_mission')
76
+ const status = (await f.tool('mission_status', {})).structuredContent
77
+ assert.equal(status.stage, 'preparation')
78
+ assert.equal(status.revision, 1)
79
+ assert.equal(status.issue, winner.issue)
80
+ const output = execFileSync(process.execPath, [script('mission-controller.mjs'), '--state', f.state, 'status'], { encoding: 'utf8' })
81
+ assert.match(output, /preparation · revision 1/)
82
+ })
83
+
84
+ test('separate builder run moves an MCP submission from preparation into the investigator packet', async t => {
85
+ const f = fixture(t)
86
+ assert.deepEqual((await f.tool('submit_mission', submission)).structuredContent, { revision: 1 })
87
+ const stage = (op, payload) => execFileSync(process.execPath,
88
+ [script('builder/stage.mjs'), op, f.root, ticket.repository, String(ticket.issue)],
89
+ { encoding: 'utf8', input: payload && JSON.stringify(payload) })
90
+ assert.equal(stage('resume').trim(), '')
91
+ const checkout = join(f.root, 'checkout')
92
+ execFileSync('git', ['init', '-q', '-b', 'main', checkout])
93
+ const runDir = join(f.root, 'tickets', '42', '7', 'run-fixture')
94
+ mkdirSync(runDir, { recursive: true })
95
+ const url = 'https://github.com/example/demo/issues/7'
96
+ stage('ready', { id: 42, checkout, runDir, url })
97
+ const packet = JSON.parse(stage('packet'))
98
+ assert.equal(packet.kind, 'brief')
99
+ assert.ok(packet.prompt.includes(submission.markdown.replaceAll('\r\n', '\n')))
100
+ assert.equal((await f.tool('mission_status', ticket)).structuredContent.stage, 'investigation')
101
+ assert.deepEqual((await f.tool('submit_mission', submission)).structuredContent, { revision: 1 })
102
+ })
@@ -0,0 +1,113 @@
1
+ function displayReview(mission, show, candidate) {
2
+ console.log('Candidate: ' + candidate.sha)
3
+ show('Test evidence', candidate.evidence)
4
+ for (const review of candidate.reviews) show('Review (' + review.verdict + ')', review.file)
5
+ if (candidate.round) {
6
+ console.log('Repair handoff reference: ' + candidate.file)
7
+ show('Prior review requesting changes', candidate.requestedBy.file)
8
+ }
9
+ const supplemental = mission.notes.filter((note) => note.kind === 'evidence' && note.candidateIndex === mission.candidates.length - 1)
10
+ for (const note of supplemental) show('Supplemental evidence', note.file)
11
+ }
12
+
13
+ const next = {
14
+ preparation: 'Run Initiate or verify readiness for the target checkout, then record ready.',
15
+ investigation: 'Run Investigator with assigned workspace access, then record brief or investigation-question.',
16
+ 'investigation-waiting': 'Record investigation-answer for the saved question to resume.',
17
+ 'planning-waiting': 'Record clarification with the saved planning question filename and an Answer section.',
18
+ planning: 'Run Planner in a fresh read-only session, then record plan or clarification.',
19
+ approval: 'Approve this exact plan filename or record plan-feedback.',
20
+ implementation: 'Run Developer in a fresh session on a dedicated branch and worktree, then record candidate.',
21
+ review: 'Run Reviewer in a fresh read-only session for the candidate SHA, then record review.',
22
+ 'review-blocked': 'Record the missing evidence to resume this review, or submit a revised commit for fresh review.',
23
+ repair: 'Give Developer the latest review and approved plan in the existing worktree, then record repair.',
24
+ 'repair-paused': 'Human decision required. Review the outstanding findings before using record continue to authorize one more repair.',
25
+ delivery: 'Follow GitHub delivery for the passing SHA and record the PR, CI, and advisory review results.',
26
+ 'delivery-head-changed': 'Submit the reported PR head as a candidate for fresh review before delivering it.',
27
+ delivered: 'Use the existing GitHub workflow for the human merge decision, checking the current PR head.',
28
+ }
29
+
30
+ function displayRepairs(mission, show) {
31
+ const repairs = mission.candidates.filter((candidate) => candidate.round)
32
+ show('Initial review requesting changes', repairs[0]?.requestedBy.file)
33
+ for (const repair of repairs) {
34
+ console.log('Repair ' + repair.round + ' candidate: ' + repair.sha)
35
+ show('Repair handoff', repair.file)
36
+ for (const review of repair.reviews) show('Review (' + review.verdict + ')', review.file)
37
+ }
38
+ }
39
+
40
+ function displayDelivery(mission, show, candidate) {
41
+ console.log('Passing SHA: ' + candidate.sha)
42
+ show('Passing review', candidate.reviews.at(-1).file)
43
+ show('Test evidence', candidate.evidence)
44
+ const result = mission.delivery.at(-1)
45
+ if (result?.head === candidate.sha && !result.changed) {
46
+ console.log('PR: ' + result.pr)
47
+ console.log('CI: ' + result.ci + ' · Advisory review: ' + result.advisory)
48
+ show('Delivery evidence', result.file)
49
+ }
50
+ }
51
+
52
+ export function showStatus(store, { mission, revision }, current = true) {
53
+ const show = (label, name) => {
54
+ if (name) console.log(label + ': ' + store.artifact(name))
55
+ }
56
+ const { stage } = mission
57
+ console.log(`${mission.repository}#${mission.number} · ${stage} · revision ${revision}`)
58
+ show('Mission', mission.file)
59
+ show('Target context', mission.ready?.file)
60
+ if (['planning', 'planning-waiting', 'approval'].includes(stage)) {
61
+ show('Investigation brief', mission.brief)
62
+ if (stage === 'planning-waiting') show('Planner question', mission.notes.at(-1).file)
63
+ if (stage === 'planning') show('Plan draft to revise', mission.plans.at(-1)?.file)
64
+ for (const note of mission.notes.filter(({ kind }) => ['clarification', 'plan-feedback'].includes(kind))) {
65
+ show(note.kind === 'clarification' ? 'Planning clarification' : 'Plan feedback', note.file)
66
+ }
67
+ }
68
+ if (['investigation', 'investigation-waiting', 'planning'].includes(stage)) {
69
+ for (const note of mission.notes.filter(note => note.kind.startsWith('investigation-')))
70
+ show(note.kind === 'investigation-question' ? 'Investigator question' : 'Operator answer', note.file)
71
+ }
72
+ const plan = mission.plans.at(-1)
73
+ if (stage === 'approval') {
74
+ show('Pending plan', plan.file)
75
+ console.log('Plan filename: ' + plan.file)
76
+ }
77
+ show('Approved plan', plan?.approved)
78
+ const candidate = mission.candidates.at(-1)
79
+ if (['review', 'review-blocked', 'repair', 'repair-paused'].includes(stage)) {
80
+ console.log('Unsuccessful repairs: ' + mission.failedRepairs + ' · Remaining automatic repair rounds: ' +
81
+ Math.max(0, 2 - mission.failedRepairs))
82
+ }
83
+ if (['review', 'review-blocked'].includes(stage)) displayReview(mission, show, candidate)
84
+ if (['repair', 'repair-paused'].includes(stage)) {
85
+ show('Latest implementation handoff', candidate.file)
86
+ show('Outstanding findings', candidate.reviews.at(-1).file)
87
+ const decision = mission.notes.findLast((note) => note.kind === 'continue')
88
+ if (stage === 'repair') show('Operator repair decision', decision?.file)
89
+ if (stage === 'repair-paused') displayRepairs(mission, show)
90
+ }
91
+ if (['delivery', 'delivered'].includes(stage)) displayDelivery(mission, show, candidate)
92
+ if (stage === 'delivery-head-changed') {
93
+ const result = mission.delivery.at(-1)
94
+ console.log('PR: ' + result.pr)
95
+ console.log('Reported PR head: ' + result.head)
96
+ show('Delivery evidence', result.file)
97
+ }
98
+ console.log('Next: ' + nextAction(mission, current))
99
+ }
100
+
101
+ export function nextAction(mission, current) {
102
+ if (!current) return 'Historical record. Run status for the current mission.'
103
+ const { stage } = mission
104
+ const candidate = mission.candidates.at(-1)
105
+ let action = next[stage]
106
+ if (stage === 'delivery' && mission.delivery.at(-1)?.head === candidate.sha && !mission.delivery.at(-1).changed) {
107
+ const { ci, advisory } = mission.delivery.at(-1)
108
+ if (ci === 'Failed') action = 'Investigate the failed CI checks. Submit any new PR head as a candidate for review.'
109
+ else if (ci === 'Pending') action = 'Wait for the required CI checks and record their results.'
110
+ else if (advisory === 'Pending') action = 'Review the advisory findings and record their disposition.'
111
+ }
112
+ return action
113
+ }