-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcheckpoint-proof.mjs
More file actions
392 lines (375 loc) · 13 KB
/
Copy pathcheckpoint-proof.mjs
File metadata and controls
392 lines (375 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import {
assertRunId,
defaultGitHubApi,
parsePullCommentUrl,
readJson,
runDirectory,
sameGitHubLogin,
} from './common.mjs'
const ACTIVE_STATUSES = new Set(['running', 'waiting_for_owner', 'awaiting_owner_review'])
export function checkpointWorktreeHead(record) {
let expectedHead = record?.run?.baseSha
for (const event of record?.events ?? []) {
if (event.type === 'implementation_completed' && event.status === 'passed') {
expectedHead = event.payload?.commitSha
}
if (event.type === 'pr_published') expectedHead = event.payload?.headSha
}
if (!/^[0-9a-f]{40}$/i.test(expectedHead ?? '')) {
throw new Error('durable active checkpoint has no valid working head')
}
return expectedHead
}
export async function checkpointJournalConfiguration(loopRoot) {
const channel = await readJson(
path.resolve(loopRoot, '..', '_shared', 'owner-channel', 'channel.json'),
)
if (
!Number.isInteger(channel.stateIssueNumber) ||
channel.stateIssueNumber < 1 ||
!channel.automationGitHubLogin
) {
throw new Error('owner channel must configure stateIssueNumber and automationGitHubLogin')
}
const [owner, repo] = channel.repository.split('/')
return { channel, owner, repo }
}
function canonicalRun(run) {
return {
schemaVersion: run.schemaVersion,
runId: run.runId,
issueNumber: run.issueNumber,
issueTitle: run.issueTitle,
issueUrl: run.issueUrl,
baseBranch: run.baseBranch,
baseSha: run.baseSha,
branch: run.branch,
status: run.status,
startedAt: run.startedAt,
finishedAt: run.finishedAt,
prUrl: run.prUrl,
headSha: run.headSha,
mergeSha: run.mergeSha,
issueSnapshot: run.issueSnapshot,
briefDigest: run.briefDigest,
uiEvidenceRequired: run.uiEvidenceRequired,
implementationCommit: run.implementationCommit,
}
}
function canonicalEvent(event) {
return {
schemaVersion: event.schemaVersion,
runId: event.runId,
type: event.type,
timestamp: event.timestamp,
status: event.status,
payload: event.payload,
}
}
function permittedArtifactPath(runId, relativePath) {
if (
typeof relativePath !== 'string' ||
path.isAbsolute(relativePath) ||
relativePath.split(/[\\/]/).includes('..')
) {
return false
}
const normalized = relativePath.split(path.sep).join('/')
return (
normalized.startsWith(`logs/runs/${runId}/`) ||
normalized.startsWith(`evidence/${runId}/`) ||
normalized.startsWith(`handoffs/${runId}/`)
)
}
function artifactReferencesFromEvents(events) {
const references = new Map()
const add = (relativePath, digest) => {
if (!relativePath) return
const existing = references.get(relativePath)
if (existing && digest && existing !== digest) {
throw new Error(`checkpoint artifact has conflicting digests: ${relativePath}`)
}
references.set(relativePath, digest ?? existing ?? null)
}
for (const event of events) {
if (event.type === 'implementation_completed' && event.payload?.resultPath) {
add(event.payload.resultPath, event.payload.resultDigest)
}
if (event.type === 'verification_completed' && event.payload?.manifestPath) {
add(event.payload.manifestPath, event.payload.manifestDigest)
}
if (event.type === 'review_completed' && event.payload?.resultPath) {
add(event.payload.resultPath, event.payload.resultDigest)
}
if (event.type === 'finalization_published' && event.payload?.resultPath) {
add(event.payload.resultPath, event.payload.resultDigest)
}
}
return [...references].sort(([left], [right]) => left.localeCompare(right))
}
export async function checkpointArtifactsForEvents({ loopRoot, runId, events }) {
const artifacts = []
for (const [relativePath, expectedDigest] of artifactReferencesFromEvents(events)) {
if (!permittedArtifactPath(runId, relativePath)) {
throw new Error(`checkpoint artifact path is outside the run: ${relativePath}`)
}
const source = await readFile(path.resolve(loopRoot, relativePath), 'utf8')
const sha256 = createHash('sha256').update(source).digest('hex')
if (expectedDigest !== sha256) {
throw new Error(`checkpoint artifact no longer matches its event: ${relativePath}`)
}
artifacts.push({
path: relativePath.split(path.sep).join('/'),
sha256,
source,
})
}
return artifacts
}
export function canonicalCheckpointRecord(record) {
return JSON.stringify({
schemaVersion: 1,
kind: 'active-checkpoint',
run: canonicalRun(record.run),
briefSource: record.briefSource,
events: record.events.map(canonicalEvent),
artifacts: record.artifacts.map((artifact) => ({
path: artifact.path,
sha256: artifact.sha256,
source: artifact.source,
})),
updatedAt: record.updatedAt,
})
}
export function checkpointRecordDigest(record) {
return createHash('sha256').update(canonicalCheckpointRecord(record)).digest('hex')
}
function validateImplementationBoundary(record) {
const { run, events, artifacts } = record
if (run.implementationCommit === null) return
if (!/^[0-9a-f]{40}$/i.test(run.implementationCommit ?? '') || !run.briefDigest) {
throw new Error('active checkpoint has an invalid $implement boundary')
}
const matches = events.filter(
(event) =>
event.type === 'implementation_completed' &&
event.status === 'passed' &&
event.payload?.agent === '$implement' &&
event.payload?.commitSha === run.implementationCommit &&
event.payload?.briefDigest === run.briefDigest,
)
if (matches.length !== 1) {
throw new Error('active checkpoint $implement commit lacks one matching durable event')
}
const event = matches[0]
const resultPath = event.payload?.resultPath
const resultDigest = event.payload?.resultDigest
const artifact = artifacts.find((candidate) => candidate.path === resultPath)
if (
typeof resultPath !== 'string' ||
!/^[0-9a-f]{64}$/.test(resultDigest ?? '') ||
artifact?.sha256 !== resultDigest
) {
throw new Error('active checkpoint $implement event lacks its digest-bound result')
}
let result
try {
result = JSON.parse(artifact.source)
} catch {
throw new Error('active checkpoint contains an invalid $implement result')
}
const startedAt = Date.parse(result?.startedAt)
const finishedAt = Date.parse(result?.finishedAt)
if (
result?.schemaVersion !== 1 ||
result.runId !== run.runId ||
result.agent !== '$implement' ||
result.invocationId !== event.payload?.invocationId ||
result.startedAt !== event.payload?.startedAt ||
result.finishedAt !== event.payload?.finishedAt ||
result.briefDigest !== run.briefDigest ||
result.commitSha !== run.implementationCommit ||
Number.isNaN(startedAt) ||
Number.isNaN(finishedAt) ||
finishedAt < startedAt ||
!Array.isArray(result.checks) ||
result.checks.length === 0 ||
result.checks.some((check) => check?.status !== 'passed') ||
!result.checks.some((check) => /^pnpm verify(?:\s|$)/.test(check.command ?? ''))
) {
throw new Error('active checkpoint $implement result does not attest the recorded boundary')
}
}
export function validateCheckpointRecord(record) {
const run = record?.run
const events = record?.events
const artifacts = record?.artifacts
if (
record?.schemaVersion !== 1 ||
record?.kind !== 'active-checkpoint' ||
!run ||
run.schemaVersion !== 1 ||
!ACTIVE_STATUSES.has(run.status) ||
run.finishedAt !== null ||
!Number.isInteger(run.issueNumber) ||
!/^[0-9a-f]{40}$/i.test(run.baseSha) ||
(run.headSha !== null && !/^[0-9a-f]{40}$/i.test(run.headSha)) ||
!Array.isArray(events) ||
events.length === 0 ||
!Array.isArray(artifacts) ||
typeof record.briefSource !== 'string' ||
Number.isNaN(Date.parse(record.updatedAt))
) {
throw new Error('invalid active checkpoint record')
}
assertRunId(run.runId)
const artifactPaths = new Set()
for (const artifact of artifacts) {
if (
!permittedArtifactPath(run.runId, artifact?.path) ||
typeof artifact.source !== 'string' ||
!/^[0-9a-f]{64}$/.test(artifact.sha256 ?? '') ||
createHash('sha256').update(artifact.source).digest('hex') !== artifact.sha256 ||
artifactPaths.has(artifact.path)
) {
throw new Error('active checkpoint contains an invalid artifact')
}
artifactPaths.add(artifact.path)
}
let previousTimestamp = -Infinity
for (const event of events) {
const timestamp = Date.parse(event.timestamp)
if (
event.schemaVersion !== 1 ||
event.runId !== run.runId ||
event.type === 'checkpoint_published' ||
Number.isNaN(timestamp) ||
timestamp < previousTimestamp
) {
throw new Error('active checkpoint contains invalid or unordered events')
}
previousTimestamp = timestamp
}
if (
events.at(-1).timestamp !== record.updatedAt ||
!events.some((event) => event.type === 'loop_started')
) {
throw new Error('active checkpoint is not bound to the latest run event')
}
if (
run.briefDigest !== null &&
createHash('sha256').update(record.briefSource).digest('hex') !== run.briefDigest
) {
throw new Error('active checkpoint brief does not match the frozen digest')
}
validateImplementationBoundary(record)
return record
}
export function checkpointPublicationBody(record) {
const validated = validateCheckpointRecord(record)
const digest = checkpointRecordDigest(validated)
const result = {
digest,
body: [
`<!-- issue-dev-loop:checkpoint:${validated.run.runId}:sha256:${digest} -->`,
'```json',
canonicalCheckpointRecord(validated),
'```',
].join('\n'),
}
if (result.body.length > 60_000) {
throw new Error('active checkpoint exceeds the GitHub comment size budget')
}
return result
}
export function parseCheckpointRecord(body) {
const serialized = body?.match(/```json\s*([^\n]+)\s*```/)?.[1]
return serialized ? JSON.parse(serialized) : null
}
export async function verifyPublishedCheckpoint({
loopRoot,
record,
commentUrl,
githubApi = defaultGitHubApi,
} = {}) {
const validated = validateCheckpointRecord(record)
const { channel, owner, repo } = await checkpointJournalConfiguration(loopRoot)
const target = parsePullCommentUrl(commentUrl)
if (
!target ||
target.surface !== 'issues' ||
target.kind !== 'issue_comment' ||
target.owner.toLowerCase() !== owner.toLowerCase() ||
target.repo.toLowerCase() !== repo.toLowerCase() ||
target.number !== channel.stateIssueNumber
) {
throw new Error('checkpoint comment must be on the configured state journal issue')
}
const comment = await githubApi(
`repos/${target.owner}/${target.repo}/issues/comments/${target.commentId}`,
)
const { digest, body } = checkpointPublicationBody(validated)
if (
!sameGitHubLogin(comment.user?.login, channel.automationGitHubLogin) ||
!comment.body?.includes(body)
) {
throw new Error('published checkpoint comment does not attest the exact active state')
}
return { record: validated, digest, commentUrl }
}
export async function verifyLatestDurableCheckpoint({
loopRoot,
runId,
events,
operation,
githubApi = defaultGitHubApi,
} = {}) {
const normalizedRunId = assertRunId(runId)
const latestPhaseEvent = events.findLast((event) => event.type !== 'checkpoint_published')
const checkpoint = events.findLast(
(event) =>
event.type === 'checkpoint_published' &&
event.status === 'published' &&
event.payload?.checkpointUpdatedAt === latestPhaseEvent?.timestamp,
)
if (!latestPhaseEvent || !checkpoint) {
throw new Error(`${operation} requires a durable checkpoint for the latest run phase`)
}
const record = validateCheckpointRecord(
await readJson(path.join(runDirectory(loopRoot, normalizedRunId), 'checkpoint-result.json')),
)
const currentRecord = validateCheckpointRecord({
schemaVersion: 1,
kind: 'active-checkpoint',
run: await readJson(path.join(runDirectory(loopRoot, normalizedRunId), 'run.json')),
briefSource: await readFile(
path.join(loopRoot, 'handoffs', normalizedRunId, 'implementation-brief.md'),
'utf8',
),
events: events.filter((event) => event.type !== 'checkpoint_published'),
artifacts: await checkpointArtifactsForEvents({
loopRoot,
runId: normalizedRunId,
events: events.filter((event) => event.type !== 'checkpoint_published'),
}),
updatedAt: latestPhaseEvent.timestamp,
})
const digest = checkpointRecordDigest(record)
if (
record.run.runId !== normalizedRunId ||
record.updatedAt !== latestPhaseEvent.timestamp ||
canonicalCheckpointRecord(currentRecord) !== canonicalCheckpointRecord(record) ||
checkpoint.payload?.digest !== digest
) {
throw new Error(`${operation} checkpoint event does not match its durable record`)
}
return verifyPublishedCheckpoint({
loopRoot,
record,
commentUrl: checkpoint.payload?.commentUrl,
githubApi,
})
}