@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,177 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { field, matchesTicket } from '../mission/transitions.mjs'
5
+ import { join } from 'node:path'
6
+
7
+ export function publishCandidate(m, store, bundle, disposition) {
8
+ if (disposition) matchesTicket(m, disposition)
9
+ const c = m.candidates.at(-1)
10
+ const review = c.reviews.at(-1)
11
+ if (review.verdict !== 'Pass') throw new Error('Delivery requires a passing review.')
12
+ const cwd = mkdtempSync(join(tmpdir(), 'ew-deliver-'))
13
+ const exec = (bin, args) =>
14
+ execFileSync(bin, args, {
15
+ cwd,
16
+ encoding: 'utf8',
17
+ stdio: ['ignore', 'pipe', 'inherit'],
18
+ env: { ...process.env, GH_PROMPT_DISABLED: '1', GIT_TERMINAL_PROMPT: '0' },
19
+ }).trim()
20
+ const gh = (...args) => exec('gh', args)
21
+ const git = (...args) => exec('git', args)
22
+ const repo = m.repository
23
+ const remote = 'https://github.com/' + repo + '.git'
24
+ const branch = c.branch
25
+ if (branch !== 'workflow/issue-' + m.number) throw new Error('Unexpected delivery branch.')
26
+ const read = (name) => readFileSync(store.artifact(name), 'utf8')
27
+ const summary = (candidate) =>
28
+ [
29
+ 'Reviewed commit: ' + candidate.sha,
30
+ read(m.plans.at(-1).approved),
31
+ read(candidate.evidence),
32
+ read(candidate.reviews.at(-1).file),
33
+ ].join('\n\n')
34
+ const prFields =
35
+ 'body,url,headRefOid,headRefName,headRepositoryOwner,headRepository,baseRefName,isDraft,state,statusCheckRollup'
36
+ const previous = m.delivery.at(-1)
37
+ try {
38
+ const listed = JSON.parse(
39
+ gh('pr', 'list', '-R', repo, '--head', branch, '--base', m.ready.base, '--state', 'all', '--json', prFields),
40
+ )
41
+ const matches = listed.filter(
42
+ (pr) =>
43
+ pr.headRepositoryOwner?.login?.toLowerCase() === repo.split('/')[0] &&
44
+ pr.headRepository?.name?.toLowerCase() === repo.split('/')[1] &&
45
+ pr.url.toLowerCase().startsWith('https://github.com/' + repo + '/pull/'),
46
+ )
47
+ let pr = previous ? matches.find((p) => p.url === previous.pr) : matches[0]
48
+ if ((previous && !pr) || matches.length > 1 || (pr && pr.state !== 'OPEN'))
49
+ throw new Error('Reconcile the existing PR before continuing.')
50
+ if (!previous && pr && pr.headRefOid !== c.sha)
51
+ throw new Error('An existing PR has a different head. Confirm its ownership before resuming.')
52
+ if (!disposition && pr && previous && previous.head === pr.headRefOid && c.sha !== previous.head) {
53
+ // A repair reviewed after the prior publication may move its branch
54
+ // forward. A head changed on GitHub follows the fresh-review path below.
55
+ const earlier = m.candidates.slice(0, -1).some((record) => record.sha === previous.head)
56
+ if (earlier) {
57
+ git('init', '--bare', '-q', '.')
58
+ git('fetch', '--no-tags', bundle, 'HEAD')
59
+ if (git('rev-parse', 'FETCH_HEAD') !== c.sha) throw new Error('Bundle differs from the reviewed commit.')
60
+ git('merge-base', '--is-ancestor', previous.head, c.sha)
61
+ git(
62
+ '-c',
63
+ 'credential.helper=!gh auth git-credential',
64
+ 'push',
65
+ '--force-with-lease=refs/heads/' + branch + ':' + previous.head,
66
+ remote,
67
+ c.sha + ':refs/heads/' + branch,
68
+ )
69
+ pr = JSON.parse(gh('pr', 'view', pr.url, '--json', prFields))
70
+ }
71
+ }
72
+ if (!pr) {
73
+ git('init', '--bare', '-q', '.')
74
+ git('fetch', '--no-tags', bundle, 'HEAD')
75
+ if (git('rev-parse', 'FETCH_HEAD') !== c.sha) throw new Error('Bundle differs from the reviewed commit.')
76
+ const ref = 'refs/heads/' + branch
77
+ const existing = git('-c', 'credential.helper=!gh auth git-credential', 'ls-remote', '--refs', remote, ref)
78
+ if (existing && existing.split(/\s/)[0] !== c.sha)
79
+ throw new Error('Remote branch has a different head. Reconcile before publishing.')
80
+ if (!existing)
81
+ git(
82
+ '-c',
83
+ 'credential.helper=!gh auth git-credential',
84
+ 'push',
85
+ '--force-with-lease=' + ref + ':',
86
+ remote,
87
+ c.sha + ':' + ref,
88
+ )
89
+ const body = join(cwd, 'body.md')
90
+ writeFileSync(body, summary(c))
91
+ const url = gh(
92
+ 'pr',
93
+ 'create',
94
+ '-R',
95
+ repo,
96
+ '--base',
97
+ m.ready.base,
98
+ '--head',
99
+ branch,
100
+ '--title',
101
+ 'Implement issue #' + m.number,
102
+ '--body-file',
103
+ body,
104
+ )
105
+ pr = JSON.parse(gh('pr', 'view', url, '--json', prFields))
106
+ }
107
+ if (previous && pr.headRefOid === c.sha && (previous.head !== c.sha || previous.changed)) {
108
+ const latest = summary(c)
109
+ if (!pr.body.includes(latest)) {
110
+ const prior = m.candidates
111
+ .slice(0, -1)
112
+ .findLast(
113
+ (candidate) => candidate.reviews.at(-1)?.verdict === 'Pass' && pr.body.includes(summary(candidate)),
114
+ )
115
+ const updated = prior ? pr.body.replace(summary(prior), () => latest) : latest + '\n\n' + pr.body
116
+ const body = join(cwd, 'body.md')
117
+ writeFileSync(body, updated)
118
+ gh('pr', 'edit', pr.url, '--body-file', body)
119
+ }
120
+ }
121
+ const checks = pr.statusCheckRollup
122
+ const results = checks
123
+ .filter((check) => check.name !== 'OpenCodeReview (advisory)')
124
+ .map((check) => check.conclusion || check.state || check.status)
125
+ .filter((result) => !['SKIPPED', 'NEUTRAL'].includes(result))
126
+ const ci = results.some((x) => ['FAILURE', 'ERROR', 'CANCELLED', 'TIMED_OUT', 'ACTION_REQUIRED', 'STALE', 'STARTUP_FAILURE'].includes(x))
127
+ ? 'Failed'
128
+ : results.length && results.every((x) => x === 'SUCCESS')
129
+ ? 'Passed'
130
+ : 'Pending'
131
+ let advisory = previous?.head === pr.headRefOid && previous.advisory === 'Resolved' ? 'Resolved' : 'Pending'
132
+ const head = gh('pr', 'view', pr.url, '--json', 'headRefOid', '--jq', '.headRefOid')
133
+ if (head !== pr.headRefOid)
134
+ throw new Error('PR changed during status lookup. Resume to collect current evidence.')
135
+ const evidenceHeading = '\n\n### Operator evidence\n\n'
136
+ let operatorEvidence
137
+ if (disposition && head === c.sha) {
138
+ if (field(disposition, 'PR') !== pr.url || field(disposition, 'Head') !== head)
139
+ throw new Error('Advisory disposition must identify the current ticket, PR and head.')
140
+ advisory = field(disposition, 'Advisory review')
141
+ const marker = '\n## Evidence\n'
142
+ const offset = disposition.indexOf(marker)
143
+ if (offset >= 0) operatorEvidence = disposition.slice(offset + marker.length).trim()
144
+ if (!['Pending', 'Resolved'].includes(advisory) || !operatorEvidence)
145
+ throw new Error('Missing advisory disposition or evidence.')
146
+ } else if (previous?.head === head && previous.file) {
147
+ const prior = read(previous.file)
148
+ const offset = prior.indexOf(evidenceHeading)
149
+ if (offset >= 0) operatorEvidence = prior.slice(offset + evidenceHeading.length).trim()
150
+ else if (advisory === 'Resolved') operatorEvidence = 'See saved disposition in ' + previous.file
151
+ }
152
+ const document = [
153
+ 'https://github.com/' + repo + '/issues/' + m.number,
154
+ '**PR:** ' + pr.url,
155
+ '**Head:** ' + head,
156
+ '**CI:** ' + ci,
157
+ '**Advisory review:** ' + advisory,
158
+ '## Evidence',
159
+ ...checks.map(
160
+ (x) =>
161
+ (x.name ?? x.context) +
162
+ ': ' +
163
+ (x.conclusion || x.state || x.status) +
164
+ ' ' +
165
+ (x.detailsUrl || x.targetUrl || ''),
166
+ ),
167
+ ].join('\n\n')
168
+ return {
169
+ kind: head !== c.sha && previous ? 'head-changed' : 'delivery',
170
+ document: document + (operatorEvidence
171
+ ? evidenceHeading + operatorEvidence
172
+ : '\n\nReview advisory findings for this head and record their disposition before merging.'),
173
+ }
174
+ } finally {
175
+ rmSync(cwd, { recursive: true, force: true })
176
+ }
177
+ }
@@ -0,0 +1,154 @@
1
+ import assert from 'node:assert/strict'
2
+ import { execFileSync } from 'node:child_process'
3
+ import { mkdtempSync, writeFileSync, readFileSync, mkdirSync, rmSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { tmpdir } from 'node:os'
6
+ import test from 'node:test'
7
+ import { publishCandidate } from './delivery.mjs'
8
+
9
+ test('publishes only the reviewed bundle, recovers the same PR and detects a moved head', (t) => {
10
+ const dir = mkdtempSync(join(tmpdir(), 'ew-delivery-test-'))
11
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
12
+ const git = (...args) => execFileSync('git', args, { cwd: dir, encoding: 'utf8' }).trim()
13
+ git('init', '-q', '-b', 'main')
14
+ git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'base', '--allow-empty')
15
+ const base = git('rev-parse', 'HEAD')
16
+ git('switch', '-qc', 'workflow/issue-7')
17
+ git(
18
+ '-c',
19
+ 'user.name=Test',
20
+ '-c',
21
+ 'user.email=test@example.invalid',
22
+ 'commit',
23
+ '-qm',
24
+ 'candidate',
25
+ '--allow-empty',
26
+ )
27
+ const sha = git('rev-parse', 'HEAD')
28
+ const remote = join(dir, 'remote.git')
29
+ git('init', '--bare', '-q', remote)
30
+ const bundle = join(dir, 'candidate.bundle')
31
+ git('bundle', 'create', bundle, 'HEAD')
32
+ const bin = join(dir, 'bin')
33
+ mkdirSync(bin)
34
+ const gh = join(bin, 'gh')
35
+ const pr = join(dir, 'pr.json')
36
+ const url = 'https://github.com/example/demo/pull/1'
37
+ const details = {
38
+ url,
39
+ headRefOid: sha,
40
+ headRepositoryOwner: { login: 'example' },
41
+ headRepository: { name: 'demo' },
42
+ state: 'OPEN',
43
+ statusCheckRollup: [{ name: 'verify', conclusion: 'SUCCESS' }],
44
+ }
45
+ writeFileSync(
46
+ gh,
47
+ `#!/usr/bin/env node
48
+ const fs=require('node:fs')
49
+ const args=process.argv.slice(2), path=${JSON.stringify(pr)}, details=${JSON.stringify(details)}
50
+ if(args[1]==='list') console.log(fs.existsSync(path)?'['+fs.readFileSync(path,'utf8')+']':'[]')
51
+ else if(args[1]==='create'){details.body=fs.readFileSync(args[args.indexOf('--body-file')+1],'utf8');fs.writeFileSync(path,JSON.stringify(details),{flag:'wx'});console.log(details.url)}
52
+ else if(args[1]==='edit'){const d=JSON.parse(fs.readFileSync(path));d.body=fs.readFileSync(args[args.indexOf('--body-file')+1],'utf8');fs.writeFileSync(path,JSON.stringify(d))}
53
+ else if(args[1]==='view'){const d=JSON.parse(fs.readFileSync(path)); console.log(args.includes('--jq')?d.headRefOid:JSON.stringify(d))}
54
+ else process.exit(1)
55
+ `,
56
+ { mode: 0o700 },
57
+ )
58
+ const config = join(dir, 'gitconfig')
59
+ git('config', '--file', config, 'url.' + remote + '.insteadOf', 'https://github.com/example/demo.git')
60
+ const old = { PATH: process.env.PATH, GIT_CONFIG_GLOBAL: process.env.GIT_CONFIG_GLOBAL }
61
+ t.after(() => {
62
+ for (const [key, val] of Object.entries(old)) {
63
+ if (val === undefined) delete process.env[key]
64
+ else process.env[key] = val
65
+ }
66
+ })
67
+ process.env.PATH = bin + ':' + old.PATH
68
+ process.env.GIT_CONFIG_GLOBAL = config
69
+ const m = {
70
+ repository: 'example/demo',
71
+ number: 7,
72
+ ready: { base: 'main' },
73
+ plans: [{ approved: 'approved.md' }],
74
+ delivery: [],
75
+ candidates: [
76
+ {
77
+ sha,
78
+ branch: 'workflow/issue-7',
79
+ evidence: 'checks.md',
80
+ reviews: [{ verdict: 'Pass', file: 'review.md' }],
81
+ },
82
+ ],
83
+ }
84
+ const store = { artifact: (name) => join(dir, name) }
85
+ for (const file of ['approved.md', 'checks.md', 'review.md']) writeFileSync(store.artifact(file), file)
86
+ const first = publishCandidate(m, store, bundle)
87
+ assert.equal(first.kind, 'delivery')
88
+ assert.match(first.document, /\*\*CI:\*\* Passed/)
89
+ assert.equal(git('--git-dir=' + remote, 'rev-parse', 'refs/heads/workflow/issue-7'), sha)
90
+ m.delivery.push({ pr: url, head: sha, advisory: 'Pending' })
91
+ assert.deepEqual(publishCandidate(m, store, bundle), first)
92
+ const changed = JSON.parse(readFileSync(pr, 'utf8'))
93
+ changed.statusCheckRollup.push({ name: 'OpenCodeReview (advisory)', status: 'IN_PROGRESS' })
94
+ writeFileSync(pr, JSON.stringify(changed))
95
+ const pendingAdvisory = publishCandidate(m, store, bundle)
96
+ assert.match(pendingAdvisory.document, /\*\*CI:\*\* Passed/)
97
+ assert.match(pendingAdvisory.document, /\*\*Advisory review:\*\* Pending/)
98
+ const disabled = { name: 'Verify (project CI or setup required)', conclusion: 'SKIPPED' }
99
+ changed.statusCheckRollup.push(disabled)
100
+ writeFileSync(pr, JSON.stringify(changed))
101
+ assert.match(publishCandidate(m, store, bundle).document, /CI:\*\* Passed/)
102
+ writeFileSync(pr, JSON.stringify({ ...changed, statusCheckRollup: [disabled] }))
103
+ assert.match(publishCandidate(m, store, bundle).document, /CI:\*\* Pending/)
104
+ const skipped = { name: 'docs only', conclusion: 'SKIPPED' }
105
+ const conditionalCI = (jobs) => {
106
+ writeFileSync(pr, JSON.stringify({ ...changed, statusCheckRollup: [skipped, ...jobs] }))
107
+ return publishCandidate(m, store, bundle).document
108
+ }
109
+ assert.match(conditionalCI([]), /CI:\*\* Pending/)
110
+ assert.match(conditionalCI([{ name: 'target', conclusion: 'SUCCESS' }]), /CI:\*\* Passed/)
111
+ assert.match(conditionalCI([{ name: 'target', status: 'IN_PROGRESS' }]), /CI:\*\* Pending/)
112
+ assert.match(conditionalCI([{ name: 'target', conclusion: 'FAILURE' }]), /CI:\*\* Failed/)
113
+ const operator =
114
+ 'https://github.com/example/demo/issues/7\n**PR:** ' +
115
+ url +
116
+ '\n**Head:** ' +
117
+ sha +
118
+ '\n**CI:** Passed\n**Advisory review:** Resolved\n## Evidence\nChecked findings.'
119
+ changed.statusCheckRollup[0].conclusion = 'FAILURE'
120
+ writeFileSync(pr, JSON.stringify(changed))
121
+ const resolved = publishCandidate(m, store, bundle, operator)
122
+ assert.match(resolved.document, /CI:\*\* Failed/)
123
+ m.delivery.push({ pr: url, head: sha, advisory: 'Resolved', file: 'resolved.md' })
124
+ writeFileSync(store.artifact('resolved.md'), resolved.document + '\n')
125
+ assert.deepEqual(publishCandidate(m, store, bundle), resolved)
126
+ changed.statusCheckRollup[0].conclusion = 'SUCCESS'
127
+ writeFileSync(pr, JSON.stringify(changed))
128
+ const refreshed = publishCandidate(m, store, bundle)
129
+ assert.match(refreshed.document, /CI:\*\* Passed/)
130
+ assert.match(refreshed.document, /Checked findings\./)
131
+ assert.throws(
132
+ () => publishCandidate(m, store, bundle, operator.replace('/issues/7', '/issues/70')),
133
+ /must reference/,
134
+ )
135
+ changed.headRefOid = base
136
+ writeFileSync(pr, JSON.stringify(changed))
137
+ const moved = publishCandidate(m, store, bundle, operator)
138
+ assert.equal(moved.kind, 'head-changed')
139
+ assert.doesNotMatch(moved.document, /Checked findings\./)
140
+ assert.match(moved.document, /Advisory review:\*\* Pending/)
141
+ // The repair push succeeded before the preceding invocation could save its receipt.
142
+ git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'repair', '--allow-empty')
143
+ const repaired = git('rev-parse', 'HEAD')
144
+ git('push', remote, 'HEAD:refs/heads/workflow/issue-7')
145
+ changed.headRefOid = repaired
146
+ changed.body += '\n\nOperator note.'
147
+ writeFileSync(pr, JSON.stringify(changed))
148
+ writeFileSync(store.artifact('new-checks.md'), 'Repaired checks pass.')
149
+ m.candidates.push({ ...m.candidates[0], sha: repaired, evidence: 'new-checks.md' })
150
+ publishCandidate(m, store, bundle)
151
+ const edited = JSON.parse(readFileSync(pr, 'utf8')).body
152
+ assert.ok(edited.includes('Reviewed commit: ' + repaired) && edited.includes('Repaired checks pass.'))
153
+ assert.ok(edited.includes('Operator note.') && !edited.includes('Reviewed commit: ' + sha))
154
+ })
@@ -0,0 +1,184 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from 'node:fs'
3
+ import { tmpdir } from 'node:os'
4
+ import { posix, join } from 'node:path'
5
+ import { field } from '../mission/transitions.mjs'
6
+ import { checkHandoff } from './handoff.mjs'
7
+ import { roleSession } from './role-session.mjs'
8
+
9
+ function startWorkspace(docker, image, root, source, p) {
10
+ const relative = posix.relative(root, p.workspace)
11
+ if (!relative.startsWith('role-workspaces/') || relative.includes(','))
12
+ throw new Error('Invalid workspace from builder.')
13
+ const mount =
14
+ 'type=bind,src=' + posix.join(source, relative) + ',dst=' + p.workspace + (p.readonly ? ',readonly' : '')
15
+ const identity = p.author
16
+ ? [
17
+ '-e',
18
+ 'GIT_AUTHOR_NAME=' + p.author.name,
19
+ '-e',
20
+ 'GIT_COMMITTER_NAME=' + p.author.name,
21
+ '-e',
22
+ 'GIT_AUTHOR_EMAIL=' + p.author.email,
23
+ '-e',
24
+ 'GIT_COMMITTER_EMAIL=' + p.author.email,
25
+ ]
26
+ : []
27
+ return docker([
28
+ 'run',
29
+ '-d',
30
+ '--rm',
31
+ '--read-only',
32
+ '--cap-drop=ALL',
33
+ '--security-opt=no-new-privileges',
34
+ '--tmpfs',
35
+ '/tmp:mode=1777',
36
+ '-e',
37
+ 'HOME=/tmp',
38
+ ...identity,
39
+ '-e',
40
+ 'GIT_CONFIG_COUNT=1',
41
+ '-e',
42
+ 'GIT_CONFIG_KEY_0=safe.directory',
43
+ '-e',
44
+ 'GIT_CONFIG_VALUE_0=' + p.workspace,
45
+ '--mount',
46
+ mount,
47
+ '-w',
48
+ p.workspace,
49
+ '--entrypoint',
50
+ 'sleep',
51
+ image,
52
+ '900',
53
+ ])
54
+ }
55
+
56
+ function copyBundle(docker, box, writer, writerStaging) {
57
+ const temp = mkdtempSync(join(tmpdir(), 'ew-candidate-'))
58
+ const file = join(temp, 'candidate.bundle')
59
+ try {
60
+ const fd = openSync(file, 'wx', 0o600)
61
+ try {
62
+ execFileSync('docker', ['exec', box, 'git', 'bundle', 'create', '-', 'HEAD'], {
63
+ stdio: ['ignore', fd, 'inherit'],
64
+ })
65
+ } finally {
66
+ closeSync(fd)
67
+ }
68
+ docker(['cp', file, writer + ':' + writerStaging + '/candidate.bundle'])
69
+ docker(['exec', '-u', '0', writer, 'chown', 'openhands', writerStaging + '/candidate.bundle'])
70
+ } finally {
71
+ rmSync(temp, { recursive: true, force: true })
72
+ }
73
+ }
74
+
75
+ export function checkoutReview(git, workspace, bundle, sha) {
76
+ git(['init', '-q', workspace])
77
+ git(['-C', workspace, 'fetch', '--no-tags', bundle, 'HEAD'])
78
+ git(['-C', workspace, 'checkout', '--detach', sha])
79
+ }
80
+
81
+ function verifyStartingPoint(p, git) {
82
+ if (['review', 'repair'].includes(p.stage) && git('rev-parse', 'HEAD') !== p.candidate)
83
+ throw new Error('Workspace HEAD differs from the recorded candidate. Reconcile it before resuming.')
84
+ if (['implementation', 'repair'].includes(p.stage)) {
85
+ const expected = p.stage === 'repair' ? p.candidate : p.base
86
+ if (
87
+ git('branch', '--show-current') !== p.branch ||
88
+ git('status', '--porcelain') ||
89
+ (expected !== 'unborn' && git('rev-parse', 'HEAD') !== expected)
90
+ )
91
+ throw new Error('Implementation workspace changed. Inspect and reconcile the existing work before retrying.')
92
+ }
93
+ }
94
+
95
+ export function validatedKind(p, git, document, url) {
96
+ let kind = p.kind
97
+ if (kind === 'brief' && /^## Question$/m.test(document)) kind = 'investigation-question'
98
+ if (kind === 'brief') {
99
+ const template = new URL(
100
+ '../.agents/skills/workflow-investigate/references/investigation-brief.md',
101
+ import.meta.url,
102
+ )
103
+ checkHandoff(document, readFileSync(template, 'utf8'), url, false)
104
+ if (p.base !== 'unborn' && !document.includes(p.base))
105
+ throw new Error('Brief must identify the inspected commit.')
106
+ }
107
+ if (kind === 'plan' && /^## Question$/m.test(document)) kind = 'planning-question'
108
+ if (kind === 'plan') {
109
+ const template = new URL('../.agents/skills/workflow-plan/references/implementation-plan.md', import.meta.url)
110
+ checkHandoff(document, readFileSync(template, 'utf8'), url, true, p.briefName)
111
+ }
112
+ if (kind === 'repair' || kind === 'candidate') {
113
+ const sha = git('rev-parse', 'HEAD')
114
+ const start = kind === 'repair' ? p.candidate : p.base
115
+ if (sha === start) throw new Error('No new candidate commit was produced. Resume to retry the developer session.')
116
+ git('merge-base', '--is-ancestor', start, sha)
117
+ if (
118
+ git('status', '--porcelain') ||
119
+ git('branch', '--show-current') !== p.branch ||
120
+ field(document, 'Candidate commit') !== sha ||
121
+ field(document, 'Worktree') !== p.workspace ||
122
+ field(document, 'Branch') !== p.branch
123
+ )
124
+ throw new Error('Handoff differs from the observed candidate workspace.')
125
+ }
126
+ if (kind === 'review' && field(document, 'Base commit') !== p.base)
127
+ throw new Error('Review did not identify the starting commit.')
128
+ return kind
129
+ }
130
+
131
+ export async function drive({ docker, stage, writer, reader, staging, writerStaging, root, source, runRole = roleSession }) {
132
+ const image = docker(['inspect', '--format', '{{.Image}}', reader])
133
+ while (true) {
134
+ const p = JSON.parse(stage(writer, 'packet'))
135
+ if (!p.kind) return stage(writer, 'resume')
136
+ let box
137
+ try {
138
+ if (p.reviewSource) {
139
+ const input = startWorkspace(docker, image, root, source, { ...p, workspace: p.reviewSource })
140
+ try {
141
+ copyBundle(docker, input, writer, writerStaging)
142
+ } finally {
143
+ docker(['rm', '-f', input])
144
+ }
145
+ checkoutReview(
146
+ (args) => docker(['exec', writer, 'git', ...args]),
147
+ p.workspace,
148
+ writerStaging + '/candidate.bundle',
149
+ p.candidate,
150
+ )
151
+ }
152
+ if (!p.refresh) box = startWorkspace(docker, image, root, source, p)
153
+ const git = (...args) => docker(['exec', box, 'git', ...args])
154
+ if (p.kind === 'delivery') {
155
+ if (!p.refresh && git('rev-parse', 'HEAD') !== p.candidate)
156
+ throw new Error('Delivery workspace differs from reviewed candidate.')
157
+ if (!p.refresh) copyBundle(docker, box, writer, writerStaging)
158
+ const status = stage(writer, 'deliver', { revision: p.revision })
159
+ if (status.split('\n')[0].includes(' · delivery-head-changed · ')) continue
160
+ return status
161
+ }
162
+ let document = p.captured
163
+ if (document && ['candidate', 'repair'].includes(p.kind)) {
164
+ const start = p.kind === 'repair' ? p.candidate : p.base
165
+ if (git('rev-parse', 'HEAD') === start) document = undefined
166
+ }
167
+ if (!document) {
168
+ verifyStartingPoint(p, git)
169
+ document = await runRole(reader, staging, p.prompt, box)
170
+ stage(writer, 'capture', { revision: p.revision, document })
171
+ }
172
+ const kind = validatedKind(p, git, document, p.url)
173
+ console.error(stage(writer, 'result', { kind, revision: p.revision, document }))
174
+ } catch (error) {
175
+ const reason =
176
+ typeof error.status === 'number' ? 'Builder operation failed with exit ' + error.status : error.message
177
+ stage(writer, 'failure', { revision: p.revision, reason })
178
+ throw new Error(p.stage + ' at revision ' + p.revision + ': ' + reason)
179
+ } finally {
180
+ if (box) docker(['rm', '-f', box])
181
+ if (p.scratch) docker(['exec', writer, 'rm', '-rf', '--', posix.dirname(p.workspace)])
182
+ }
183
+ }
184
+ }