gestalt-mobile 0.54.1 → 0.55.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 (22) hide show
  1. package/README.md +19 -0
  2. package/dist/client/assets/{index-BoOCaxSo.js → index-DdEHicWt.js} +3 -3
  3. package/dist/client/index.html +1 -1
  4. package/dist/server/server/composition.contracts.js +490 -4
  5. package/dist/server/server/composition.js +38 -1
  6. package/dist/server/server/features/autopilot/application/service.js +174 -17
  7. package/dist/server/server/features/autopilot/domain/supervision-protocol.js +34 -0
  8. package/dist/server/server/features/org-plan-checkpoint/application/validate.js +8 -2
  9. package/dist/server/server/features/plans/application/executor-model-evidence.js +192 -0
  10. package/dist/server/server/features/plans/application/parse-model-policy.js +77 -0
  11. package/dist/server/server/features/plans/application/parse-supervised-plan.js +23 -4
  12. package/dist/server/server/features/plans/application/supervised-plan-registry.js +16 -1
  13. package/dist/server/server/features/plans/domain/model-policy-admission.js +43 -0
  14. package/dist/server/server/platform/codex/codex-model-catalog.js +38 -0
  15. package/dist/server/server/platform/codex/executor-configuration.js +90 -0
  16. package/dist/server/server/platform/codex/session-runtime.js +33 -1
  17. package/dist/server/server/platform/plans/filesystem-plan-status-source.js +118 -13
  18. package/dist/server/server/platform/plans/org-plan-capabilities.js +2 -2
  19. package/dist/server/shared/contracts/plan-signal.js +1 -0
  20. package/gestalt-supervision-capabilities.json +8 -2
  21. package/package.json +1 -1
  22. package/scripts/watch-github-run.mjs +283 -51
@@ -9,6 +9,7 @@ import { isPlanSignalReason } from '../../../shared/contracts/plan-signal.js';
9
9
  import { basename, dirname, join } from 'node:path';
10
10
  import { parseSupervisedPlan } from '../../features/plans/application/parse-supervised-plan.js';
11
11
  import { isPlanPathWithinWorkspace } from '../../features/plans/application/parse-supervised-plan.js';
12
+ import { ORG_PLAN_CAPABILITIES } from './org-plan-capabilities.js';
12
13
  const statusFileSuffix = '.plan-status.json';
13
14
  export class FilesystemPlanStatusSource {
14
15
  dismissalDirectory;
@@ -61,21 +62,41 @@ export class FilesystemPlanStatusSource {
61
62
  const statusPath = planStatusFilePath(directory, planPath);
62
63
  const candidate = join(directory, `.${randomUUID()}.status.tmp`);
63
64
  try {
64
- await writeFile(candidate, JSON.stringify({ schemaVersion: 1, planPath, reason, updatedAt: new Date().toISOString() }), { mode: 0o600 });
65
+ await writeFile(candidate, JSON.stringify({
66
+ schemaVersion: 1,
67
+ planPath,
68
+ reason,
69
+ updatedAt: new Date().toISOString(),
70
+ ...(parsed.plan.modelPolicyVersion
71
+ ? {
72
+ modelPolicyVersion: parsed.plan.modelPolicyVersion,
73
+ requiredCapabilities: ['l1-model-policy-v1'],
74
+ }
75
+ : {}),
76
+ }), { mode: 0o600 });
65
77
  await rename(candidate, statusPath);
66
78
  }
67
79
  finally {
68
80
  await rm(candidate, { force: true }).catch(() => { });
69
81
  }
82
+ // Explicit validated attachment supersedes incompatible pointer hints in
83
+ // this session only. Plan files are never removed or rewritten here.
84
+ for (const filename of await readdir(directory)) {
85
+ const stalePath = join(directory, filename);
86
+ if (stalePath === statusPath || !filename.endsWith(statusFileSuffix))
87
+ continue;
88
+ const stale = await this.planReadFilesystem.readFile(stalePath, 'utf8').catch(() => '');
89
+ if (declaresModelPolicy(stale) && !parseSignal(stale))
90
+ await rm(stalePath, { force: true });
91
+ }
70
92
  const identity = createHash('sha256').update(planPath).digest('hex');
71
93
  const dismissed = new Set(await this.dismissed(session.id));
72
94
  if (dismissed.delete(identity))
73
95
  await this.saveDismissals(session.id, dismissed);
74
96
  const lease = this.leases.get(session.id);
75
- if (lease)
76
- await lease.refreshLatest();
77
- else
97
+ if (!lease)
78
98
  await this.open(session, listener);
99
+ await this.leases.get(session.id)?.selectAttachment(statusPath);
79
100
  }
80
101
  closeAll() {
81
102
  for (const lease of this.leases.values())
@@ -201,6 +222,9 @@ class ActiveLease {
201
222
  activeStatusPath;
202
223
  activePlanPath;
203
224
  lastEmittedUpdate;
225
+ policyBlockedStatusPath;
226
+ /** Retire older reads when mandatory rejection or explicit recovery changes admission. */
227
+ policySelectionRevision = 0;
204
228
  constructor(statusDirectory, sessionId, workspacePath, listener, planReadFilesystem, isDismissed, onActiveStatusPath, onClose) {
205
229
  this.statusDirectory = statusDirectory;
206
230
  this.sessionId = sessionId;
@@ -302,9 +326,21 @@ class ActiveLease {
302
326
  }, 25);
303
327
  }
304
328
  async refreshCurrent() {
305
- return this.activeStatusPath ? this.refreshPath(this.activeStatusPath) : this.refreshLatest();
329
+ // Admission/checkpoint reads must see mandatory publications even while the
330
+ // directory watcher is debouncing an update to a different status path.
331
+ return this.refreshLatest();
332
+ }
333
+ async selectAttachment(statusPath) {
334
+ this.policySelectionRevision += 1;
335
+ const blocked = this.policyBlockedStatusPath;
336
+ const update = await this.refreshPath(statusPath, undefined, true);
337
+ if (update?.kind !== 'updated')
338
+ throw new Error('PLAN_UNAVAILABLE');
339
+ if (update?.kind === 'updated' && blocked && blocked !== statusPath)
340
+ await rm(blocked, { force: true });
306
341
  }
307
342
  async refreshLatest() {
343
+ const policyRevision = this.policySelectionRevision;
308
344
  try {
309
345
  const candidates = (await readdir(this.statusDirectory))
310
346
  .filter((filename) => filename.endsWith(statusFileSuffix))
@@ -314,21 +350,49 @@ class ActiveLease {
314
350
  this.planReadFilesystem.readFile(statusPath, 'utf8').catch(() => ''),
315
351
  stat(statusPath).catch(() => undefined),
316
352
  ]);
317
- return { statusPath, signal: parseSignal(source), modifiedAt: metadata?.mtimeMs ?? 0 };
353
+ return {
354
+ statusPath,
355
+ signal: parseSignal(source),
356
+ modifiedAt: metadata?.mtimeMs ?? 0,
357
+ policyRequired: declaresModelPolicy(source),
358
+ };
318
359
  }));
319
360
  const latest = signals
320
361
  .filter((candidate) => candidate.signal !== null)
321
362
  .sort((left, right) => right.signal.updatedAt.localeCompare(left.signal.updatedAt) ||
322
363
  right.modifiedAt - left.modifiedAt)[0];
323
- return latest ? this.refreshPath(latest.statusPath, latest.signal) : null;
364
+ if (policyRevision !== this.policySelectionRevision)
365
+ return null;
366
+ const invalidPolicy = signals
367
+ .filter((candidate) => !candidate.signal && candidate.policyRequired)
368
+ .sort((a, b) => b.modifiedAt - a.modifiedAt)[0];
369
+ if (invalidPolicy && (!latest || invalidPolicy.modifiedAt >= latest.modifiedAt)) {
370
+ this.policyBlockedStatusPath = invalidPolicy.statusPath;
371
+ return !this.closed ? this.emitUnavailable(true) : null;
372
+ }
373
+ return latest
374
+ ? this.refreshPath(latest.statusPath, latest.signal, true)
375
+ : this.activeStatusPath
376
+ ? this.refreshPath(this.activeStatusPath, undefined, true)
377
+ : null;
324
378
  }
325
379
  catch {
326
380
  return !this.closed ? this.emitUnavailable() : null;
327
381
  }
328
382
  }
329
- async refreshPath(statusPath, parsedSignal) {
383
+ async refreshPath(statusPath, parsedSignal, selectedLatest = false) {
384
+ if (this.policyBlockedStatusPath &&
385
+ !selectedLatest &&
386
+ statusPath !== this.policyBlockedStatusPath)
387
+ return this.refreshLatest();
388
+ let policyRequired = parsedSignal?.modelPolicyVersion === 1;
389
+ const policyRevision = this.policySelectionRevision;
330
390
  try {
331
- const signal = parsedSignal ?? parseSignal(await this.planReadFilesystem.readFile(statusPath, 'utf8'));
391
+ const source = parsedSignal
392
+ ? null
393
+ : await this.planReadFilesystem.readFile(statusPath, 'utf8');
394
+ policyRequired ||= source !== null && declaresModelPolicy(source);
395
+ const signal = parsedSignal ?? parseSignal(source);
332
396
  if (!signal)
333
397
  throw new Error('INVALID_PLAN_STATUS');
334
398
  const [planPath, workspacePath] = await Promise.all([
@@ -346,8 +410,14 @@ class ActiveLease {
346
410
  workspacePath,
347
411
  });
348
412
  if (result.kind === 'available') {
413
+ policyRequired ||= result.plan.modelPolicyVersion === 1;
414
+ if (result.plan.modelPolicyVersion !== signal.modelPolicyVersion)
415
+ throw new Error('MODEL_POLICY_PUBLICATION_MISMATCH');
349
416
  if (!this.closed && !(await this.isDismissed(identity)) && !this.closed) {
417
+ if (policyRevision !== this.policySelectionRevision)
418
+ return null;
350
419
  const previousStatusPath = this.activeStatusPath;
420
+ this.policyBlockedStatusPath = undefined;
351
421
  this.activeStatusPath = statusPath;
352
422
  this.watchActivePlan(planPath);
353
423
  this.onActiveStatusPath(statusPath);
@@ -369,25 +439,44 @@ class ActiveLease {
369
439
  }
370
440
  }
371
441
  else if (!this.closed) {
372
- return this.emitUnavailable();
442
+ if (policyRevision !== this.policySelectionRevision)
443
+ return null;
444
+ policyRequired ||= result.reason === 'INVALID_MODEL_POLICY';
445
+ if (policyRequired)
446
+ this.policyBlockedStatusPath = statusPath;
447
+ return this.emitUnavailable(policyRequired);
373
448
  }
374
449
  return null;
375
450
  }
376
451
  catch (error) {
452
+ if (policyRevision !== this.policySelectionRevision)
453
+ return null;
377
454
  if (error.code === 'ENOENT' &&
378
455
  this.activeStatusPath !== undefined &&
379
456
  statusPath !== this.activeStatusPath)
380
457
  return null;
381
- return !this.closed ? this.emitUnavailable() : null;
458
+ if (policyRequired)
459
+ this.policyBlockedStatusPath = statusPath;
460
+ return !this.closed ? this.emitUnavailable(policyRequired) : null;
382
461
  }
383
462
  }
384
- emitUnavailable() {
463
+ emitUnavailable(modelPolicyRequired = false) {
464
+ if (modelPolicyRequired)
465
+ this.policySelectionRevision += 1;
385
466
  this.lastEmittedUpdate = undefined;
386
- const update = { kind: 'unavailable', code: 'PLAN_STATUS_UNAVAILABLE' };
467
+ const update = {
468
+ kind: 'unavailable',
469
+ code: 'PLAN_STATUS_UNAVAILABLE',
470
+ ...(modelPolicyRequired ? { modelPolicyRequired: true } : {}),
471
+ };
387
472
  this.listener(update);
388
473
  return update;
389
474
  }
390
475
  }
476
+ /** Recognize mandatory policy even when its version/capability envelope cannot be parsed. */
477
+ function declaresModelPolicy(source) {
478
+ return /"modelPolicyVersion"\s*:|"l1-model-policy[^"\r\n]*"/.test(source);
479
+ }
391
480
  function parseSignal(source) {
392
481
  try {
393
482
  const value = JSON.parse(source);
@@ -398,9 +487,25 @@ function parseSignal(source) {
398
487
  return null;
399
488
  if (typeof signal.reason !== 'string' || !isRfc3339Utc(signal.updatedAt))
400
489
  return null;
490
+ const required = signal.requiredCapabilities;
491
+ if (required !== undefined &&
492
+ (!Array.isArray(required) ||
493
+ required.some((capability) => typeof capability !== 'string' ||
494
+ !ORG_PLAN_CAPABILITIES.split(',').includes(capability))))
495
+ return null;
496
+ if (signal.modelPolicyVersion !== undefined &&
497
+ (signal.modelPolicyVersion !== 1 ||
498
+ !Array.isArray(required) ||
499
+ !required.includes('l1-model-policy-v1')))
500
+ return null;
501
+ if (Array.isArray(required) &&
502
+ required.includes('l1-model-policy-v1') &&
503
+ signal.modelPolicyVersion !== 1)
504
+ return null;
401
505
  return {
402
506
  planPath: signal.planPath,
403
507
  updatedAt: signal.updatedAt,
508
+ ...(signal.modelPolicyVersion === 1 ? { modelPolicyVersion: 1 } : {}),
404
509
  reason: isPlanSignalReason(signal.reason) ? signal.reason : null,
405
510
  };
406
511
  }
@@ -3,5 +3,5 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- /** Compiled host assertion; never supplied by config, request or ambient env. */
7
- export const ORG_PLAN_CAPABILITIES = 'suspension-v1,nested-suspension-v1';
6
+ /** Schema/retention support only; never asserts effective runtime enforcement. */
7
+ export const ORG_PLAN_CAPABILITIES = 'suspension-v1,nested-suspension-v1,l1-model-policy-v1';
@@ -16,5 +16,6 @@ export function isPlanSignalReason(value) {
16
16
  return (typeof value === 'string' &&
17
17
  (planSignalReasons.includes(value) ||
18
18
  /^review:[A-Za-z0-9._-]{1,128}:REVIEWED$/.test(value) ||
19
+ /^measure:(start|checkpoint|finish):[A-Za-z0-9._-]{1,128}$/.test(value) ||
19
20
  /^l2:[A-Za-z0-9._-]{1,128}:(WIP|DONE)$/.test(value)));
20
21
  }
@@ -13,6 +13,12 @@
13
13
  "session-verdict",
14
14
  "acknowledgement-safe-composer",
15
15
  "org-plan-contract",
16
- "suspension-v1"
17
- ]
16
+ "suspension-v1",
17
+ "l1-model-policy-v1"
18
+ ],
19
+ "modelPolicyContract": {
20
+ "version": 1,
21
+ "scope": "schema-and-retention",
22
+ "runtimeEnforcement": false
23
+ }
18
24
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.54.1",
3
+ "version": "0.55.0",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",
@@ -5,82 +5,314 @@
5
5
  */
6
6
 
7
7
  import { execFile } from 'node:child_process';
8
+ import { createHash } from 'node:crypto';
9
+ import { mkdir, open, writeFile } from 'node:fs/promises';
10
+ import { dirname, join } from 'node:path';
8
11
  import { promisify } from 'node:util';
9
12
  import { pathToFileURL } from 'node:url';
10
13
  import { setTimeout as sleep } from 'node:timers/promises';
11
14
 
12
15
  const execute = promisify(execFile);
16
+ const statuses = ['queued', 'in_progress', 'completed', 'waiting', 'requested', 'pending'];
17
+ const conclusions = [
18
+ 'success',
19
+ 'failure',
20
+ 'cancelled',
21
+ 'timed_out',
22
+ 'action_required',
23
+ 'neutral',
24
+ 'skipped',
25
+ 'stale',
26
+ 'startup_failure',
27
+ ];
28
+ const passing = ['success', 'neutral', 'skipped'];
29
+ const iso = (value) =>
30
+ typeof value === 'string' && Number.isFinite(Date.parse(value))
31
+ ? new Date(value).toISOString()
32
+ : null;
33
+ const positive = (value) => Number.isSafeInteger(value) && value > 0;
13
34
 
14
- /** Emits structural observations only; timestamps distinguish polling from upstream updates. */
35
+ /** One owner, one expected attempt. Only structural facts reach stdout or evidence. */
15
36
  export async function watchGithubRun({
16
37
  repository,
17
38
  runId,
39
+ attempt,
40
+ candidate,
41
+ evidenceDirectory,
42
+ signal,
43
+ gh = 'gh',
44
+ pollIntervalMs = 30_000,
45
+ maxRetries = 3,
18
46
  read = async () => {
19
- const { stdout } = await execute(
20
- 'gh',
21
- ['run', 'view', runId, '--repo', repository, '--json', 'status,conclusion,updatedAt'],
22
- { timeout: 60_000 },
47
+ const timeout = AbortSignal.timeout(60_000);
48
+ const commandSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
49
+ const command = execute(
50
+ gh,
51
+ [
52
+ 'run',
53
+ 'view',
54
+ runId,
55
+ '--repo',
56
+ repository,
57
+ '--json',
58
+ 'databaseId,attempt,headSha,status,conclusion,updatedAt,jobs',
59
+ ],
60
+ { maxBuffer: 4 * 1024 * 1024, signal: commandSignal },
23
61
  );
24
- return JSON.parse(stdout);
62
+ const closed = new Promise((resolve) => command.child.once('close', resolve));
63
+ try {
64
+ const { stdout } = await command;
65
+ return JSON.parse(stdout);
66
+ } catch (error) {
67
+ if (commandSignal.aborted) {
68
+ // Abort rejects before the child necessarily exits. Reap the same
69
+ // owned child, escalating only if it ignores the initial SIGTERM.
70
+ const force = setTimeout(() => command.child.kill('SIGKILL'), 1_000);
71
+ try {
72
+ await closed;
73
+ } finally {
74
+ clearTimeout(force);
75
+ }
76
+ if (timeout.aborted && !signal?.aborted) error.code = 'ETIMEDOUT';
77
+ }
78
+ throw error;
79
+ }
25
80
  },
26
- wait = () => sleep(30_000),
81
+ wait = (ms) => sleep(ms, undefined, { signal }),
27
82
  now = () => new Date().toISOString(),
28
83
  write = (record) => process.stdout.write(`${JSON.stringify(record)}\n`),
29
84
  }) {
30
- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || !/^\d+$/.test(runId))
31
- throw new Error('Expected repository owner/name and numeric run ID');
32
- for (;;) {
33
- let run;
34
- try {
35
- run = await read();
36
- } catch {
37
- write({ event: 'githubRunObservationFailed', observedAt: now(), runId });
38
- return 1;
85
+ if (
86
+ typeof repository !== 'string' ||
87
+ repository.length > 200 ||
88
+ !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) ||
89
+ typeof runId !== 'string' ||
90
+ !/^[1-9]\d{0,19}$/.test(runId) ||
91
+ !positive(attempt) ||
92
+ typeof candidate !== 'string' ||
93
+ !/^[a-f0-9]{40}$/i.test(candidate) ||
94
+ typeof evidenceDirectory !== 'string' ||
95
+ !evidenceDirectory ||
96
+ Buffer.byteLength(evidenceDirectory) > 512 ||
97
+ Buffer.byteLength(JSON.stringify(evidenceDirectory)) > 600 ||
98
+ !positive(pollIntervalMs) ||
99
+ pollIntervalMs > 300_000 ||
100
+ !Number.isInteger(maxRetries) ||
101
+ maxRetries < 0 ||
102
+ maxRetries > 5
103
+ ) {
104
+ throw new Error('Expected OWNER/REPO RUN_ID ATTEMPT COMMIT_SHA NEW_EVIDENCE_DIRECTORY');
105
+ }
106
+ const identity = { repository, runId, attempt, candidate: candidate.toLowerCase() };
107
+ let journal;
108
+ let bytes = 0;
109
+ const hash = createHash('sha256');
110
+ const counts = { polls: 0, changes: 0, readFailures: 0, failures: 0, jobs: null };
111
+ let firstFailure = null;
112
+ let lastObservation = null;
113
+ let completeness = 'partial';
114
+ const emit = async (event, fields = {}, visible = true) => {
115
+ const record = { event, observedAt: iso(now()), ...identity, ...fields };
116
+ const line = `${JSON.stringify(record)}\n`;
117
+ await journal.writeFile(line);
118
+ hash.update(line);
119
+ bytes += Buffer.byteLength(line);
120
+ if (visible) write(record);
121
+ };
122
+ const finish = async (reason, exitCode) => {
123
+ if (signal?.aborted) {
124
+ reason = 'cancelled';
125
+ exitCode = 130;
126
+ completeness = 'partial';
39
127
  }
40
- if (
41
- !run ||
42
- !['queued', 'in_progress', 'completed', 'waiting', 'requested', 'pending'].includes(
43
- run.status,
44
- )
45
- ) {
46
- write({ event: 'githubRunObservationFailed', observedAt: now(), runId });
47
- return 1;
128
+ const summary = {
129
+ event: 'githubRunFinished',
130
+ observedAt: iso(now()),
131
+ ...identity,
132
+ reason,
133
+ exitCode,
134
+ // This observation precedes process exit; it is not the exit timestamp.
135
+ processExitedAt: null,
136
+ completeness,
137
+ coverage: 'workflow-status-and-failure-identities',
138
+ testCounts: null,
139
+ counts,
140
+ firstFailure,
141
+ upstreamUpdatedAt: lastObservation?.upstreamUpdatedAt ?? null,
142
+ status: lastObservation?.status ?? null,
143
+ conclusion: lastObservation?.conclusion ?? null,
144
+ evidence: {
145
+ directory: evidenceDirectory,
146
+ file: 'events.jsonl',
147
+ bytes,
148
+ sha256: hash.copy().digest('hex'),
149
+ },
150
+ };
151
+ await journal.sync();
152
+ await writeFile(join(evidenceDirectory, 'summary.json'), `${JSON.stringify(summary)}\n`, {
153
+ flag: 'wx',
154
+ mode: 0o600,
155
+ });
156
+ write(summary);
157
+ return exitCode;
158
+ };
159
+ try {
160
+ await mkdir(dirname(evidenceDirectory), { recursive: true });
161
+ // An existing evidence directory belongs to an earlier/active owner. Never
162
+ // overwrite it or launch another poller on the same process evidence handle.
163
+ await mkdir(evidenceDirectory, { mode: 0o700 });
164
+ journal = await open(join(evidenceDirectory, 'events.jsonl'), 'wx', 0o600);
165
+ } catch {
166
+ write({
167
+ event: 'githubRunEvidenceFailed',
168
+ observedAt: iso(now()),
169
+ ...identity,
170
+ reason: 'evidenceUnavailable',
171
+ });
172
+ return 1;
173
+ }
174
+ try {
175
+ let previous = null;
176
+ let retries = 0;
177
+ for (;;) {
178
+ if (signal?.aborted) return await finish('cancelled', 130);
179
+ let run;
180
+ try {
181
+ counts.polls += 1;
182
+ run = await read();
183
+ } catch (error) {
184
+ if (signal?.aborted) return await finish('cancelled', 130);
185
+ // Classify only; command diagnostics may contain credentials or output.
186
+ const diagnostic = String(error?.stderr ?? error?.code ?? '');
187
+ const rateLimited = /rate limit|HTTP 429/i.test(diagnostic);
188
+ const transient =
189
+ rateLimited ||
190
+ /HTTP 5\d\d|ECONN|ETIMEDOUT|ENET|EAI_AGAIN|TLS handshake|could not resolve|connection|timeout/i.test(
191
+ diagnostic,
192
+ ) ||
193
+ error?.killed === true;
194
+ counts.readFailures += 1;
195
+ await emit('githubRunObservationFailed', {
196
+ reason: rateLimited ? 'rateLimited' : transient ? 'network' : 'readFailed',
197
+ retry: transient && retries < maxRetries,
198
+ });
199
+ if (!transient || retries >= maxRetries) return await finish('observationFailed', 1);
200
+ await wait(Math.min(120_000, pollIntervalMs * 2 ** retries++));
201
+ continue;
202
+ }
203
+ // A response after cancellation must not certify late success.
204
+ if (signal?.aborted) return await finish('cancelled', 130);
205
+ retries = 0;
206
+ if (
207
+ !run ||
208
+ String(run.databaseId) !== runId ||
209
+ run.attempt !== attempt ||
210
+ typeof run.headSha !== 'string' ||
211
+ run.headSha.toLowerCase() !== identity.candidate
212
+ ) {
213
+ await emit('githubRunIdentityChanged', { reason: 'identityMismatch' });
214
+ return await finish('identityMismatch', 1);
215
+ }
216
+ if (!statuses.includes(run.status)) {
217
+ await emit('githubRunObservationFailed', { reason: 'unknownStatus', retry: false });
218
+ return await finish('unknownStatus', 1);
219
+ }
220
+ const conclusion = conclusions.includes(run.conclusion) ? run.conclusion : null;
221
+ lastObservation = { status: run.status, conclusion, upstreamUpdatedAt: iso(run.updatedAt) };
222
+ const semantic = JSON.stringify([run.status, conclusion]);
223
+ if (semantic !== previous) {
224
+ counts.changes += 1;
225
+ await emit('githubRunObserved', lastObservation);
226
+ previous = semantic;
227
+ }
228
+ if (run.status === 'completed') {
229
+ completeness = Array.isArray(run.jobs) ? 'complete' : 'partial';
230
+ counts.jobs = Array.isArray(run.jobs) ? run.jobs.length : null;
231
+ for (const job of Array.isArray(run.jobs) ? run.jobs : []) {
232
+ const jobId = positive(job?.databaseId) ? String(job.databaseId) : null;
233
+ if (!jobId || !conclusions.includes(job?.conclusion) || job?.status !== 'completed')
234
+ completeness = 'partial';
235
+ if (passing.includes(job?.conclusion)) continue;
236
+ const steps = Array.isArray(job?.steps)
237
+ ? job.steps.filter((step) => step?.conclusion && !passing.includes(step.conclusion))
238
+ : [];
239
+ if (
240
+ !Array.isArray(job?.steps) ||
241
+ job.steps.some(
242
+ (step) => !positive(step?.number) || !conclusions.includes(step?.conclusion),
243
+ )
244
+ )
245
+ completeness = 'partial';
246
+ for (const step of steps.length ? steps : [null]) {
247
+ const failure = {
248
+ jobId,
249
+ stepNumber: positive(step?.number) ? step.number : null,
250
+ conclusion: conclusions.includes(step?.conclusion ?? job?.conclusion)
251
+ ? (step?.conclusion ?? job?.conclusion)
252
+ : null,
253
+ };
254
+ if (step && (!positive(step.number) || !conclusions.includes(step.conclusion)))
255
+ completeness = 'partial';
256
+ counts.failures += 1;
257
+ firstFailure ??= failure;
258
+ await emit('githubJobFailed', failure, false);
259
+ }
260
+ }
261
+ if (conclusion && !passing.includes(conclusion) && !firstFailure) {
262
+ firstFailure = { jobId: null, stepNumber: null, conclusion };
263
+ counts.failures += 1;
264
+ await emit('githubRunFailed', firstFailure, false);
265
+ }
266
+ if (!conclusion) completeness = 'partial';
267
+ return await finish(
268
+ 'completed',
269
+ conclusion === 'success' && completeness === 'complete' && counts.failures === 0 ? 0 : 1,
270
+ );
271
+ }
272
+ await wait(pollIntervalMs);
273
+ }
274
+ } catch {
275
+ if (signal?.aborted) {
276
+ try {
277
+ return await finish('cancelled', 130);
278
+ } catch {
279
+ /* Preserve incomplete evidence below. */
280
+ }
48
281
  }
49
- const conclusion = [
50
- 'success',
51
- 'failure',
52
- 'cancelled',
53
- 'timed_out',
54
- 'action_required',
55
- 'neutral',
56
- 'skipped',
57
- 'stale',
58
- 'startup_failure',
59
- ].includes(run.conclusion)
60
- ? run.conclusion
61
- : null;
62
282
  write({
63
- event: 'githubRunObserved',
64
- observedAt: now(),
65
- runId,
66
- status: run.status,
67
- conclusion,
68
- upstreamUpdatedAt:
69
- typeof run.updatedAt === 'string' && Number.isFinite(Date.parse(run.updatedAt))
70
- ? new Date(run.updatedAt).toISOString()
71
- : null,
283
+ event: 'githubRunEvidenceFailed',
284
+ observedAt: iso(now()),
285
+ ...identity,
286
+ reason: 'evidenceIncomplete',
72
287
  });
73
- if (run.status === 'completed') return conclusion === 'success' ? 0 : 1;
74
- await wait();
288
+ return 1;
289
+ } finally {
290
+ await journal.close();
75
291
  }
76
292
  }
77
293
 
78
294
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
79
- const [repository, runId] = process.argv.slice(2);
295
+ const [repository, runId, attempt, candidate, evidenceDirectory] = process.argv.slice(2);
296
+ const controller = new AbortController();
297
+ const cancel = () => controller.abort();
298
+ process.once('SIGINT', cancel);
299
+ process.once('SIGTERM', cancel);
80
300
  try {
81
- process.exitCode = await watchGithubRun({ repository, runId });
301
+ process.exitCode = await watchGithubRun({
302
+ repository,
303
+ runId,
304
+ attempt: Number(attempt),
305
+ candidate,
306
+ evidenceDirectory,
307
+ signal: controller.signal,
308
+ });
82
309
  } catch {
83
- process.stderr.write('Usage: node watch-github-run.mjs OWNER/REPO RUN_ID\n');
310
+ process.stderr.write(
311
+ 'Usage: node watch-github-run.mjs OWNER/REPO RUN_ID ATTEMPT COMMIT_SHA NEW_EVIDENCE_DIRECTORY\n',
312
+ );
84
313
  process.exitCode = 1;
314
+ } finally {
315
+ process.removeListener('SIGINT', cancel);
316
+ process.removeListener('SIGTERM', cancel);
85
317
  }
86
318
  }