@sockulags/agent-os 0.9.1 → 0.12.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 (42) hide show
  1. package/README.md +112 -67
  2. package/cli/index.mjs +299 -12
  3. package/cli/index.test.mjs +277 -3
  4. package/hooks/hooks.json +17 -0
  5. package/package.json +6 -3
  6. package/policy.md +42 -40
  7. package/skills/batch-work/SKILL.md +43 -43
  8. package/skills/batch-work/agents/openai.yaml +2 -2
  9. package/skills/batch-work/references/manifest.md +100 -100
  10. package/skills/batch-work/scripts/manifest-hash.mjs +263 -263
  11. package/skills/batch-work/scripts/test-manifest-hash.mjs +132 -132
  12. package/skills/chart-work/SKILL.md +37 -37
  13. package/skills/chart-work/references/elicitation.md +25 -25
  14. package/skills/chart-work/references/map.md +84 -84
  15. package/skills/chart-work/references/prototypes.md +21 -21
  16. package/skills/check-work/SKILL.md +61 -0
  17. package/skills/deliver-work/SKILL.md +12 -12
  18. package/skills/deliver-work/workflow.md +119 -109
  19. package/skills/diagnose-before-fix/SKILL.md +24 -24
  20. package/skills/dispatch-next/SKILL.md +28 -28
  21. package/skills/init-agent-os/SKILL.md +52 -37
  22. package/skills/init-agent-os/references/repository-init.md +74 -0
  23. package/skills/list-skills/SKILL.md +43 -0
  24. package/skills/list-skills/agents/openai.yaml +2 -0
  25. package/skills/plain-voice/SKILL.md +39 -0
  26. package/skills/plain-voice/references/tells.md +82 -0
  27. package/skills/proportional-testing/SKILL.md +30 -0
  28. package/skills/proportional-testing/references/strategy.md +75 -0
  29. package/skills/quality-ratchet/SKILL.md +50 -0
  30. package/skills/quality-ratchet/scripts/quality-delta.mjs +752 -0
  31. package/skills/quality-ratchet/scripts/quality-delta.test.mjs +514 -0
  32. package/skills/scope-guard/SKILL.md +21 -21
  33. package/skills/shape-work/SKILL.md +39 -39
  34. package/skills/shape-work/references/implementation-issues.md +69 -69
  35. package/skills/shape-work/references/mockups.md +23 -23
  36. package/skills/simplifier/SKILL.md +34 -0
  37. package/skills/simplifier/agents/openai.yaml +2 -0
  38. package/skills/simplifier-audit/SKILL.md +28 -0
  39. package/skills/simplifier-audit/agents/openai.yaml +2 -0
  40. package/skills/simplifier-review/SKILL.md +36 -0
  41. package/skills/verify-before-done/SKILL.md +29 -29
  42. package/skills/writing-skills/SKILL.md +68 -68
@@ -1,263 +1,263 @@
1
- #!/usr/bin/env node
2
-
3
- import crypto from 'node:crypto'
4
- import fs from 'node:fs'
5
- import path from 'node:path'
6
- import process from 'node:process'
7
- import { pathToFileURL } from 'node:url'
8
-
9
- export const planFields = [
10
- 'baseline_sha',
11
- 'integration_branch',
12
- 'max_workers',
13
- 'retry_limit',
14
- 'integration_strategy',
15
- 'aggregate_checks'
16
- ]
17
-
18
- export const taskFields = [
19
- 'task_key',
20
- 'source',
21
- 'dependencies',
22
- 'scope',
23
- 'outcome',
24
- 'non_goals',
25
- 'checks',
26
- 'task_hash'
27
- ]
28
-
29
- export const runtimeFields = [
30
- 'task_key',
31
- 'state',
32
- 'attempt',
33
- 'branch',
34
- 'worktree',
35
- 'worker_id',
36
- 'head_sha',
37
- 'result'
38
- ]
39
-
40
- const cursorFields = ['agent_os_batch', 'batch_id', 'status', 'next_action', 'manifest_hash']
41
- const batchStates = ['planned', 'running', 'reconciling', 'verifying', 'ready', 'delivered', 'blocked']
42
- const taskStates = ['pending', 'ready', 'running', 'succeeded', 'integrated', 'failed', 'blocked', 'conflict']
43
-
44
- function stable(value) {
45
- if (Array.isArray(value)) return value.map(stable)
46
- if (value && typeof value === 'object') {
47
- return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stable(value[key])]))
48
- }
49
- return typeof value === 'string' ? value.replace(/\r\n/g, '\n') : value
50
- }
51
-
52
- function digest(value) {
53
- return crypto.createHash('sha256').update(JSON.stringify(stable(value))).digest('hex')
54
- }
55
-
56
- function exactFields(value, expected, label) {
57
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`)
58
- const actual = Object.keys(value).sort()
59
- const wanted = [...expected].sort()
60
- if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
61
- throw new Error(`${label} fields must be exactly: ${expected.join(', ')}`)
62
- }
63
- }
64
-
65
- function string(value, label, { empty = false } = {}) {
66
- if (typeof value !== 'string' || (!empty && !value.trim())) throw new Error(`${label} must be a ${empty ? '' : 'non-empty '}string`)
67
- }
68
-
69
- function strings(value, label) {
70
- if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item.trim())) {
71
- throw new Error(`${label} must be an array of non-empty strings`)
72
- }
73
- }
74
-
75
- function unquote(value) {
76
- const trimmed = value.trim()
77
- if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
78
- (trimmed.startsWith("'") && trimmed.endsWith("'"))) return trimmed.slice(1, -1)
79
- return trimmed
80
- }
81
-
82
- export function parseCursor(content) {
83
- const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/)
84
- if (!match) throw new Error('manifest must start with YAML frontmatter')
85
- const cursor = {}
86
- for (const line of match[1].split(/\r?\n/)) {
87
- const separator = line.indexOf(':')
88
- if (separator < 1) throw new Error(`invalid cursor line: ${line}`)
89
- const key = line.slice(0, separator).trim()
90
- if (key in cursor) throw new Error(`duplicate cursor field: ${key}`)
91
- cursor[key] = unquote(line.slice(separator + 1))
92
- }
93
- exactFields(cursor, cursorFields, 'cursor')
94
- if (cursor.agent_os_batch !== '2') throw new Error('agent_os_batch must be 2')
95
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(cursor.batch_id)) throw new Error('batch_id must be kebab-case')
96
- if (!batchStates.includes(cursor.status)) throw new Error(`invalid batch status: ${cursor.status}`)
97
- if (cursor.status !== 'delivered') string(cursor.next_action, 'next_action')
98
- string(cursor.manifest_hash, 'manifest_hash', { empty: true })
99
- return cursor
100
- }
101
-
102
- function blocks(content) {
103
- const found = { plan: [], task: [], runtime: [] }
104
- for (const match of content.matchAll(/```json batch-(plan|task|runtime)\r?\n([\s\S]*?)\r?\n```/g)) {
105
- try {
106
- found[match[1]].push(JSON.parse(match[2]))
107
- } catch (error) {
108
- throw new Error(`invalid batch-${match[1]} JSON: ${error.message}`)
109
- }
110
- }
111
- return found
112
- }
113
-
114
- export function parsePlan(value) {
115
- exactFields(value, planFields, 'batch plan')
116
- string(value.baseline_sha, 'baseline_sha')
117
- string(value.integration_branch, 'integration_branch')
118
- if (!Number.isInteger(value.max_workers) || value.max_workers < 1) throw new Error('max_workers must be a positive integer')
119
- if (!Number.isInteger(value.retry_limit) || value.retry_limit < 0) throw new Error('retry_limit must be a non-negative integer')
120
- string(value.integration_strategy, 'integration_strategy')
121
- strings(value.aggregate_checks, 'aggregate_checks')
122
- return value
123
- }
124
-
125
- function parseTask(value) {
126
- exactFields(value, taskFields, `task ${value?.task_key ?? '<unknown>'}`)
127
- string(value.task_key, 'task_key')
128
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.task_key)) throw new Error(`${value.task_key}: task_key must be kebab-case`)
129
- string(value.source, `${value.task_key}: source`)
130
- strings(value.dependencies, `${value.task_key}: dependencies`)
131
- strings(value.scope, `${value.task_key}: scope`)
132
- string(value.outcome, `${value.task_key}: outcome`)
133
- strings(value.non_goals, `${value.task_key}: non_goals`)
134
- strings(value.checks, `${value.task_key}: checks`)
135
- string(value.task_hash, `${value.task_key}: task_hash`, { empty: true })
136
- return value
137
- }
138
-
139
- function validateGraph(tasks) {
140
- const keys = new Set()
141
- for (const task of tasks) {
142
- if (keys.has(task.task_key)) throw new Error(`duplicate task_key: ${task.task_key}`)
143
- keys.add(task.task_key)
144
- }
145
- for (const task of tasks) {
146
- for (const dependency of task.dependencies) {
147
- if (!keys.has(dependency)) throw new Error(`${task.task_key}: unknown dependency ${dependency}`)
148
- if (dependency === task.task_key) throw new Error(`${task.task_key}: self dependency`)
149
- }
150
- }
151
- const visiting = new Set()
152
- const visited = new Set()
153
- const byKey = new Map(tasks.map((task) => [task.task_key, task]))
154
- function visit(key) {
155
- if (visiting.has(key)) throw new Error(`dependency cycle at ${key}`)
156
- if (visited.has(key)) return
157
- visiting.add(key)
158
- for (const dependency of byKey.get(key).dependencies) visit(dependency)
159
- visiting.delete(key)
160
- visited.add(key)
161
- }
162
- for (const key of keys) visit(key)
163
- }
164
-
165
- function portable(value) {
166
- return !path.isAbsolute(value) && !/^[A-Za-z]:[\\/]/.test(value) && !value.startsWith('\\\\')
167
- }
168
-
169
- function parseRuntime(value, tasks) {
170
- exactFields(value, ['tasks'], 'batch runtime')
171
- if (!Array.isArray(value.tasks)) throw new Error('batch runtime tasks must be an array')
172
- const definitions = new Map(tasks.map((task) => [task.task_key, task]))
173
- const seen = new Set()
174
- const states = new Map()
175
- for (const item of value.tasks) {
176
- exactFields(item, runtimeFields, `runtime ${item?.task_key ?? '<unknown>'}`)
177
- if (!definitions.has(item.task_key)) throw new Error(`runtime has unknown task ${item.task_key}`)
178
- if (seen.has(item.task_key)) throw new Error(`runtime duplicates task ${item.task_key}`)
179
- seen.add(item.task_key)
180
- if (!taskStates.includes(item.state)) throw new Error(`${item.task_key}: invalid runtime state ${item.state}`)
181
- if (!Number.isInteger(item.attempt) || item.attempt < 0) throw new Error(`${item.task_key}: attempt must be a non-negative integer`)
182
- for (const field of ['branch', 'worktree', 'worker_id', 'head_sha', 'result']) string(item[field], `${item.task_key}: ${field}`, { empty: true })
183
- if (item.worktree && !portable(item.worktree)) throw new Error(`${item.task_key}: worktree must be portable`)
184
- if (['ready', 'running'].includes(item.state) && (!item.attempt || !item.branch || !item.worktree)) {
185
- throw new Error(`${item.task_key}: active task requires attempt, branch, and worktree`)
186
- }
187
- if (item.state === 'running' && !item.worker_id) throw new Error(`${item.task_key}: running task requires worker_id`)
188
- if (['succeeded', 'integrated'].includes(item.state) && !item.head_sha) throw new Error(`${item.task_key}: completed task requires head_sha`)
189
- states.set(item.task_key, item.state)
190
- }
191
- if (seen.size !== tasks.length) throw new Error('runtime must contain exactly one entry per task')
192
- for (const item of value.tasks) {
193
- if (['ready', 'running', 'succeeded', 'integrated'].includes(item.state)) {
194
- for (const dependency of definitions.get(item.task_key).dependencies) {
195
- if (states.get(dependency) !== 'integrated') throw new Error(`${item.task_key}: dependency ${dependency} is not integrated`)
196
- }
197
- }
198
- }
199
- return value
200
- }
201
-
202
- export function parseManifest(content) {
203
- const cursor = parseCursor(content)
204
- const found = blocks(content)
205
- if (found.plan.length !== 1) throw new Error('manifest requires exactly one batch-plan block')
206
- if (!found.task.length) throw new Error('manifest requires at least one batch-task block')
207
- if (found.runtime.length !== 1) throw new Error('manifest requires exactly one batch-runtime block')
208
- const plan = parsePlan(found.plan[0])
209
- const tasks = found.task.map(parseTask)
210
- validateGraph(tasks)
211
- const runtime = parseRuntime(found.runtime[0], tasks)
212
- return { cursor, plan, tasks, runtime }
213
- }
214
-
215
- export function hashTask(task) {
216
- const definition = Object.fromEntries(taskFields.filter((field) => field !== 'task_hash').map((field) => [field, task[field]]))
217
- return digest(definition)
218
- }
219
-
220
- export function hashManifest(batchId, plan, tasks) {
221
- return digest({
222
- batch_id: batchId,
223
- plan,
224
- tasks: tasks.map((task) => [task.task_key, hashTask(task)]).sort(([left], [right]) => left.localeCompare(right))
225
- })
226
- }
227
-
228
- export function checkManifest(content) {
229
- const parsed = parseManifest(content)
230
- const taskHashes = Object.fromEntries(parsed.tasks.map((task) => [task.task_key, hashTask(task)]))
231
- const manifestHash = hashManifest(parsed.cursor.batch_id, parsed.plan, parsed.tasks)
232
- const mismatches = []
233
- for (const task of parsed.tasks) {
234
- if (task.task_hash !== taskHashes[task.task_key]) mismatches.push(`${task.task_key}: task_hash mismatch`)
235
- }
236
- if (parsed.cursor.manifest_hash !== manifestHash) mismatches.push('manifest_hash mismatch')
237
- return { ...parsed, calculated: { task_hashes: taskHashes, manifest_hash: manifestHash }, mismatches }
238
- }
239
-
240
- function main() {
241
- const args = process.argv.slice(2)
242
- const check = args[0] === '--check'
243
- const file = check ? args[1] : args[0]
244
- if (!file || args.length !== (check ? 2 : 1)) {
245
- console.error('Usage: manifest-hash.mjs [--check] <manifest.md>')
246
- process.exitCode = 2
247
- return
248
- }
249
- try {
250
- const result = checkManifest(fs.readFileSync(file, 'utf8'))
251
- if (check && result.mismatches.length) {
252
- for (const mismatch of result.mismatches) console.error(mismatch)
253
- process.exitCode = 1
254
- return
255
- }
256
- console.log(JSON.stringify(result.calculated, null, 2))
257
- } catch (error) {
258
- console.error(error.message)
259
- process.exitCode = 2
260
- }
261
- }
262
-
263
- if (import.meta.url === pathToFileURL(process.argv[1]).href) main()
1
+ #!/usr/bin/env node
2
+
3
+ import crypto from 'node:crypto'
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import process from 'node:process'
7
+ import { pathToFileURL } from 'node:url'
8
+
9
+ export const planFields = [
10
+ 'baseline_sha',
11
+ 'integration_branch',
12
+ 'max_workers',
13
+ 'retry_limit',
14
+ 'integration_strategy',
15
+ 'aggregate_checks'
16
+ ]
17
+
18
+ export const taskFields = [
19
+ 'task_key',
20
+ 'source',
21
+ 'dependencies',
22
+ 'scope',
23
+ 'outcome',
24
+ 'non_goals',
25
+ 'checks',
26
+ 'task_hash'
27
+ ]
28
+
29
+ export const runtimeFields = [
30
+ 'task_key',
31
+ 'state',
32
+ 'attempt',
33
+ 'branch',
34
+ 'worktree',
35
+ 'worker_id',
36
+ 'head_sha',
37
+ 'result'
38
+ ]
39
+
40
+ const cursorFields = ['agent_os_batch', 'batch_id', 'status', 'next_action', 'manifest_hash']
41
+ const batchStates = ['planned', 'running', 'reconciling', 'verifying', 'ready', 'delivered', 'blocked']
42
+ const taskStates = ['pending', 'ready', 'running', 'succeeded', 'integrated', 'failed', 'blocked', 'conflict']
43
+
44
+ function stable(value) {
45
+ if (Array.isArray(value)) return value.map(stable)
46
+ if (value && typeof value === 'object') {
47
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stable(value[key])]))
48
+ }
49
+ return typeof value === 'string' ? value.replace(/\r\n/g, '\n') : value
50
+ }
51
+
52
+ function digest(value) {
53
+ return crypto.createHash('sha256').update(JSON.stringify(stable(value))).digest('hex')
54
+ }
55
+
56
+ function exactFields(value, expected, label) {
57
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`)
58
+ const actual = Object.keys(value).sort()
59
+ const wanted = [...expected].sort()
60
+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
61
+ throw new Error(`${label} fields must be exactly: ${expected.join(', ')}`)
62
+ }
63
+ }
64
+
65
+ function string(value, label, { empty = false } = {}) {
66
+ if (typeof value !== 'string' || (!empty && !value.trim())) throw new Error(`${label} must be a ${empty ? '' : 'non-empty '}string`)
67
+ }
68
+
69
+ function strings(value, label) {
70
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item.trim())) {
71
+ throw new Error(`${label} must be an array of non-empty strings`)
72
+ }
73
+ }
74
+
75
+ function unquote(value) {
76
+ const trimmed = value.trim()
77
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) ||
78
+ (trimmed.startsWith("'") && trimmed.endsWith("'"))) return trimmed.slice(1, -1)
79
+ return trimmed
80
+ }
81
+
82
+ export function parseCursor(content) {
83
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/)
84
+ if (!match) throw new Error('manifest must start with YAML frontmatter')
85
+ const cursor = {}
86
+ for (const line of match[1].split(/\r?\n/)) {
87
+ const separator = line.indexOf(':')
88
+ if (separator < 1) throw new Error(`invalid cursor line: ${line}`)
89
+ const key = line.slice(0, separator).trim()
90
+ if (key in cursor) throw new Error(`duplicate cursor field: ${key}`)
91
+ cursor[key] = unquote(line.slice(separator + 1))
92
+ }
93
+ exactFields(cursor, cursorFields, 'cursor')
94
+ if (cursor.agent_os_batch !== '2') throw new Error('agent_os_batch must be 2')
95
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(cursor.batch_id)) throw new Error('batch_id must be kebab-case')
96
+ if (!batchStates.includes(cursor.status)) throw new Error(`invalid batch status: ${cursor.status}`)
97
+ if (cursor.status !== 'delivered') string(cursor.next_action, 'next_action')
98
+ string(cursor.manifest_hash, 'manifest_hash', { empty: true })
99
+ return cursor
100
+ }
101
+
102
+ function blocks(content) {
103
+ const found = { plan: [], task: [], runtime: [] }
104
+ for (const match of content.matchAll(/```json batch-(plan|task|runtime)\r?\n([\s\S]*?)\r?\n```/g)) {
105
+ try {
106
+ found[match[1]].push(JSON.parse(match[2]))
107
+ } catch (error) {
108
+ throw new Error(`invalid batch-${match[1]} JSON: ${error.message}`)
109
+ }
110
+ }
111
+ return found
112
+ }
113
+
114
+ export function parsePlan(value) {
115
+ exactFields(value, planFields, 'batch plan')
116
+ string(value.baseline_sha, 'baseline_sha')
117
+ string(value.integration_branch, 'integration_branch')
118
+ if (!Number.isInteger(value.max_workers) || value.max_workers < 1) throw new Error('max_workers must be a positive integer')
119
+ if (!Number.isInteger(value.retry_limit) || value.retry_limit < 0) throw new Error('retry_limit must be a non-negative integer')
120
+ string(value.integration_strategy, 'integration_strategy')
121
+ strings(value.aggregate_checks, 'aggregate_checks')
122
+ return value
123
+ }
124
+
125
+ function parseTask(value) {
126
+ exactFields(value, taskFields, `task ${value?.task_key ?? '<unknown>'}`)
127
+ string(value.task_key, 'task_key')
128
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.task_key)) throw new Error(`${value.task_key}: task_key must be kebab-case`)
129
+ string(value.source, `${value.task_key}: source`)
130
+ strings(value.dependencies, `${value.task_key}: dependencies`)
131
+ strings(value.scope, `${value.task_key}: scope`)
132
+ string(value.outcome, `${value.task_key}: outcome`)
133
+ strings(value.non_goals, `${value.task_key}: non_goals`)
134
+ strings(value.checks, `${value.task_key}: checks`)
135
+ string(value.task_hash, `${value.task_key}: task_hash`, { empty: true })
136
+ return value
137
+ }
138
+
139
+ function validateGraph(tasks) {
140
+ const keys = new Set()
141
+ for (const task of tasks) {
142
+ if (keys.has(task.task_key)) throw new Error(`duplicate task_key: ${task.task_key}`)
143
+ keys.add(task.task_key)
144
+ }
145
+ for (const task of tasks) {
146
+ for (const dependency of task.dependencies) {
147
+ if (!keys.has(dependency)) throw new Error(`${task.task_key}: unknown dependency ${dependency}`)
148
+ if (dependency === task.task_key) throw new Error(`${task.task_key}: self dependency`)
149
+ }
150
+ }
151
+ const visiting = new Set()
152
+ const visited = new Set()
153
+ const byKey = new Map(tasks.map((task) => [task.task_key, task]))
154
+ function visit(key) {
155
+ if (visiting.has(key)) throw new Error(`dependency cycle at ${key}`)
156
+ if (visited.has(key)) return
157
+ visiting.add(key)
158
+ for (const dependency of byKey.get(key).dependencies) visit(dependency)
159
+ visiting.delete(key)
160
+ visited.add(key)
161
+ }
162
+ for (const key of keys) visit(key)
163
+ }
164
+
165
+ function portable(value) {
166
+ return !path.isAbsolute(value) && !/^[A-Za-z]:[\\/]/.test(value) && !value.startsWith('\\\\')
167
+ }
168
+
169
+ function parseRuntime(value, tasks) {
170
+ exactFields(value, ['tasks'], 'batch runtime')
171
+ if (!Array.isArray(value.tasks)) throw new Error('batch runtime tasks must be an array')
172
+ const definitions = new Map(tasks.map((task) => [task.task_key, task]))
173
+ const seen = new Set()
174
+ const states = new Map()
175
+ for (const item of value.tasks) {
176
+ exactFields(item, runtimeFields, `runtime ${item?.task_key ?? '<unknown>'}`)
177
+ if (!definitions.has(item.task_key)) throw new Error(`runtime has unknown task ${item.task_key}`)
178
+ if (seen.has(item.task_key)) throw new Error(`runtime duplicates task ${item.task_key}`)
179
+ seen.add(item.task_key)
180
+ if (!taskStates.includes(item.state)) throw new Error(`${item.task_key}: invalid runtime state ${item.state}`)
181
+ if (!Number.isInteger(item.attempt) || item.attempt < 0) throw new Error(`${item.task_key}: attempt must be a non-negative integer`)
182
+ for (const field of ['branch', 'worktree', 'worker_id', 'head_sha', 'result']) string(item[field], `${item.task_key}: ${field}`, { empty: true })
183
+ if (item.worktree && !portable(item.worktree)) throw new Error(`${item.task_key}: worktree must be portable`)
184
+ if (['ready', 'running'].includes(item.state) && (!item.attempt || !item.branch || !item.worktree)) {
185
+ throw new Error(`${item.task_key}: active task requires attempt, branch, and worktree`)
186
+ }
187
+ if (item.state === 'running' && !item.worker_id) throw new Error(`${item.task_key}: running task requires worker_id`)
188
+ if (['succeeded', 'integrated'].includes(item.state) && !item.head_sha) throw new Error(`${item.task_key}: completed task requires head_sha`)
189
+ states.set(item.task_key, item.state)
190
+ }
191
+ if (seen.size !== tasks.length) throw new Error('runtime must contain exactly one entry per task')
192
+ for (const item of value.tasks) {
193
+ if (['ready', 'running', 'succeeded', 'integrated'].includes(item.state)) {
194
+ for (const dependency of definitions.get(item.task_key).dependencies) {
195
+ if (states.get(dependency) !== 'integrated') throw new Error(`${item.task_key}: dependency ${dependency} is not integrated`)
196
+ }
197
+ }
198
+ }
199
+ return value
200
+ }
201
+
202
+ export function parseManifest(content) {
203
+ const cursor = parseCursor(content)
204
+ const found = blocks(content)
205
+ if (found.plan.length !== 1) throw new Error('manifest requires exactly one batch-plan block')
206
+ if (!found.task.length) throw new Error('manifest requires at least one batch-task block')
207
+ if (found.runtime.length !== 1) throw new Error('manifest requires exactly one batch-runtime block')
208
+ const plan = parsePlan(found.plan[0])
209
+ const tasks = found.task.map(parseTask)
210
+ validateGraph(tasks)
211
+ const runtime = parseRuntime(found.runtime[0], tasks)
212
+ return { cursor, plan, tasks, runtime }
213
+ }
214
+
215
+ export function hashTask(task) {
216
+ const definition = Object.fromEntries(taskFields.filter((field) => field !== 'task_hash').map((field) => [field, task[field]]))
217
+ return digest(definition)
218
+ }
219
+
220
+ export function hashManifest(batchId, plan, tasks) {
221
+ return digest({
222
+ batch_id: batchId,
223
+ plan,
224
+ tasks: tasks.map((task) => [task.task_key, hashTask(task)]).sort(([left], [right]) => left.localeCompare(right))
225
+ })
226
+ }
227
+
228
+ export function checkManifest(content) {
229
+ const parsed = parseManifest(content)
230
+ const taskHashes = Object.fromEntries(parsed.tasks.map((task) => [task.task_key, hashTask(task)]))
231
+ const manifestHash = hashManifest(parsed.cursor.batch_id, parsed.plan, parsed.tasks)
232
+ const mismatches = []
233
+ for (const task of parsed.tasks) {
234
+ if (task.task_hash !== taskHashes[task.task_key]) mismatches.push(`${task.task_key}: task_hash mismatch`)
235
+ }
236
+ if (parsed.cursor.manifest_hash !== manifestHash) mismatches.push('manifest_hash mismatch')
237
+ return { ...parsed, calculated: { task_hashes: taskHashes, manifest_hash: manifestHash }, mismatches }
238
+ }
239
+
240
+ function main() {
241
+ const args = process.argv.slice(2)
242
+ const check = args[0] === '--check'
243
+ const file = check ? args[1] : args[0]
244
+ if (!file || args.length !== (check ? 2 : 1)) {
245
+ console.error('Usage: manifest-hash.mjs [--check] <manifest.md>')
246
+ process.exitCode = 2
247
+ return
248
+ }
249
+ try {
250
+ const result = checkManifest(fs.readFileSync(file, 'utf8'))
251
+ if (check && result.mismatches.length) {
252
+ for (const mismatch of result.mismatches) console.error(mismatch)
253
+ process.exitCode = 1
254
+ return
255
+ }
256
+ console.log(JSON.stringify(result.calculated, null, 2))
257
+ } catch (error) {
258
+ console.error(error.message)
259
+ process.exitCode = 2
260
+ }
261
+ }
262
+
263
+ if (import.meta.url === pathToFileURL(process.argv[1]).href) main()