Repository navigation
727 lines (708 loc) · 39.8 KB
/
Copy pathpoll.yml
File metadata and controls
727 lines (708 loc) · 39.8 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
# One `agent-board pass` (agent-board's docs/pass.md): follows the bot's pull
# requests, refreshes usage from the broker, plans and applies the operator's
# epics, starts board work by Priority, WIP and pace, and derives board
# Status. The configuration is .github/pass.json on the default branch.
name: poll
run-name: pass${{ inputs.apply && ' (apply)' || '' }}
# The clock is the `next` job: each applying pass starts the next one
# PASS_INTERVAL_MINUTES after its own start, and `next-fallback` stands in
# when `next` fails or GitHub never creates it, or when GitHub cancels a
# started pass for its timeout or a lost runner. There is no schedule: GitHub
# dropped most scheduled runs, and a waiting scheduled run counts as a newer
# chain owner. A lost chain can restart from the scheduled pin workflow or a
# manual dispatch. Its public cursor state comes from a validated
# applying predecessor; bootstrap runs discover one.
# Living status stays disabled until replay records have access-controlled durable storage.
on:
workflow_dispatch:
inputs:
apply:
description: Take the steps; otherwise only preview
type: boolean
default: false
previous_run_id:
description: Preceding applying poll run (empty discovers a trusted predecessor)
type: string
required: false
default: ''
permissions: {}
# The agent-board commit the pass runs. It is given the bot's token, so it is
# a revision reviewed here, never agent-board's moving branch: move it only
# with a review of what that revision's `pass` does.
env:
AGENT_BOARD_REV: 183ed445b9b0b7b5510454e03e794a31c0efbb5d
# Minutes from one applying pass's start to the next, for `next` and its
# recovery alike; a pass makes about 2,000 of the bot's hourly requests.
# The supervisor's usageStaleMinutes must stay above it, with slack.
PASS_INTERVAL_MINUTES: 45
jobs:
pass:
if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}
# One pass at a time; one that is due while another runs waits for it,
# and a group keeps only the newest waiting run. The group is the job's,
# not the workflow's, so `next` waiting out its interval holds nothing.
# Previews wait in their own group: one there could otherwise replace a
# queued applying successor, and with no schedule the chain would stop.
concurrency:
group: ${{ inputs.apply && 'pass' || 'pass-preview' }}
cancel-in-progress: false
runs-on: ubuntu-26.04
# The build (10), the join (3) and the pass's own bound (15, plus two
# to finish its writes), with room for checkout, setup and optional caching.
timeout-minutes: 46
env:
# Actions comparisons are case-insensitive; pass the same boolean to Node.
PASS_RESPONSE_CACHE_ENABLED: ${{ vars.PASS_RESPONSE_CACHE == 'enabled' && 'true' || 'false' }}
# `actions: write` starts dispatch.yml and review.yml runs with the job
# token; the identity token is the tailnet join's.
permissions:
contents: read
actions: write
id-token: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# A GitHub release outage (504s for over an hour on 2026-11-08) must not
# stop the job: build the same just from crates.io instead.
- id: just
continue-on-error: true
uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4.0.0
with:
just-version: 1.58.0
- if: steps.just.outcome == 'failure'
run: cargo install --locked --version 1.58.0 just && echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
# Built each pass and never cached: a cache any job on the default
# branch can write is not where a binary given the bot's token should
# come from.
- name: Install verified agent-board
env:
GH_TOKEN: ${{ github.token }}
timeout-minutes: 10
run: just build-agent-board "$AGENT_BOARD_REV"
# Stage 2 reads the broker's /usage over the tailnet. Without the
# join the pass runs without usage.url, pacing on the published
# snapshot, rather than failing on a broker it cannot reach.
- name: Join the tailnet
id: tailnet
continue-on-error: true
timeout-minutes: 3
uses: cgwalters-forge/actions/tailscale@main
with:
hostname: pass-${{ github.run_id }}-${{ github.run_attempt }}
# The broker's address stays in the variable the agent job, the
# broker probe and the tailnet test read (else the organization's
# tailnet setting), not in a second copy in pass.json.
- name: Configuration
env:
INFERENCE_URL: >-
${{ steps.tailnet.outcome == 'success' && (vars.INFERENCE_URL || steps.tailnet.outputs.proxy) || '' }}
run: |
base=${INFERENCE_URL%/}
base=${base%/v1}
jq --arg base "$base" 'if $base == "" then . else .usage.url = "\($base)/usage" end' \
.github/pass.json > "$RUNNER_TEMP/pass.json"
# A forged cached body could steer scheduling even with a valid ETag.
# Accept handoff metadata only from a validated applying predecessor.
- name: Validate predecessor
id: predecessor
timeout-minutes: 2
env:
GH_TOKEN: ${{ github.token }}
PREVIOUS_RUN_ID: ${{ inputs.previous_run_id }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
shell: node {0}
run: |
const fs = require('node:fs');
const { execFileSync } = require('node:child_process');
const { createHmac, createCipheriv, createDecipheriv, randomBytes } = require('node:crypto');
const STATE = '.state/pass.json';
const CACHE = '.state/pass-responses.json';
const RESPONSES = '.state/pass-responses.enc';
const HANDOFF = '.state/handoff/pass.json';
const SCHEMA = 'agent-board/poll-state/v1';
const MAX_BYTES = 32 * 1024 * 1024; // The pinned pass's state-file limit.
// The --cache-bytes budget covers entries; agent-board allows another
// 256 bytes for the scope and JSON framing (agent-board#1197).
const MAX_CACHE_FILE_BYTES = 256 * 1024 * 1024 + 256;
const MAX_ARCHIVE_BYTES = 1024 ** 3; // 1 GiB
const RUN_ID = /^[1-9][0-9]{0,19}$/;
const SHA256 = /^[0-9a-f]{64}$/;
// agent-board writes one digest, or two joined by ':' when a pass saves quiet waits.
const SCOPE = /^[0-9a-f]{64}(:[0-9a-f]{64})?$/;
const cacheKey = (id, attempt) => RUN_ID.test(id) && RUN_ID.test(attempt) ? `pass-responses-${id}-${attempt}` : '';
const NONCE_BYTES = 12;
const TAG_BYTES = 16;
const MAX_CIPHERTEXT_BYTES = MAX_CACHE_FILE_BYTES + NONCE_BYTES + TAG_BYTES;
// Do not accept the old encrypted fragments of pass.json as a cache file.
const cacheContext = (key, scope) => Buffer.from(`pass-response-file-v1\n${key}\n${scope}`);
function api(endpoint, timeout = 20000) {
return JSON.parse(execFileSync('gh', ['api', endpoint], {
timeout, maxBuffer: MAX_BYTES, stdio: ['ignore', 'pipe', 'pipe'],
}));
}
function validate(env = process.env, get = api) {
let id = env.PREVIOUS_RUN_ID;
const root = `repos/${env.GITHUB_REPOSITORY}/actions`;
if (!id) {
const listed = get(`${root}/workflows/poll.yml/runs?branch=${encodeURIComponent(env.DEFAULT_BRANCH)}&per_page=100`).workflow_runs;
if (!Array.isArray(listed) || listed.length > 100) throw new Error('invalid run listing');
const previous = listed.filter(run => RUN_ID.test(String(run.id)) &&
BigInt(run.id) < BigInt(env.GITHUB_RUN_ID) && run.head_branch === env.DEFAULT_BRANCH &&
(run.event === 'schedule' || (run.event === 'workflow_dispatch' && run.display_title === 'pass (apply)')) &&
run.conclusion !== 'cancelled').sort((a, b) => BigInt(a.id) > BigInt(b.id) ? -1 : 1)[0];
if (!previous) return null;
id = String(previous.id);
}
if (!RUN_ID.test(id) || id === env.GITHUB_RUN_ID) return null;
const run = get(`${root}/runs/${id}`);
const workflow = get(`${root}/workflows/poll.yml`);
if (String(run.id) !== id || run.workflow_id !== workflow.id ||
run.path !== '.github/workflows/poll.yml' ||
run.repository?.full_name !== env.GITHUB_REPOSITORY ||
run.head_repository?.full_name !== env.GITHUB_REPOSITORY ||
run.head_branch !== env.DEFAULT_BRANCH ||
!(run.event === 'schedule' ||
(run.event === 'workflow_dispatch' && run.display_title === 'pass (apply)'))) return null;
// Require the state-writing job to have finished, not the whole workflow.
const key = cacheKey(id, run.run_attempt);
const jobs = get(key ? `${root}/runs/${id}/attempts/${run.run_attempt}/jobs?per_page=100` :
`${root}/runs/${id}/jobs?filter=latest&per_page=100`);
if (!Array.isArray(jobs.jobs) || jobs.total_count !== jobs.jobs.length || jobs.jobs.length > 100) return null;
const passes = jobs.jobs.filter(job => job.name === 'pass');
return passes.length === 1 && passes[0].status === 'completed' &&
['success', 'failure'].includes(passes[0].conclusion) ? { id, key } : null;
}
function publicState(state, get = api) {
// Repository cursors can name private threads, including holds on public issues.
const cursors = ['follow', 'share', 'action_first', 'scan', 'authored'].map(name => `${name}_cursor`);
const cursorRepo = value => typeof value === 'string' && /^([\w.-]+\/[\w.-]+)(?:#[1-9][0-9]*)?$/.exec(value)?.[1].toLowerCase();
const repositories = new Set(cursors.map(key => cursorRepo(state[key])).filter(Boolean));
const publicRepos = new Set();
const deadline = Date.now() + 90000;
for (const repo of repositories) {
const remaining = deadline - Date.now();
if (remaining <= 0) break;
try {
const metadata = get(`repos/${repo}`, Math.min(10000, remaining));
if (metadata.full_name?.toLowerCase() === repo && metadata.private === false && metadata.visibility === 'public') publicRepos.add(repo);
} catch { /* Drop cursors on any doubt. */ }
}
const { response_scope, interval_seconds } = state;
const handoff = { schema: SCHEMA,
interval_seconds: Number.isInteger(interval_seconds) && interval_seconds >= 300 && interval_seconds <= 21600 ? interval_seconds : 300 };
if (typeof response_scope === 'string' && SCOPE.test(response_scope)) handoff.response_scope = response_scope;
for (const key of cursors) if (publicRepos.has(cursorRepo(state[key]))) handoff[key] = state[key];
return handoff;
}
function checkCache(env, get = api) {
const key = env.RESPONSE_CACHE_KEY;
if (!key) return '';
const ref = `refs/heads/${env.DEFAULT_BRANCH}`;
// Prefix results and multiple archive versions are ambiguous.
const listing = get(`repos/${env.GITHUB_REPOSITORY}/actions/caches?key=${key}&ref=${encodeURIComponent(ref)}&per_page=1`);
const entries = listing.actions_caches;
if (listing.total_count !== 1 || !Array.isArray(entries) || entries.length !== 1) return '';
const [entry] = entries;
return entry?.key === key && entry.ref === ref && Number.isSafeInteger(entry.size_in_bytes) &&
entry.size_in_bytes > 0 && entry.size_in_bytes <= MAX_ARCHIVE_BYTES ? key : '';
}
function readBounded(file, limit = MAX_BYTES, min = 1) {
const stats = fs.lstatSync(file);
if (!stats.isFile() || stats.size < min || stats.size > limit) throw new Error('invalid state file size or type');
return fs.readFileSync(file);
}
function parseState(data) {
const state = JSON.parse(data);
if (state?.schema !== SCHEMA) throw new Error('invalid state schema');
return state;
}
function prepareState(restored) {
fs.mkdirSync('.state', { recursive: true });
fs.rmSync(CACHE, { force: true });
if (restored !== 'success') return;
try {
const { responses, pass_responses, response_cache, response_cache_key, ...state } = parseState(readBounded(HANDOFF));
fs.writeFileSync(STATE, JSON.stringify(state));
} catch { /* Bad handoff: start without cursors. */ }
}
function encryptionKey(env) {
if (env.PASS_CACHE_KEY) return createHmac('sha256', env.PASS_CACHE_KEY).update('pass-response-cache-dedicated-v1').digest();
if (!env.PASS_RESPONSE_CACHE_PAT) throw new Error('missing cache credential');
return createHmac('sha256', env.PASS_RESPONSE_CACHE_PAT).update('pass-response-cache-v1').digest();
}
function exportCache(scope, env, key) {
// Fork PR jobs can read default-branch caches but lack the secret.
// Bind to the attempt and scope; store nonce | tag | ciphertext.
const nonce = randomBytes(NONCE_BYTES);
const cipher = createCipheriv('aes-256-gcm', encryptionKey(env), nonce);
cipher.setAAD(cacheContext(key, scope));
const ciphertext = cipher.update(readBounded(CACHE, MAX_CACHE_FILE_BYTES));
const end = cipher.final();
fs.writeFileSync(RESPONSES, Buffer.concat([nonce, cipher.getAuthTag()]), { flag: 'wx', mode: 0o600 });
fs.appendFileSync(RESPONSES, ciphertext);
fs.appendFileSync(RESPONSES, end);
}
function exportState(env) {
const output = '.state/public';
fs.rmSync(output, { recursive: true, force: true });
fs.rmSync(RESPONSES, { force: true });
let handoff;
try {
handoff = publicState(parseState(readBounded(STATE)));
const key = cacheKey(env.GITHUB_RUN_ID, env.GITHUB_RUN_ATTEMPT);
if (env.PASS_RESPONSE_CACHE_ENABLED === 'true' && key && handoff.response_scope && fs.existsSync(CACHE)) {
try {
exportCache(handoff.response_scope, env, key);
handoff.response_cache_key = key;
} catch {
fs.rmSync(RESPONSES, { force: true });
console.log('Could not encrypt pass responses; the next pass reads cold');
}
}
fs.mkdirSync(output);
fs.writeFileSync(`${output}/pass.json`, JSON.stringify(handoff) + '\n');
} catch {
fs.rmSync(output, { recursive: true, force: true });
console.log('Could not prepare public pass state; the next pass starts cold');
return;
}
if (handoff.response_cache_key) {
try { fs.appendFileSync(env.GITHUB_OUTPUT, 'cache-ready=true\n'); }
catch { console.log('Could not signal response cache readiness; the next pass reads cold'); }
}
}
function prepareCache(env) {
let key = '';
try {
// A rerun can leave an older cursor artifact behind.
if (parseState(readBounded(HANDOFF)).response_cache_key === env.RESPONSE_CACHE_KEY) key = checkCache(env);
if (key) {
// The cache action does not restrict tar members to its path input.
// Never let an archive write a path in the privileged checkout.
const guard = fs.mkdtempSync(`${env.RUNNER_TEMP}/pass-cache-`);
fs.writeFileSync(`${guard}/tar`, `#!/bin/sh
[ "$PASS_CACHE_EXTRACT" = 1 ] || exec /usr/bin/tar "$@"
case "$1" in -tf) exit 0 ;; -xf) ;; *) exit 1 ;; esac
dest="$GITHUB_WORKSPACE/${RESPONSES}"
tmp=$(mktemp "$dest.XXXXXX") || exit 1
trap 'rm -f -- "$tmp"' EXIT
if /usr/bin/prlimit --fsize=${MAX_CIPHERTEXT_BYTES}:${MAX_CIPHERTEXT_BYTES} -- /usr/bin/tar "$@" \\
--no-recursion --occurrence=1 --to-stdout -- '${RESPONSES}' > "$tmp" 2>/dev/null; then
mv -T -- "$tmp" "$dest"
else exit 1; fi
`, { mode: 0o755 });
fs.appendFileSync(env.GITHUB_PATH, `${guard}\n`);
}
} catch { key = ''; }
fs.appendFileSync(env.GITHUB_OUTPUT, `key=${key}\n`);
if (!key) console.log('No eligible response cache; using cold reads');
}
function restoreCache(env) {
const pending = `${CACHE}.tmp`;
try {
if (env.CACHE_HIT !== 'true') return;
const state = parseState(readBounded(STATE));
const header = NONCE_BYTES + TAG_BYTES;
const data = readBounded(RESPONSES, MAX_CIPHERTEXT_BYTES, header + 1);
if (!state.response_scope) return;
const decipher = createDecipheriv('aes-256-gcm', encryptionKey(env), data.subarray(0, NONCE_BYTES), { authTagLength: TAG_BYTES });
decipher.setAAD(cacheContext(env.RESPONSE_CACHE_KEY, state.response_scope));
decipher.setAuthTag(data.subarray(NONCE_BYTES, header));
// Do not write any plaintext before authentication succeeds.
const plaintext = decipher.update(data.subarray(header));
const end = decipher.final();
fs.writeFileSync(pending, plaintext, { flag: 'wx', mode: 0o600 });
fs.appendFileSync(pending, end);
fs.renameSync(pending, CACHE);
} catch { console.log('Rejected response cache; using cold reads'); }
finally {
fs.rmSync(pending, { force: true });
fs.rmSync(RESPONSES, { force: true });
}
}
function main(mode, env = process.env) {
switch (mode) {
case 'validate': {
let predecessor;
try { predecessor = validate(env); } catch { /* Missing provenance starts cold. */ }
const { id = '', key = '' } = predecessor ?? {};
fs.appendFileSync(env.GITHUB_OUTPUT, `run-id=${id}\nresponse-key=${key}\n`);
console.log(id ? `Validated predecessor ${id}` : 'No trusted predecessor; starting cold');
break;
}
case 'prepare': prepareState(env.RESTORED); break;
case 'export': exportState(env); break;
case 'check-cache': prepareCache(env); break;
case 'restore-cache': restoreCache(env); break;
default: throw new Error('Unknown pass-state mode; expected validate, prepare, export, check-cache, or restore-cache');
}
}
if (require.main === module) main(process.argv[2] || 'validate');
module.exports = { main, validate, publicState, checkCache };
- name: Restore pass state
id: restore
if: steps.predecessor.outputs.run-id != ''
continue-on-error: true
timeout-minutes: 2
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
github-token: ${{ github.token }}
run-id: ${{ steps.predecessor.outputs.run-id }}
name: pass-state
path: .state/handoff
- name: Prepare state directory
timeout-minutes: 1
env:
RESTORED: ${{ steps.restore.outcome }}
run: just pass-state prepare
- name: Check response cache size
id: cache-check
if: env.PASS_RESPONSE_CACHE_ENABLED == 'true' && steps.restore.outcome == 'success'
continue-on-error: true
timeout-minutes: 1
env:
GH_TOKEN: ${{ github.token }}
RESPONSE_CACHE_KEY: ${{ steps.predecessor.outputs.response-key }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
run: just pass-state check-cache
- name: Restore pass responses
id: responses
if: steps.cache-check.outcome == 'success' && steps.cache-check.outputs.key != ''
continue-on-error: true
timeout-minutes: 2
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
env:
PASS_CACHE_EXTRACT: '1'
with:
path: .state/pass-responses.enc
key: ${{ steps.cache-check.outputs.key }}
- name: Validate restored responses
if: ${{ !cancelled() && steps.cache-check.outcome != 'skipped' }}
continue-on-error: true
timeout-minutes: 1
env:
CACHE_HIT: ${{ steps.responses.outcome == 'success' && steps.responses.outputs.cache-hit == 'true' }}
RESPONSE_CACHE_KEY: ${{ steps.cache-check.outputs.key }}
PASS_CACHE_KEY: ${{ steps.responses.outputs.cache-hit == 'true' && secrets.PASS_CACHE_KEY || '' }}
PASS_RESPONSE_CACHE_PAT: ${{ steps.responses.outputs.cache-hit == 'true' && secrets.PASS_CACHE_KEY == '' && secrets.CGWALTERS_BOT_PAT || '' }}
run: just pass-state restore-cache
- name: One pass
id: pass
timeout-minutes: 18
env:
# The bot's token: it reads the organization's board and the
# private usage issue, and makes the pass's writes.
GH_TOKEN: ${{ secrets.CGWALTERS_BOT_PAT }}
DISPATCH_TOKEN: ${{ github.token }}
AGENT_BOARD: ${{ runner.temp }}/agent-board/bin/agent-board
# A scheduled pass applies once the operator sets PASS_APPLY; a
# pass started by hand applies only when asked to.
APPLY: >-
${{ ((github.event_name == 'schedule' && vars.PASS_APPLY == 'enabled') ||
(github.event_name == 'workflow_dispatch' && inputs.apply)) && '--apply' || '' }}
shell: bash
# The caps of the first scheduled passes, until they have been
# watched; stderr too, so that the summary says why a pass failed.
# Dispatch picks one fix bounds file per target, so the pass needs both.
run: |
cache=()
if [[ $PASS_RESPONSE_CACHE_ENABLED == true ]]; then
cache=(--cache .state/pass-responses.json --cache-bytes 268435456)
fi
"$AGENT_BOARD" pass --config "$RUNNER_TEMP/pass.json" ${APPLY:+"$APPLY"} \
"${cache[@]}" \
--fix-bounds .github/agentic-job/fix.toml \
--fix-bounds .github/agentic-job/midstream-fix.toml \
--max-dispatch 20 --max-writes 60 --max-status-changes 50 2>&1 | tee "$RUNNER_TEMP/pass.log"
# Threat: raw state and responses can include private comments and records.
# The artifact is readable outside this job; filter before publishing.
- name: Prepare public pass state
id: state
if: >-
${{ !cancelled() && (steps.pass.outcome == 'success' || steps.pass.outcome == 'failure') &&
((github.event_name == 'schedule' && vars.PASS_APPLY == 'enabled') ||
(github.event_name == 'workflow_dispatch' && inputs.apply)) }}
timeout-minutes: 3
env:
GH_TOKEN: ${{ github.token }}
PASS_CACHE_KEY: ${{ env.PASS_RESPONSE_CACHE_ENABLED == 'true' && secrets.PASS_CACHE_KEY || '' }}
PASS_RESPONSE_CACHE_PAT: ${{ env.PASS_RESPONSE_CACHE_ENABLED == 'true' && secrets.PASS_CACHE_KEY == '' && secrets.CGWALTERS_BOT_PAT || '' }}
run: just pass-state export
- name: Upload pass state
id: publish-state
if: ${{ !cancelled() && steps.state.outcome == 'success' }}
timeout-minutes: 2
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: pass-state
path: .state/public/pass.json
include-hidden-files: true
retention-days: 1
if-no-files-found: ignore
- name: Save pass responses
if: ${{ !cancelled() && steps.publish-state.outcome == 'success' && steps.state.outputs.cache-ready == 'true' }}
continue-on-error: true
timeout-minutes: 2
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: .state/pass-responses.enc
key: pass-responses-${{ github.run_id }}-${{ github.run_attempt }}
# GitHub drops agent-board-pin.yml's hourly runs too, so the pass starts
# it when agent-board's head is not the pin and has no pin PR yet (the
# title is the one `just bump-agent-board` gives it); the pin workflow
# checks CI and stays idempotent, and its schedule is the fallback.
# Threat: these two in-org reads do not need the long-lived bot writer
# credential. Opt in only after the org's tracker-poll-reads policy lands;
# an enabled exchange failure must not fall back to the PAT.
- name: Mint the poll read token
id: poll-read-token
if: ${{ !cancelled() && vars.AGENT_BOARD_PIN == 'enabled' && vars.POLL_READ_STS_DOMAIN != '' }}
timeout-minutes: 1
uses: octo-sts/action@f603d3be9d8dd9871a265776e625a27b00effe05 # v1.1.1
with:
domain: ${{ vars.POLL_READ_STS_DOMAIN }}
scope: cgwalters-forge
identity: tracker-poll-reads
- name: Start the agent-board pin bump
if: ${{ !cancelled() && vars.AGENT_BOARD_PIN == 'enabled' && (vars.POLL_READ_STS_DOMAIN == '' || steps.poll-read-token.outcome == 'success') }}
timeout-minutes: 2
env:
GH_TOKEN: ${{ vars.POLL_READ_STS_DOMAIN == '' && secrets.CGWALTERS_BOT_PAT || steps.poll-read-token.outputs.token }}
DISPATCH_TOKEN: ${{ github.token }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
shell: bash
run: |
[[ -n $GH_TOKEN ]] || { echo '::error::missing poll read token'; exit 1; }
source=$(jq -er .source .github/poll/agent-board.json)
branch=$(jq -er .branch .github/poll/agent-board.json)
bot=$(jq -er .bot .github/poll/agent-board.json)
head=$(gh api "repos/${source#https://github.com/}/commits/$branch" --jq .sha)
[[ $head =~ ^[0-9a-f]{40}$ ]] || { echo "::error::no head for $source $branch"; exit 1; }
if [[ $head == "$AGENT_BOARD_REV" ]]; then echo "the pin is $branch's head"; exit 0; fi
title="workflows: Move agent-board to ${head:0:7}"
open=$(gh pr list --repo "$GITHUB_REPOSITORY" --author "$bot" --head agent-board-pin --state open --json title --jq '.[0].title // ""')
if [[ $open == "$title" ]]; then echo "already proposed: $title"; exit 0; fi
GH_TOKEN=$DISPATCH_TOKEN gh workflow run agent-board-pin.yml --repo "$GITHUB_REPOSITORY" --ref "$DEFAULT_BRANCH"
- name: Summary
if: ${{ !cancelled() }}
run: |
{
echo '### Pass'
echo '<pre>'
sed 's/&/\&/g; s/</\</g; s/>/\>/g' "$RUNNER_TEMP/pass.log" 2>/dev/null || echo 'No pass ran'
echo '</pre>'
} >> "$GITHUB_STEP_SUMMARY"
next:
needs: pass
# Only an applying pass continues the chain, whether it passed or failed
# (`!cancelled()`, else GitHub adds an implicit `success()`);
# a preview by hand never starts one. A newer `next` replaces a waiting
# one, but two chains offset by a few minutes never wait at once (#1019),
# so before dispatching `next` also stops if a newer applying run on the
# default branch is still to finish: that run continues the chain. A run
# arriving between the check and the dispatch, or the newer run failing
# to continue, can still leave two chains or none. Setting PASS_APPLY to
# anything but `enabled` also disables scheduled recovery. While
# it waits, `next` keeps a hosted runner busy for up to an interval per
# pass. While RELEASE_TRAIN is `dry-run` or `apply`, `next` also starts
# release-train.yml when its newest run is an hour old or absent, since
# GitHub drops its hourly schedule too; the train's own gate and
# concurrency still decide what that run does. Supervisor wakes use a
# thirty-minute threshold. With MAINTAIN_SHADOW `enabled`, `next` also
# starts maintain-shadow.yml when its newest default-branch run is at
# least thirty minutes old or absent; failures only warn. Its cron is
# the fallback, and its preview keeps its own read-only job token.
concurrency:
group: pass-next
cancel-in-progress: true
if: >-
${{ !cancelled() && (needs.pass.result == 'success' || needs.pass.result == 'failure') && vars.PASS_APPLY == 'enabled' &&
github.ref == format('refs/heads/{0}', github.event.repository.default_branch) &&
(github.event_name == 'schedule' || inputs.apply) }}
runs-on: ubuntu-26.04
# The verified download, the interval's wait, and the pinned dispatch's
# retries, whose backoff adds to each request's own timeout: without a
# schedule, a deadline that cuts them off stops the chain.
timeout-minutes: 120
permissions:
actions: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
# A GitHub release outage (504s for over an hour on 2026-11-08) must not
# stop the job: build the same just from crates.io instead.
- id: just
continue-on-error: true
uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4.0.0
with:
just-version: 1.58.0
- if: steps.just.outcome == 'failure'
run: cargo install --locked --version 1.58.0 just && echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Install verified agent-board
env:
GH_TOKEN: ${{ github.token }}
timeout-minutes: 10
run: just build-agent-board "$AGENT_BOARD_REV"
- name: Start the shadow poll if stale
if: ${{ vars.MAINTAIN_SHADOW == 'enabled' }}
timeout-minutes: 2
env:
GH_TOKEN: ${{ github.token }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
shell: bash
run: |
if latest=$(timeout 30s gh run list --workflow maintain-shadow.yml --branch "$DEFAULT_BRANCH" --limit 1 --json createdAt --jq '.[0].createdAt // empty'); then
if [[ -z $latest ]] || (( $(date +%s) - $(date -d "$latest" +%s) >= 1800 )); then
timeout 30s gh workflow run maintain-shadow.yml --ref "$DEFAULT_BRANCH" || echo '::warning::Could not start maintain-shadow.yml'
fi
else
echo '::warning::Could not check maintain-shadow.yml age'
fi
- name: Start promote if overdue
# A second dispatch can replace a pending run in promote's concurrency
# group. Check for active runs even if the newest run has finished.
continue-on-error: true
timeout-minutes: 2
env:
GH_TOKEN: ${{ github.token }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
shell: node {0}
run: |
const { readFileSync } = require('node:fs');
const { execFileSync } = require('node:child_process');
const { GITHUB_REPOSITORY: repo, DEFAULT_BRANCH: branch } = process.env;
const gh = args => execFileSync('gh', args, { encoding: 'utf8', timeout: 10_000 });
function list(filter) {
const { total_count: count, workflow_runs: runs } = JSON.parse(gh([
'api', '--method', 'GET', `repos/${repo}/actions/workflows/promote.yml/runs`, '-f', 'per_page=1', '-f', filter,
]));
if (!Number.isSafeInteger(count) || count < 0 || !Array.isArray(runs) || runs.length !== Math.min(count, 1)) {
throw new Error('invalid promote run listing');
}
return runs;
}
function overdue() {
const [latest] = list(`branch=${branch}`);
if (latest === undefined) return true;
if (latest?.status !== 'completed') return false;
const created = typeof latest.created_at === 'string' ? Date.parse(latest.created_at) : NaN;
if (!Number.isFinite(created)) throw new Error('invalid promote run creation time');
return Date.now() - created > 60 * 60_000;
}
function wake() {
if (JSON.parse(readFileSync('.github/pass.json', 'utf8')).promote?.publish !== true || !overdue()) return;
for (const status of ['queued', 'waiting', 'pending', 'requested', 'in_progress']) {
if (list(`status=${status}`).length) return;
}
// Catch a new cron run that arrived during the status checks.
if (!overdue()) return;
console.log('Dispatching promote.yml: no active or recent run.');
gh(['workflow', 'run', 'promote.yml', '--repo', repo, '--ref', branch]);
}
wake();
- name: Start the next pass an interval after this one started
env:
GH_TOKEN: ${{ github.token }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
SUPERVISOR: ${{ vars.SUPERVISOR }}
RELEASE_TRAIN: ${{ vars.RELEASE_TRAIN }}
shell: bash
run: |
supervisor=()
if [[ $SUPERVISOR == preview || $SUPERVISOR == apply ]]; then
supervisor=(--supervisor-workflow supervisor.yml --supervisor-stale-minutes 30
--supervisor-input prompt= --supervisor-input session=false)
fi
train=()
if [[ $RELEASE_TRAIN == dry-run || $RELEASE_TRAIN == apply ]]; then
train=(--train-workflow release-train.yml --train-stale-minutes 60)
fi
"$RUNNER_TEMP/agent-board/bin/agent-board" pass next --workflow poll.yml \
--branch "$DEFAULT_BRANCH" --input apply=true --input "previous_run_id=$GITHUB_RUN_ID" --apply-title 'pass (apply)' \
--wait-minutes "$PASS_INTERVAL_MINUTES" "${supervisor[@]}" "${train[@]}"
# Best-effort recovery when `next` fails or never runs, including a missing
# `pass`. Use only runner tools and one dispatch attempt; there is no further
# recovery job. Dropped GitHub schedules/jobs still prevent a within-one-
# interval guarantee. Previews never recover. A cancelled pass recovers only
# when it started and GitHub ended it (job timeout or lost runner); a run
# replaced while pending or cancelled by hand does not. `!cancelled()` holds
# after a dependency times out (observed, not documented) and turns false
# when the run is cancelled, which also stops a recovery already running.
next-fallback:
needs: [pass, next]
if: >-
${{ !cancelled() &&
(needs.next.result == 'failure' || needs.next.result == 'skipped' || needs.next.result == '' || needs.next.result == 'cancelled') &&
vars.PASS_APPLY == 'enabled' &&
github.ref == format('refs/heads/{0}', github.event.repository.default_branch) &&
(github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.apply)) }}
runs-on: ubuntu-26.04
timeout-minutes: 55
# `checks: read` reads the cancelled pass job's annotations.
permissions:
actions: write
checks: read
steps:
- name: Recover the next pass
env:
GH_TOKEN: ${{ github.token }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
PASS_RESULT: ${{ needs.pass.result }}
NEXT_RESULT: ${{ needs.next.result }}
shell: bash
run: |
printf 'Recovery dependencies: pass=<%s> next=<%s>\n' "$PASS_RESULT" "$NEXT_RESULT"
# Threat: recovering a replaced or hand-cancelled run restarts a chain
# someone stopped. GitHub's failure annotation on the started pass job
# decides. A step can write the same text, so this is a heuristic: it
# must be the whole message, and any cancel annotation vetoes it.
# The same holds for `next`; the separate scheduled check can later restart it.
if [[ $PASS_RESULT == cancelled || $NEXT_RESULT == cancelled ]]; then
name=pass; [[ $PASS_RESULT == cancelled ]] || name=next
job=$(timeout 30s gh api --method GET "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/jobs" -f filter=latest \
--jq "first(.jobs[] | select(.name == \"$name\" and .started_at != null) | .id) // empty")
[[ -n $job ]] || { echo "the $name job never started; not recovering"; exit 0; }
ended=$(timeout 30s gh api --method GET "repos/$GITHUB_REPOSITORY/check-runs/$job/annotations" -f per_page=100 \
--jq '[.[] | select(.annotation_level == "failure") | .message] |
any(test("^The job (running on runner .+ )?has exceeded the maximum execution time of [^ ]+( minutes)?\\.?$|^The (self-)?hosted runner: [^\n]+ lost communication with the server\\.( |$)")) and
(any(test("canceled by|higher priority")) | not)')
[[ $ended == true ]] || { echo "the $name job was cancelled, not ended by GitHub; not recovering"; exit 0; }
fi
started=$(timeout 30s gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" --jq .run_started_at)
[[ -n $started && $started != null ]] || { echo '::error::missing run start time' >&2; exit 1; }
started_epoch=$(date -d "$started" +%s)
delay=$(( started_epoch + PASS_INTERVAL_MINUTES * 60 - $(date +%s) ))
if (( delay > PASS_INTERVAL_MINUTES * 60 )); then delay=$(( PASS_INTERVAL_MINUTES * 60 )); fi
if (( delay > 0 )); then sleep "$delay"; fi
# Threat: a recovered old run can fork an already-owned chain. Match
# pinned pass next's branch, event/title, active statuses, creation-time
# and ID ordering, and fail if this run is outside its 200-run bound.
runs=''
for page in 1 2; do
# Full run pages can exceed Linux's per-argument limit. Read one
# response on stdin and retain only the fields the check uses.
listed=$(timeout 30s gh api --method GET "repos/$GITHUB_REPOSITORY/actions/workflows/poll.yml/runs" \
-f branch="$DEFAULT_BRANCH" -f exclude_pull_requests=true -f per_page=100 -f page="$page" |
jq -ces 'if length == 1 and (.[0].workflow_runs | type) == "array"
then .[0].workflow_runs | map({id, head_branch, status, event, created_at, display_title})
else error("expected one response with a workflow_runs array") end')
runs+="$listed"$'\n'
if jq -e --argjson id "$GITHUB_RUN_ID" 'any(.[]; .id == $id)' <<< "$listed" >/dev/null; then break; fi
if (( $(jq 'length' <<< "$listed") < 100 )); then break; fi
done
newer=$(jq -rs --argjson id "$GITHUB_RUN_ID" --arg branch "$DEFAULT_BRANCH" '
def created: .created_at | fromdateiso8601;
add |
map(if (.id | type) == "number" and
all(.head_branch, .status, .event, .created_at; type == "string") and
(.event != "workflow_dispatch" or (.display_title | type) == "string")
then (created as $at | .) else error("invalid workflow run") end) |
(map(select(.id == $id))[0] // error("current run absent from bounded listing")) as $me |
first(.[] | select(.id != $id and .head_branch == $branch and
(.status == "queued" or .status == "waiting" or .status == "pending" or .status == "requested" or .status == "in_progress") and
(.event == "schedule" or (.event == "workflow_dispatch" and .display_title == "pass (apply)")) and
([created, .id] > [($me | created), $id])) | .id) // empty' <<< "$runs")
if [[ -n $newer ]]; then echo "run $newer continues the chain; not starting another"; exit 0; fi
timeout 30s gh workflow run poll.yml --repo "$GITHUB_REPOSITORY" --ref "$DEFAULT_BRANCH" -f apply=true -f "previous_run_id=$GITHUB_RUN_ID"