@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,180 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import {
3
+ linkSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync,
4
+ unlinkSync, writeFileSync,
5
+ } from 'node:fs'
6
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path'
7
+
8
+ export class InputError extends Error {
9
+ constructor(message, code) {
10
+ super(message)
11
+ this.code = code
12
+ }
13
+ }
14
+
15
+ export function requireInput(condition, message, code) {
16
+ if (!condition) throw new InputError(message, code)
17
+ }
18
+
19
+ export function digest(value) {
20
+ return createHash('sha256').update(value).digest('hex')
21
+ }
22
+
23
+ export function containsPath(parent, child) {
24
+ const path = relative(parent, child)
25
+ return path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith('..' + sep))
26
+ }
27
+
28
+ const states = new Set([
29
+ 'preparation', 'investigation', 'investigation-waiting', 'planning', 'planning-waiting', 'approval', 'implementation',
30
+ 'review', 'review-blocked', 'repair', 'repair-paused', 'delivery', 'delivery-head-changed', 'delivered',
31
+ ])
32
+
33
+ const artifactName = /^[a-z-]+-[a-f0-9]{64}\.md$/
34
+
35
+ function publish(directory, name, contents) {
36
+ const temporary = join(directory, '.pending-' + randomUUID())
37
+ try {
38
+ writeFileSync(temporary, contents, { flag: 'wx', mode: 0o600, flush: true })
39
+ try {
40
+ // A named revision can be published by only one writer, even after a restart.
41
+ linkSync(temporary, join(directory, name))
42
+ return true
43
+ } catch (error) {
44
+ if (error.code !== 'EEXIST') throw error
45
+ return false
46
+ }
47
+ } finally {
48
+ try {
49
+ unlinkSync(temporary)
50
+ } catch (error) {
51
+ if (error.code !== 'ENOENT') throw error
52
+ }
53
+ }
54
+ }
55
+
56
+ export function operatorFile(path) {
57
+ requireInput(lstatSync(path, { throwIfNoEntry: false })?.isFile(), 'Expected a regular Markdown input file.')
58
+ const bytes = readFileSync(path)
59
+ const text = bytes.toString('utf8')
60
+ requireInput(Buffer.from(text).equals(bytes), 'Expected nonempty UTF-8 Markdown.')
61
+ return normalizeMarkdown(text)
62
+ }
63
+
64
+ export function normalizeMarkdown(text) {
65
+ requireInput(typeof text === 'string' && text.isWellFormed() && text.trim(),
66
+ 'Expected nonempty UTF-8 Markdown.', 'invalid_input')
67
+ return text.replace(/\r\n/g, '\n')
68
+ }
69
+
70
+ export function openStore(path, pack, create) {
71
+ const directory = resolve(path)
72
+ requireInput(!containsPath(pack, directory), 'Choose a state directory outside the workflow pack checkout.')
73
+ requireInput(!lstatSync(directory, { throwIfNoEntry: false })?.isSymbolicLink(), 'Choose a state directory without a symbolic link at its final component.')
74
+
75
+ if (!lstatSync(directory, { throwIfNoEntry: false })) {
76
+ requireInput(create, 'No mission state here. Use submit or check --state.', 'missing_mission')
77
+ const parent = realpathSync(resolve(directory, '..'))
78
+ requireInput(!containsPath(pack, parent), 'Choose a state directory outside the workflow pack checkout.')
79
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
80
+ }
81
+ requireInput(lstatSync(directory).isDirectory(), 'Expected a mission state directory.')
82
+ const root = realpathSync(directory)
83
+ requireInput(!containsPath(pack, root), 'Choose a state directory outside the workflow pack checkout.')
84
+
85
+ function revisions() {
86
+ return readdirSync(root)
87
+ .map((entry) => /^mission-([1-9]\d*)\.json$/.exec(entry))
88
+ .filter(Boolean)
89
+ .map((match) => Number(match[1]))
90
+ .sort((left, right) => right - left)
91
+ }
92
+
93
+ function artifact(name) {
94
+ requireInput(artifactName.test(name), 'Invalid handoff reference in saved state.')
95
+ const file = join(root, name)
96
+ requireInput(lstatSync(file, { throwIfNoEntry: false })?.isFile(), 'Saved handoff is missing. Restore it before proceeding.')
97
+ const contents = readFileSync(file)
98
+ requireInput(name.endsWith(digest(contents) + '.md'), 'Saved handoff was changed. Restore it before proceeding.')
99
+ return file
100
+ }
101
+
102
+ function read(revision) {
103
+ const path = join(root, 'mission-' + revision + '.json')
104
+ const invalid = 'Invalid mission state at revision ' + revision + '. Restore the saved record before proceeding.'
105
+ requireInput(lstatSync(path, { throwIfNoEntry: false })?.isFile(), invalid)
106
+ let saved
107
+ try {
108
+ saved = JSON.parse(readFileSync(path, 'utf8'))
109
+ } catch (error) {
110
+ if (error instanceof SyntaxError) throw new InputError(invalid)
111
+ throw error
112
+ }
113
+ requireInput(saved?.revision === revision && saved?.version === 1 &&
114
+ /^[a-f0-9]{64}$/.test(saved.request) && validMission(saved.mission), invalid)
115
+ for (const name of handoffs(saved.mission)) artifact(name)
116
+ return saved
117
+ }
118
+
119
+ return {
120
+ root, artifact, read, revisions,
121
+ saveArtifact(kind, contents) {
122
+ const name = kind + '-' + digest(contents) + '.md'
123
+ publish(root, name, contents)
124
+ artifact(name)
125
+ return name
126
+ },
127
+ save(revision, request, mission) {
128
+ return publish(root, 'mission-' + revision + '.json',
129
+ JSON.stringify({ version: 1, revision, request, mission }, null, 2) + '\n')
130
+ },
131
+ }
132
+ }
133
+
134
+ function validMission(mission) {
135
+ return mission && states.has(mission.stage) && typeof mission.repository === 'string' &&
136
+ Number.isSafeInteger(mission.number) && mission.number > 0 && typeof mission.file === 'string' &&
137
+ Array.isArray(mission.notes) && Array.isArray(mission.plans) &&
138
+ Array.isArray(mission.candidates) && Array.isArray(mission.delivery) &&
139
+ Number.isSafeInteger(mission.failedRepairs) && mission.failedRepairs >= 0 &&
140
+ Number.isSafeInteger(mission.round) && mission.round >= mission.failedRepairs &&
141
+ mission.notes.every((note) => typeof note?.file === 'string') &&
142
+ mission.plans.every((plan) => typeof plan?.file === 'string') &&
143
+ mission.candidates.every((candidate) => typeof candidate?.file === 'string' &&
144
+ typeof candidate.evidence === 'string' && typeof candidate.sha === 'string' &&
145
+ Number.isSafeInteger(candidate.round) && candidate.round >= 0 &&
146
+ (!candidate.round || (typeof candidate.requestedBy?.file === 'string' && typeof candidate.requestedBy.sha === 'string')) &&
147
+ Array.isArray(candidate.reviews) && candidate.reviews.every((review) => typeof review?.file === 'string')) &&
148
+ mission.delivery.every((result) => typeof result?.file === 'string') &&
149
+ hasStageInputs(mission)
150
+ }
151
+
152
+ function hasStageInputs(mission) {
153
+ const { stage, ready, brief, plans, candidates, delivery } = mission
154
+ if (stage === 'preparation') return true
155
+ if (typeof ready?.file !== 'string' || typeof ready.base !== 'string' || typeof ready.checkout !== 'string') return false
156
+ if (stage === 'investigation-waiting') return mission.notes.at(-1)?.kind === 'investigation-question'
157
+ if (stage === 'investigation') return true
158
+ if (typeof brief !== 'string') return false
159
+ if (stage === 'planning-waiting') return mission.notes.at(-1)?.kind === 'planning-question'
160
+ if (stage === 'planning') return true
161
+ if (!plans.length) return false
162
+ if (stage === 'approval') return true
163
+ if (typeof plans.at(-1).approved !== 'string') return false
164
+ if (stage === 'implementation') return true
165
+ if (!candidates.length) return false
166
+ if (stage === 'review') return true
167
+ if (stage === 'delivery-head-changed') return delivery.length > 0
168
+ if (!candidates.at(-1).reviews.length) return false
169
+ return stage !== 'delivered' || delivery.length > 0
170
+ }
171
+
172
+ function handoffs(mission) {
173
+ return [
174
+ mission.file, mission.ready?.file, mission.brief,
175
+ ...mission.notes.map((note) => note.file),
176
+ ...mission.plans.flatMap((plan) => [plan.file, plan.approved]),
177
+ ...mission.candidates.flatMap((candidate) => [candidate.file, candidate.evidence, candidate.requestedBy?.file, ...candidate.reviews.map((review) => review.file)]),
178
+ ...mission.delivery.map((result) => result.file),
179
+ ].filter((name) => name !== undefined)
180
+ }
@@ -0,0 +1,54 @@
1
+ import { fileURLToPath } from 'node:url'
2
+ import { readFileSync, realpathSync } from 'node:fs'
3
+ import { changeMission, findMission, identity } from './controller.mjs'
4
+ import { InputError, normalizeMarkdown, openStore } from './store.mjs'
5
+ import { nextAction } from './status.mjs'
6
+
7
+ const pack = realpathSync(fileURLToPath(new URL('../../', import.meta.url)))
8
+ const ticket = {
9
+ repository: { type: 'string', description: 'GitHub owner/repo' },
10
+ issue: { type: 'integer', minimum: 1, maximum: Number.MAX_SAFE_INTEGER },
11
+ }
12
+ export const tools = [
13
+ {
14
+ name: 'submit_mission', description: 'Save a mission for the operator to run.',
15
+ inputSchema: {
16
+ type: 'object', required: ['repository', 'issue', 'markdown'], additionalProperties: false,
17
+ properties: { ...ticket, markdown: { type: 'string' },
18
+ expectedRevision: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER - 1 } },
19
+ },
20
+ },
21
+ {
22
+ name: 'mission_status', description: 'Read current progress, or look up a ticket by repository and issue.',
23
+ inputSchema: { type: 'object', properties: ticket, additionalProperties: false,
24
+ oneOf: [{ maxProperties: 0 }, { required: ['repository', 'issue'] }] },
25
+ },
26
+ ]
27
+
28
+ export function callTool(state, tool, args) {
29
+ const submit = tool.name === 'submit_mission'
30
+ if (!args || typeof args !== 'object' || Array.isArray(args) ||
31
+ Object.keys(args).some(key => !Object.hasOwn(tool.inputSchema.properties, key)))
32
+ throw new InputError('Expected the advertised tool arguments.', 'invalid_input')
33
+ let key
34
+ if (submit || Object.keys(args).length) {
35
+ if (typeof args.repository !== 'string' || !Number.isSafeInteger(args.issue))
36
+ throw new InputError('Supply repository and a positive integer issue together.', 'invalid_input')
37
+ key = identity(args.repository, args.issue)
38
+ }
39
+ if (submit) {
40
+ const text = normalizeMarkdown(args.markdown)
41
+ const store = openStore(state, pack, true)
42
+ const { revision } = changeMission(store, 'submit', [key, text],
43
+ args.expectedRevision === undefined ? 0 : args.expectedRevision)
44
+ return { revision }
45
+ }
46
+ const store = openStore(state, pack, false)
47
+ const { saved: { mission, revision }, current } = findMission(store, key)
48
+ return {
49
+ repository: mission.repository, issue: mission.number, revision, stage: mission.stage,
50
+ nextAction: nextAction(mission, current),
51
+ pendingPlan: mission.stage === 'approval' ? readFileSync(store.artifact(mission.plans.at(-1).file), 'utf8') : null,
52
+ prUrl: mission.delivery.at(-1)?.pr ?? null,
53
+ }
54
+ }
@@ -0,0 +1,269 @@
1
+ import { lstatSync, realpathSync } from 'node:fs'
2
+ import { isAbsolute, resolve } from 'node:path'
3
+ import { containsPath, InputError, operatorFile, requireInput } from './store.mjs'
4
+
5
+ const shaPattern = /^[a-f0-9]{40}$|^[a-f0-9]{64}$/i
6
+
7
+ export function issueUrl({ repository, number }) {
8
+ return `https://github.com/${repository}/issues/${number}`
9
+ }
10
+
11
+ function populatedSection(text, title) {
12
+ const [, ...matches] = text.split('\n## ' + title + '\n')
13
+ const section = matches.length === 1 && matches[0].split('\n## ')[0].trim()
14
+ requireInput(section, 'Expected one populated Markdown section named ' + title + '.')
15
+ return section
16
+ }
17
+
18
+ export function field(text, name) {
19
+ const values = text.split('\n').flatMap((line) => {
20
+ const match = new RegExp('^(?:[-*] )?\\*\\*' + name + '(?::\\*\\*|\\*\\* *(?:—|:)) +(.+)$').exec(line)
21
+ return match ? [match[1].trim()] : []
22
+ })
23
+ requireInput(values.length === 1 && values[0], 'Expected one Markdown field named ' + name + '.')
24
+ return values[0].replace(/^`([^`]+)`$/, '$1')
25
+ }
26
+
27
+ function references(text, artifact, description) {
28
+ const citations = text.match(/[a-z-]+-[a-f0-9]{64}\.md/g) ?? []
29
+ requireInput(citations.includes(artifact), 'Handoff must reference the current ' + description + '.')
30
+ if (description === 'approved plan') {
31
+ const approvedPlans = new Set(citations.filter((name) => name.startsWith('approved-plan-')))
32
+ requireInput(approvedPlans.size === 1, 'Handoff must reference exactly one approved plan.')
33
+ }
34
+ }
35
+
36
+ export function matchesTicket(mission, text) {
37
+ const citations = text.match(/https?:\/\/[^\s<>"'`()\[\]]+/gi) ?? []
38
+ const expected = issueUrl(mission)
39
+ requireInput(citations.some((url) => url.replace(/[.,;:!]+$/, '').toLowerCase() === expected),
40
+ 'Handoff must reference ' + expected + '.')
41
+ }
42
+
43
+ function sha(value) {
44
+ const clean = value.replace(/^`([a-f0-9]+)`$/i, '$1')
45
+ requireInput(shaPattern.test(clean), 'Expected a full candidate Git SHA.')
46
+ return clean.toLowerCase()
47
+ }
48
+
49
+ function atStage(mission, kind, ...stages) {
50
+ requireInput(stages.includes(mission.stage), 'Cannot record ' + kind + ' during ' + mission.stage + '. Run status.')
51
+ }
52
+
53
+ function ready(mission, text, store, initialized = false) {
54
+ atStage(mission, 'ready', initialized ? 'implementation' : 'preparation')
55
+ const checkout = field(text, 'Checkout')
56
+ requireInput(isAbsolute(checkout) && lstatSync(checkout, { throwIfNoEntry: false })?.isDirectory(),
57
+ 'Checkout must name an existing absolute target checkout directory.')
58
+ const canonicalCheckout = realpathSync(checkout)
59
+ requireInput(!containsPath(canonicalCheckout, store.root),
60
+ 'Choose a state directory outside the target checkout.')
61
+ populatedSection(text, 'Readiness')
62
+ if (initialized) {
63
+ const previous = operatorFile(store.artifact(mission.ready.file))
64
+ requireInput(field(previous, 'Starting commit') === 'unborn' && !mission.candidates.length &&
65
+ canonicalCheckout === mission.ready.checkout && field(text, 'Base branch') === mission.ready.base,
66
+ 'Expected the original unborn checkout and base branch before the first candidate.')
67
+ sha(field(text, 'Starting commit'))
68
+ delete mission.brief
69
+ mission.plans = []
70
+ }
71
+ mission.ready = { file: store.saveArtifact('ready', text), base: field(text, 'Base branch'), checkout: canonicalCheckout }
72
+ mission.stage = 'investigation'
73
+ }
74
+
75
+ function brief(mission, text, store) {
76
+ atStage(mission, 'brief', 'investigation')
77
+ for (const title of ['Mission', 'Repository context', 'Verified findings']) populatedSection(text, title)
78
+ mission.brief = store.saveArtifact('brief', text)
79
+ mission.stage = 'planning'
80
+ }
81
+
82
+ function plan(mission, text, store) {
83
+ atStage(mission, 'plan', 'planning', 'approval', 'implementation')
84
+ references(populatedSection(text, 'Mission and evidence'), mission.brief, 'investigation brief')
85
+ for (const title of ['Planned changes', 'Acceptance criteria', 'Verification']) populatedSection(text, title)
86
+ const approval = populatedSection(text, 'Human approval')
87
+ requireInput(approval.split('\n').includes('**Decision:** Pending') && field(text, 'Decision') === 'Pending',
88
+ 'A submitted plan must have one Pending decision.')
89
+ const file = store.saveArtifact('plan', text)
90
+ requireInput(mission.stage === 'planning' || mission.plans.at(-1)?.file !== file,
91
+ 'This is already the current plan revision. Run status.')
92
+ mission.plans.push({ file })
93
+ mission.stage = 'approval'
94
+ }
95
+
96
+ export function approve(mission, expected, store) {
97
+ atStage(mission, 'approval', 'approval')
98
+ const plan = mission.plans.at(-1)
99
+ requireInput(expected === plan.file, 'Approval must name the current pending plan file.')
100
+ const text = operatorFile(store.artifact(plan.file))
101
+ const approved = text.replace(/^\*\*Decision:\*\* Pending$/m, '**Decision:** Approved')
102
+ requireInput(approved !== text, 'Expected the plan decision on a line reading **Decision:** Pending.')
103
+ plan.approved = store.saveArtifact('approved-plan', approved)
104
+ mission.stage = 'implementation'
105
+ }
106
+
107
+ function candidate(mission, text, store, repair) {
108
+ const previous = mission.candidates.at(-1)
109
+ const replacing = ['review', 'review-blocked'].includes(mission.stage)
110
+ const stages = repair ? ['repair'] : ['implementation', 'delivery', 'delivery-head-changed', 'delivered']
111
+ if (replacing && repair === Boolean(previous.round)) stages.push('review', 'review-blocked')
112
+ atStage(mission, repair ? 'repair' : 'candidate', ...stages)
113
+ references(field(text, 'Approved plan'), mission.plans.at(-1).approved, 'approved plan')
114
+ const commit = sha(field(text, 'Candidate commit'))
115
+ if (mission.stage === 'delivery-head-changed') {
116
+ requireInput(commit === mission.delivery.at(-1).head, 'Submit the newly reported PR head for review.')
117
+ } else {
118
+ requireInput(!mission.candidates.some((record) => record.sha === commit), 'Submit a new candidate SHA.')
119
+ }
120
+ const verification = populatedSection(text, 'Verification')
121
+ const target = field(text, 'Target').toLowerCase()
122
+ requireInput(target === mission.repository || target === 'https://github.com/' + mission.repository,
123
+ 'Candidate target must identify the mission repository.')
124
+ const branch = field(text, 'Branch')
125
+ const localBranch = (name) => name.replace(/^refs\/heads\//, '')
126
+ requireInput(localBranch(branch) !== localBranch(mission.ready.base),
127
+ 'Candidate must use a dedicated branch instead of the recorded base branch.')
128
+ const worktree = field(text, 'Worktree')
129
+ requireInput(isAbsolute(worktree), 'Expected an absolute implementation worktree path.')
130
+ const canonicalWorktree = lstatSync(worktree, { throwIfNoEntry: false }) ? realpathSync(worktree) : resolve(worktree)
131
+ requireInput(canonicalWorktree !== mission.ready.checkout,
132
+ 'Use a dedicated implementation worktree separate from the readiness checkout.')
133
+ let requestedBy
134
+ if (repair) {
135
+ requestedBy = replacing ? previous.requestedBy : { sha: previous.sha, file: previous.reviews.at(-1).file }
136
+ requireInput(branch === previous.branch && worktree === previous.worktree,
137
+ 'Use the dedicated branch and worktree from the preceding candidate.')
138
+ const details = populatedSection(text, 'Repair details')
139
+ references(details, requestedBy.file, 'review requesting changes')
140
+ requireInput(details.includes(requestedBy.sha), 'Repair must identify the preceding reviewed SHA.')
141
+ }
142
+ const file = store.saveArtifact(repair ? 'repair' : 'candidate', text)
143
+ const evidence = store.saveArtifact('checks', '# Verification for ' + commit + '\n\n' + verification + '\n')
144
+ mission.candidates.push({ sha: commit, branch, worktree, file, evidence, round: repair ? mission.round : 0, requestedBy, reviews: [] })
145
+ mission.stage = 'review'
146
+ }
147
+
148
+ function review(mission, text, store) {
149
+ atStage(mission, 'review', 'review')
150
+ const candidate = mission.candidates.at(-1)
151
+ requireInput(sha(field(text, 'Candidate')) === candidate.sha, 'Review must identify the exact current candidate SHA.')
152
+ references(field(text, 'Mission and approved plan'), mission.plans.at(-1).approved, 'approved plan')
153
+ const target = field(text, 'Target and base').toLowerCase()
154
+ requireInput(target === mission.repository && field(text, 'Base branch') === mission.ready.base,
155
+ 'Review must identify the target repository and intended base branch.')
156
+ sha(field(text, 'Base commit'))
157
+ if (candidate.round) {
158
+ const details = populatedSection(text, 'Repair review')
159
+ references(details, candidate.file, 'repair handoff')
160
+ references(details, candidate.requestedBy.file, 'review requesting changes')
161
+ }
162
+ const verdictLine = field(text, 'Verdict')
163
+ const match = /^(Pass|Changes requested|Blocked)\s+[—-]\s+(\S.*)$/.exec(verdictLine)
164
+ requireInput(match, 'Expected a review verdict of Pass, Changes requested, or Blocked followed by the reason.')
165
+ const [, verdict] = match
166
+ if (verdict !== 'Blocked') {
167
+ populatedSection(text, 'Acceptance criteria')
168
+ populatedSection(text, 'Thermo review and required changes')
169
+ }
170
+ const file = store.saveArtifact('review', text)
171
+ requireInput(verdict === 'Blocked' || !candidate.reviews.some((review) => review.file === file),
172
+ 'This review was already saved. Run status.')
173
+ candidate.reviews.push({ file, verdict })
174
+ if (verdict === 'Pass') {
175
+ mission.stage = 'delivery'
176
+ } else if (verdict === 'Blocked') {
177
+ mission.stage = 'review-blocked'
178
+ } else {
179
+ if (candidate.round) mission.failedRepairs++
180
+ mission.stage = mission.failedRepairs >= 2 ? 'repair-paused' : 'repair'
181
+ if (mission.stage === 'repair') mission.round++
182
+ }
183
+ }
184
+
185
+ function delivery(mission, text, store, observedChange = false) {
186
+ const deliveryStages = ['delivery', 'delivered']
187
+ const stages = observedChange && mission.delivery.length
188
+ ? [...deliveryStages, 'delivery-head-changed', 'review', 'review-blocked', 'repair', 'repair-paused']
189
+ : deliveryStages
190
+ atStage(mission, observedChange ? 'head-changed' : 'delivery', ...stages)
191
+ const candidate = mission.candidates.at(-1)
192
+ const head = sha(field(text, 'Head'))
193
+ const pr = field(text, 'PR')
194
+ const prefix = 'https://github.com/' + mission.repository + '/pull/'
195
+ requireInput(pr.toLowerCase().startsWith(prefix) && /^[1-9]\d*$/.test(pr.slice(prefix.length)),
196
+ 'Expected a GitHub PR URL for the mission repository.')
197
+ const prior = mission.delivery.at(-1)
198
+ requireInput(!prior || prior.pr.toLowerCase() === pr.toLowerCase(), 'Use the PR already recorded for this mission.')
199
+ const ci = field(text, 'CI')
200
+ const advisory = field(text, 'Advisory review')
201
+ requireInput(['Pending', 'Failed', 'Passed'].includes(ci), 'Expected CI to be Pending, Failed, or Passed.')
202
+ requireInput(['Pending', 'Resolved'].includes(advisory), 'Expected advisory review to be Pending or Resolved.')
203
+ populatedSection(text, 'Evidence')
204
+ const changed = observedChange || head !== candidate.sha
205
+ if (observedChange) {
206
+ const previousHead = mission.stage === 'delivery-head-changed' ? prior.head : candidate.sha
207
+ requireInput(head !== previousHead, 'The reported PR head already matches the last recorded head.')
208
+ } else if (changed) {
209
+ requireInput(!mission.candidates.some((record) => record.sha === head),
210
+ 'Delivery evidence refers to a superseded candidate SHA. Use record head-changed if you verified the actual PR head changed.')
211
+ }
212
+ const file = store.saveArtifact('delivery', text)
213
+ mission.delivery.push({ file, pr, head, ci, advisory, changed })
214
+ if (changed) mission.stage = 'delivery-head-changed'
215
+ else mission.stage = ci === 'Passed' && advisory === 'Resolved' ? 'delivered' : 'delivery'
216
+ }
217
+
218
+ function note(mission, kind, text, store, stage, next = stage) {
219
+ atStage(mission, kind, stage)
220
+ const file = store.saveArtifact(kind, text)
221
+ const entry = { kind, file }
222
+ if (kind === 'evidence') {
223
+ entry.candidate = mission.candidates.at(-1).sha
224
+ entry.candidateIndex = mission.candidates.length - 1
225
+ requireInput(sha(field(text, 'Candidate')) === entry.candidate,
226
+ 'Supplemental evidence must identify the exact current candidate SHA.')
227
+ }
228
+ mission.notes.push(entry)
229
+ mission.stage = next
230
+ }
231
+
232
+ export function record(mission, kind, text, store) {
233
+ matchesTicket(mission, text)
234
+ switch (kind) {
235
+ case 'ready': return ready(mission, text, store)
236
+ case 'initialized-base': return ready(mission, text, store, true)
237
+ case 'brief': return brief(mission, text, store)
238
+ case 'plan': return plan(mission, text, store)
239
+ case 'investigation-question':
240
+ for (const title of ['Findings', 'Question', 'Why it matters']) populatedSection(text, title)
241
+ return note(mission, kind, text, store, 'investigation', 'investigation-waiting')
242
+ case 'investigation-answer':
243
+ populatedSection(text, 'Answer')
244
+ references(text, mission.notes.at(-1)?.file, 'investigation question')
245
+ return note(mission, kind, text, store, 'investigation-waiting', 'investigation')
246
+ case 'planning-question':
247
+ for (const title of ['Question', 'Why it matters']) populatedSection(text, title)
248
+ return note(mission, kind, text, store, 'planning', 'planning-waiting')
249
+ case 'clarification':
250
+ if (mission.stage === 'planning-waiting') {
251
+ populatedSection(text, 'Answer')
252
+ references(text, mission.notes.at(-1).file, 'planning question')
253
+ return note(mission, kind, text, store, 'planning-waiting', 'planning')
254
+ }
255
+ return note(mission, kind, text, store, 'planning')
256
+ case 'plan-feedback': return note(mission, kind, text, store, 'approval', 'planning')
257
+ case 'candidate': return candidate(mission, text, store, false)
258
+ case 'repair': return candidate(mission, text, store, true)
259
+ case 'review': return review(mission, text, store)
260
+ case 'evidence': return note(mission, kind, text, store, 'review-blocked', 'review')
261
+ case 'continue':
262
+ note(mission, kind, text, store, 'repair-paused', 'repair')
263
+ mission.round++
264
+ return
265
+ case 'delivery': return delivery(mission, text, store)
266
+ case 'head-changed': return delivery(mission, text, store, true)
267
+ default: throw new InputError('Unknown handoff kind. Run --help.')
268
+ }
269
+ }
@@ -0,0 +1,72 @@
1
+ import { realpathSync } from 'node:fs'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { parseArgs } from 'node:util'
4
+ import { changeMission, findMission, identity } from './mission/controller.mjs'
5
+ import { InputError, openStore, operatorFile, requireInput } from './mission/store.mjs'
6
+
7
+ import { showStatus } from './mission/status.mjs'
8
+
9
+ const pack = realpathSync(fileURLToPath(new URL('../', import.meta.url)))
10
+ const usage = `Usage: node engineering-workflows/mission-controller.mjs --state DIR COMMAND
11
+ submit OWNER/REPO ISSUE MISSION.md [--at REVISION]
12
+ status [OWNER/REPO ISSUE]
13
+ record KIND FILE.md --at REVISION
14
+ approve PLAN_FILENAME --at REVISION
15
+
16
+ Kinds: ready, initialized-base, brief, investigation-question, investigation-answer, planning-question, clarification, plan, plan-feedback, candidate, review,
17
+ evidence, repair, continue, delivery, head-changed`
18
+
19
+ function mutate(store, command, operands, at) {
20
+ requireInput(at !== undefined || command === 'submit',
21
+ 'Supply --at with the revision shown by status.')
22
+ const previous = at === undefined ? 0 : Number(at)
23
+ requireInput(String(previous) === (at ?? '0'), 'Expected a valid revision in --at.')
24
+
25
+ let payload
26
+ if (command === 'submit') {
27
+ requireInput(operands.length === 3, usage)
28
+ payload = [identity(...operands.slice(0, 2)), operatorFile(operands[2])]
29
+ } else if (command === 'record') {
30
+ requireInput(operands.length === 2, usage)
31
+ payload = [operands[0], operatorFile(operands[1])]
32
+ } else {
33
+ requireInput(operands.length === 1, usage)
34
+ payload = operands
35
+ }
36
+
37
+ const { revision, replay } = changeMission(store, command, payload, previous)
38
+ if (replay) console.log('Already accepted at revision ' + revision + '.')
39
+ else showStatus(store, store.read(revision))
40
+ }
41
+
42
+ function main(args) {
43
+ let parsed
44
+ try {
45
+ parsed = parseArgs({
46
+ args, allowPositionals: true,
47
+ options: { state: { type: 'string' }, at: { type: 'string' }, help: { type: 'boolean' } },
48
+ })
49
+ } catch (error) {
50
+ if (!error.code?.startsWith('ERR_PARSE_ARGS_')) throw error
51
+ throw new InputError(usage)
52
+ }
53
+ const { values, positionals: [command, ...operands] } = parsed
54
+ if (values.help) return console.log(usage)
55
+ requireInput(values.state && ['submit', 'status', 'record', 'approve'].includes(command), usage)
56
+ const store = openStore(values.state, pack, command === 'submit')
57
+ if (command === 'status') {
58
+ requireInput(operands.length === 0 || operands.length === 2, usage)
59
+ const key = operands.length ? identity(...operands) : null
60
+ const { saved, current } = findMission(store, key)
61
+ return showStatus(store, saved, current)
62
+ }
63
+ mutate(store, command, operands, values.at)
64
+ }
65
+
66
+ try {
67
+ main(process.argv.slice(2))
68
+ } catch (error) {
69
+ console.error(error instanceof InputError ? error.message :
70
+ 'Mission controller failed unexpectedly' + (error.code ? ' (' + error.code + ')' : '') + '. Check the input files and state directory.')
71
+ process.exitCode = 1
72
+ }
@@ -0,0 +1,66 @@
1
+ import { createInterface } from 'node:readline'
2
+ import { once } from 'node:events'
3
+ import { InputError } from './mission/store.mjs'
4
+ import { callTool, tools } from './mission/tools.mjs'
5
+
6
+ const [flag, state, ...extra] = process.argv.slice(2)
7
+ if (flag !== '--state' || !state || extra.length) {
8
+ console.error('Usage: node engineering-workflows/mission-mcp.mjs --state DIR')
9
+ process.exit(1)
10
+ }
11
+
12
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
13
+ const error = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } })
14
+ let phase = 'new'
15
+
16
+ function dispatch(line) {
17
+ let message
18
+ try { message = JSON.parse(line) }
19
+ catch { return error(null, -32700, 'Invalid JSON.') }
20
+ if (!object(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string' ||
21
+ (message.id !== undefined && typeof message.id !== 'string' && !Number.isSafeInteger(message.id)))
22
+ return error(null, -32600, 'Invalid request.')
23
+
24
+ const { id, method, params } = message
25
+ if (id === undefined) {
26
+ if (method === 'notifications/initialized' && phase === 'initializing') phase = 'ready'
27
+ return
28
+ }
29
+ if (params !== undefined && !object(params)) return error(id, -32602, 'Expected named parameters.')
30
+ let result
31
+ if (method === 'ping') result = {}
32
+ else if (method === 'initialize') {
33
+ if (phase !== 'new') return error(id, -32600, 'Session already initialized.')
34
+ if (typeof params?.protocolVersion !== 'string' || !object(params.capabilities) ||
35
+ typeof params.clientInfo?.name !== 'string' || typeof params.clientInfo?.version !== 'string')
36
+ return error(id, -32602, 'Invalid initialization parameters.')
37
+ phase = 'initializing'
38
+ result = { protocolVersion: '2025-06-18', capabilities: { tools: {} },
39
+ serverInfo: { name: 'engineering-workflows-missions', version: '1' } }
40
+ } else if (phase !== 'ready') return error(id, -32600, 'Initialize the session first.')
41
+ else if (method === 'tools/list') {
42
+ if (params?.cursor !== undefined && typeof params.cursor !== 'string')
43
+ return error(id, -32602, 'Expected a string cursor.')
44
+ result = { tools }
45
+ } else if (method === 'tools/call') {
46
+ if (typeof params?.name !== 'string' || (params.arguments !== undefined && !object(params.arguments)))
47
+ return error(id, -32602, 'Expected a tool name and named arguments.')
48
+ const tool = tools.find(entry => entry.name === params?.name)
49
+ if (!tool) return error(id, -32602, 'Unknown tool.')
50
+ let value
51
+ try { value = callTool(state, tool, params.arguments === undefined ? {} : params.arguments) }
52
+ catch (cause) {
53
+ const known = cause instanceof InputError && cause.code
54
+ value = { code: known ? cause.code : 'internal_failure',
55
+ message: known ? cause.message : 'Could not access valid mission state. Check the builder store.' }
56
+ result = { isError: true }
57
+ }
58
+ result = { ...result, structuredContent: value, content: [{ type: 'text', text: JSON.stringify(value) }] }
59
+ } else return error(id, -32601, 'Unknown method.')
60
+ return { jsonrpc: '2.0', id, result }
61
+ }
62
+
63
+ for await (const line of createInterface({ input: process.stdin, crlfDelay: Infinity })) {
64
+ const reply = dispatch(line)
65
+ if (reply && !process.stdout.write(JSON.stringify(reply) + '\n')) await once(process.stdout, 'drain')
66
+ }