omp-superagent 0.1.6 → 0.1.8

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 (90) hide show
  1. package/DESIGN.md +36 -20
  2. package/README.ko.md +140 -33
  3. package/README.md +165 -41
  4. package/THIRD_PARTY_NOTICES.md +9 -7
  5. package/config.example.json +3 -1
  6. package/docs/OPERATIONS.md +395 -157
  7. package/docs/design/execution.md +156 -22
  8. package/docs/design/messaging.md +258 -52
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.7.md +25 -0
  11. package/docs/releases/0.1.8.md +21 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  17. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  20. package/package.json +9 -9
  21. package/scripts/ci.ts +4 -4
  22. package/scripts/test-omp.sh +2 -1
  23. package/skills/head/SKILL.md +26 -5
  24. package/skills/head/references/routing.md +68 -33
  25. package/skills/head/references/supervision.md +20 -4
  26. package/skills/lane/references/workflow.md +16 -7
  27. package/src/board.ts +5 -3
  28. package/src/cli.ts +161 -19
  29. package/src/config.ts +21 -1
  30. package/src/contracts.ts +63 -8
  31. package/src/cron-jobs.ts +443 -19
  32. package/src/cron-pr-intake.ts +257 -0
  33. package/src/discord-markdown.ts +350 -123
  34. package/src/extension.ts +78 -13
  35. package/src/gateway-client.ts +8 -2
  36. package/src/head-quota.ts +80 -0
  37. package/src/head-recovery.ts +40 -1
  38. package/src/host-extension.ts +122 -4
  39. package/src/host-inventory-manifest.ts +2 -2
  40. package/src/host-protocol.ts +11 -0
  41. package/src/host-sdk-helper.ts +121 -12
  42. package/src/host.ts +175 -57
  43. package/src/installed-omp.ts +116 -4
  44. package/src/lane-rows.ts +44 -4
  45. package/src/lane-watch.ts +339 -0
  46. package/src/managed-memory-helper.ts +13 -10
  47. package/src/managed-memory.ts +62 -27
  48. package/src/managed-ulw-probe.ts +75 -20
  49. package/src/managed-ulw.ts +174 -21
  50. package/src/messenger-command-catalog.json +2 -2
  51. package/src/native-launch-profile.ts +4 -2
  52. package/src/native-presets.ts +32 -5
  53. package/src/native-sessions.ts +3 -1
  54. package/src/native-settings.ts +47 -9
  55. package/src/observation-request.ts +23 -0
  56. package/src/omp-usage.ts +254 -36
  57. package/src/pr-github-schema.ts +5 -1
  58. package/src/pr-github.ts +68 -19
  59. package/src/pr-intake-automation.ts +316 -0
  60. package/src/pr-intake-comment.ts +226 -0
  61. package/src/pr-intake-fix.ts +233 -0
  62. package/src/pr-intake-github.ts +480 -0
  63. package/src/pr-intake-material.ts +230 -0
  64. package/src/pr-intake-mode.ts +59 -0
  65. package/src/pr-intake-review.ts +397 -0
  66. package/src/pr-intake-tree.ts +69 -0
  67. package/src/pr-intake-work.ts +29 -0
  68. package/src/pr-watch.ts +91 -32
  69. package/src/runtime.ts +2702 -391
  70. package/src/setup-judge.ts +1 -1
  71. package/src/setup.ts +12 -16
  72. package/src/store.ts +429 -86
  73. package/src/topic-history.ts +243 -47
  74. package/src/worker-checkout.ts +106 -0
  75. package/src/worker-destination.ts +10 -0
  76. package/src/worker-doctor.ts +66 -0
  77. package/src/worker-enrollment.ts +165 -0
  78. package/src/worker-host.ts +180 -0
  79. package/src/worker-ledger.ts +188 -0
  80. package/src/worker-placement.ts +78 -0
  81. package/src/worker-profile.ts +274 -0
  82. package/src/worker-registration.ts +288 -0
  83. package/src/worker-repository.ts +233 -0
  84. package/src/worker-request.ts +74 -0
  85. package/src/worker-service.ts +230 -0
  86. package/src/worker-stdio.ts +61 -0
  87. package/src/worker-trust.ts +36 -0
  88. package/src/worker-wire.ts +204 -0
  89. package/src/workflow.ts +81 -32
  90. package/src/setup-memory.ts +0 -21
package/src/pr-github.ts CHANGED
@@ -2,11 +2,15 @@ import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { Type, type Static, type TSchema } from "@sinclair/typebox/type";
4
4
  import {
5
- PrReadError, checkPageSchema, commentSchema, comparePageSchema, loginSchema, metadataSchema,
5
+ PrReadError, checkPageSchema, type ciOutcomeSchema, commentSchema, comparePageSchema, loginSchema, metadataSchema,
6
6
  pages, parseWire, reviewSchema, safeText, safeUrl, sha, statusSchema, timelineSchema,
7
7
  } from "./pr-github-schema";
8
8
 
9
9
  export type PrRef = { readonly owner: string; readonly repo: string; readonly number: number };
10
+ type CiPass = "passed" | "passed_with_skips";
11
+ type PrCi =
12
+ | { readonly outcome: Exclude<Static<typeof ciOutcomeSchema>, CiPass> }
13
+ | { readonly outcome: CiPass; readonly key: string; readonly skipped: number };
10
14
  export type PrSnapshot = {
11
15
  readonly head: string;
12
16
  readonly state: "open" | "closed" | "merged";
@@ -18,6 +22,7 @@ export type PrSnapshot = {
18
22
  readonly failures: readonly {
19
23
  readonly key: string; readonly name: string; readonly url: string; readonly conclusion: string;
20
24
  }[];
25
+ readonly ci: PrCi;
21
26
  readonly headChange: "self" | "external" | "rewritten" | "unknown";
22
27
  };
23
28
 
@@ -38,12 +43,12 @@ export function prKey(ref: PrRef): string {
38
43
  return `${parsed.owner}/${parsed.repo}#${parsed.number}`;
39
44
  }
40
45
 
41
- async function api<T extends TSchema>(endpoint: string, schema: T, signal: AbortSignal): Promise<Static<T>> {
46
+ async function api<T extends TSchema>(endpoint: string, schema: T, signal: AbortSignal, env?: NodeJS.ProcessEnv): Promise<Static<T>> {
42
47
  if (signal.aborted) throw new PrReadError("aborted");
43
48
  const output = await new Promise<string>((resolve, reject) => {
44
49
  execFile("gh", ["api", "--hostname", "github.com", "--method", "GET", "--paginate", "--slurp",
45
50
  "--header", "Accept: application/vnd.github+json", endpoint],
46
- { encoding: "utf8", timeout: 30_000, maxBuffer: 16 * 1024 * 1024, signal }, (error, stdout) => {
51
+ { encoding: "utf8", timeout: 30_000, maxBuffer: 16 * 1024 * 1024, signal, env }, (error, stdout) => {
47
52
  if (error) reject(new PrReadError(signal.aborted ? "aborted" : "request"));
48
53
  else resolve(stdout);
49
54
  });
@@ -52,6 +57,8 @@ async function api<T extends TSchema>(endpoint: string, schema: T, signal: Abort
52
57
  return parseWire(schema, output);
53
58
  }
54
59
 
60
+ export { api as readGitHubApi };
61
+
55
62
  function fingerprint(value: unknown): string {
56
63
  return createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 24);
57
64
  }
@@ -61,6 +68,20 @@ function unique<T extends { readonly key: string }>(rows: readonly T[]): T[] {
61
68
  .sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
62
69
  }
63
70
 
71
+ async function readCheckRuns(root: string, head: string, signal: AbortSignal) {
72
+ const checks = await api(`${root}/commits/${head}/check-runs?per_page=100&filter=latest`, pages(checkPageSchema), signal);
73
+ const runs = checks.flatMap(page => page.check_runs);
74
+ const checkCount = checks[0]?.total_count;
75
+ if (checks.some(page => page.total_count !== checkCount) || runs.length !== checkCount
76
+ || new Set(runs.map(run => run.id)).size !== checkCount
77
+ || runs.some(run => run.head_sha !== head)) throw new PrReadError("response");
78
+ return runs.sort((left, right) => left.id - right.id);
79
+ }
80
+
81
+ function checkAttempt(run: Static<typeof checkPageSchema>["check_runs"][number]): string {
82
+ return `check:${run.id}:${fingerprint([run.started_at, run.completed_at, run.conclusion])}`;
83
+ }
84
+
64
85
  export async function readPrSnapshot(
65
86
  ref: PrRef, options: { readonly previousHead?: string; readonly signal: AbortSignal },
66
87
  ): Promise<PrSnapshot> {
@@ -80,12 +101,8 @@ export async function readPrSnapshot(
80
101
  const reviewComments = (await api(`${endpoint}/comments?per_page=100`, pages(Type.Array(commentSchema)), signal)).flat();
81
102
  const reviews = (await api(`${endpoint}/reviews?per_page=100`, pages(Type.Array(reviewSchema)), signal)).flat();
82
103
  const timeline = (await api(`${root}/issues/${parsed.number}/timeline?per_page=100`, pages(Type.Array(timelineSchema)), signal)).flat();
83
- const checks = await api(`${root}/commits/${head}/check-runs?per_page=100&filter=latest`, pages(checkPageSchema), signal);
104
+ const runs = await readCheckRuns(root, head, signal);
84
105
  const statuses = (await api(`${root}/commits/${head}/statuses?per_page=100`, pages(Type.Array(statusSchema)), signal)).flat();
85
- const runs = checks.flatMap(page => page.check_runs);
86
- const checkCount = checks[0]?.total_count;
87
- if (checks.some(page => page.total_count !== checkCount) || new Set(runs.map(run => run.id)).size !== checkCount
88
- || runs.some(run => run.head_sha !== head)) throw new PrReadError("response");
89
106
 
90
107
  const feedback: PrSnapshot["feedback"][number][] = [];
91
108
  for (const [kind, rows] of [["issue_comment", comments], ["review_comment", reviewComments]] as const) {
@@ -113,12 +130,22 @@ export async function readPrSnapshot(
113
130
  }
114
131
  }
115
132
  const failures: PrSnapshot["failures"][number][] = [];
133
+ const successes: string[] = [];
134
+ const skips: string[] = [];
135
+ let ciPending = false;
116
136
  for (const run of runs) {
117
- if (run.status !== "completed" || run.conclusion === null || ["success", "neutral", "skipped"].includes(run.conclusion)) continue;
118
- failures.push({
119
- key: `check:${run.id}:${fingerprint([run.started_at, run.completed_at, run.conclusion])}`,
120
- name: safeText(run.name, 256), url: safeUrl(run.html_url), conclusion: run.conclusion,
121
- });
137
+ const key = checkAttempt(run);
138
+ if (run.status !== "completed" || run.conclusion === null) { ciPending = true; continue; }
139
+ switch (run.conclusion) {
140
+ case "success":
141
+ if (run.completed_at) successes.push(key);
142
+ else ciPending = true;
143
+ break;
144
+ case "neutral": case "skipped": skips.push(key); break;
145
+ default:
146
+ failures.push({ key, name: safeText(run.name, 256), url: safeUrl(run.html_url), conclusion: run.conclusion });
147
+ break;
148
+ }
122
149
  }
123
150
  // Status history includes old failures superseded by a pending/success rerun.
124
151
  const latestStatuses = new Map<string, Static<typeof statusSchema>>();
@@ -127,11 +154,33 @@ export async function readPrSnapshot(
127
154
  if (!previous || status.id > previous.id) latestStatuses.set(status.context, status);
128
155
  }
129
156
  for (const status of latestStatuses.values()) {
130
- if (status.state !== "error" && status.state !== "failure") continue;
131
- failures.push({
132
- key: `status:${status.id}`, name: safeText(status.context, 256),
133
- url: safeUrl(status.target_url), conclusion: status.state,
134
- });
157
+ const key = `status:${status.id}`;
158
+ switch (status.state) {
159
+ case "success": successes.push(key); break;
160
+ case "pending": ciPending = true; break;
161
+ case "error": case "failure":
162
+ failures.push({ key, name: safeText(status.context, 256), url: safeUrl(status.target_url), conclusion: status.state });
163
+ break;
164
+ }
165
+ }
166
+ // This is observed commit CI, not GitHub's required-check or mergeability decision.
167
+ const ci: PrCi = failures.length ? { outcome: "failed" }
168
+ : ciPending ? { outcome: "pending" }
169
+ : successes.length ? {
170
+ outcome: skips.length ? "passed_with_skips" : "passed",
171
+ key: `ci-pass:${head}:${fingerprint([successes.sort(), skips.sort()])}`,
172
+ skipped: skips.length,
173
+ }
174
+ : { outcome: skips.length ? "skipped" : "missing" };
175
+
176
+ if ("key" in ci) {
177
+ // A rerun can change checks without moving the PR head. Bracket the
178
+ // status sample with complete check-run reads before claiming a pass.
179
+ const confirmed = await readCheckRuns(root, head, signal);
180
+ if (confirmed.length !== runs.length || confirmed.some((run, index) => {
181
+ const previous = runs[index];
182
+ return !previous || previous.status !== run.status || checkAttempt(previous) !== checkAttempt(run);
183
+ })) throw new PrReadError("ci-changed");
135
184
  }
136
185
 
137
186
  let headChange: PrSnapshot["headChange"] = "unknown";
@@ -165,6 +214,6 @@ export async function readPrSnapshot(
165
214
  || end.merge_commit_sha !== start.merge_commit_sha) throw new PrReadError("changed");
166
215
  return {
167
216
  head, state: start.merged ? "merged" : start.state, mergedSha: start.merged ? start.merge_commit_sha : null,
168
- self, feedback: unique(feedback), failures: unique(failures), headChange,
217
+ self, feedback: unique(feedback), failures: unique(failures), ci, headChange,
169
218
  };
170
219
  }
@@ -0,0 +1,316 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Type, type Static } from "@sinclair/typebox/type";
3
+ import type { StorePort } from "./contracts";
4
+ import { PrReadError, parseWire } from "./pr-github-schema";
5
+ import { inspectIntakeComment, publishIntakeComment } from "./pr-intake-comment";
6
+ import { applyIntakeFix, parseIntakeFix, reconcileIntakeFix } from "./pr-intake-fix";
7
+ import { inspectIntakeMerge, mergeIntakePull } from "./pr-intake-github";
8
+ import { IntakeMaterialError, readIntakeMaterial, readIntakeMaterialTarget } from "./pr-intake-material";
9
+ import type { PrIntakeMode } from "./pr-intake-mode";
10
+ import type { ReviewRound } from "./pr-intake-review";
11
+
12
+ // allow: SIZE_OK - This state machine owns the PR-wide ledger and its single write fence.
13
+ const maxHeads = 3;
14
+ const rank = { review: 0, fix: 1, merge: 2 } as const;
15
+ const sha = Type.String({ pattern: "^[a-f0-9]{40}$" });
16
+ const hash = Type.String({ pattern: "^[a-f0-9]{64}$" });
17
+ const nonempty = Type.String({ minLength: 1 });
18
+ const materialSchema = Type.Object({ digest: hash, baseRef: nonempty, baseSha: sha, headRef: nonempty });
19
+ const proof = {
20
+ head: sha, inputId: nonempty, answerDigest: hash, material: materialSchema,
21
+ };
22
+ const receipt = Type.Union([
23
+ Type.Object({ ...proof, state: Type.Literal("pending") }),
24
+ Type.Object({ ...proof, state: Type.Literal("unknown") }),
25
+ Type.Object({ ...proof, state: Type.Literal("refused"), reason: nonempty }),
26
+ Type.Object({ ...proof, state: Type.Literal("confirmed"), id: nonempty }),
27
+ ]);
28
+ const ledger = Type.Object({
29
+ ownerId: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
30
+ lineage: Type.Object({ revision: nonempty, heads: Type.Array(sha, { maxItems: maxHeads, uniqueItems: true }) }),
31
+ nextHead: Type.Optional(sha),
32
+ comments: Type.Array(receipt),
33
+ fix: Type.Optional(receipt),
34
+ merge: Type.Optional(receipt),
35
+ });
36
+ const verdictSchema = Type.Object({
37
+ verdict: Type.Union([Type.Literal("approve"), Type.Literal("blocked"), Type.Literal("fix")]),
38
+ summary: Type.String({ minLength: 1, maxLength: 2048 }),
39
+ });
40
+ const key = (r: Scope) => `pr-intake-automation:${r.repositoryId}:${r.number}`;
41
+ const digest = (s: string) => createHash("sha256").update(s).digest("hex");
42
+
43
+ export const prIntakeAutomationApis = {
44
+ inspectIntakeComment, publishIntakeComment, applyIntakeFix, reconcileIntakeFix,
45
+ inspectIntakeMerge, mergeIntakePull, readIntakeMaterial,
46
+ };
47
+ type Scope = Pick<ReviewRound, "repositoryId" | "number">;
48
+ type Ledger = Readonly<Static<typeof ledger>>;
49
+ type Receipt = Readonly<Static<typeof receipt>>;
50
+ type CommitReceipt = Exclude<Receipt, { state: "confirmed" }>
51
+ | (Extract<Receipt, { state: "confirmed" }> & { readonly sha: string });
52
+ type Effect = "comment" | "fix" | "merge";
53
+ type Submission =
54
+ | { readonly status: "confirmed"; readonly id: string }
55
+ | { readonly status: "blocked" | "unknown"; readonly reason: string };
56
+ export type PrIntakeAutomationState = Omit<Ledger, "fix" | "merge"> & {
57
+ readonly comment?: Receipt;
58
+ readonly fix?: CommitReceipt;
59
+ readonly merge?: CommitReceipt;
60
+ };
61
+ export type PrIntakeAutomationEvidence = { readonly answer: string; readonly material: Readonly<Static<typeof materialSchema>> };
62
+ export type PrIntakeAutomationDeps = {
63
+ readonly store: Pick<StorePort, "getMeta" | "setMeta">;
64
+ readonly mode: PrIntakeMode;
65
+ readonly observedHead: string | null;
66
+ readonly evidence: PrIntakeAutomationEvidence | null;
67
+ readonly verify: (stage: PrIntakeMode) => void;
68
+ readonly signal: AbortSignal;
69
+ readonly reconcileOnly?: boolean;
70
+ readonly api?: Partial<typeof prIntakeAutomationApis>;
71
+ };
72
+ export type PrIntakeAutomationProgress = {
73
+ readonly status: "waiting" | "held" | "unknown" | "commented" | "fixed" | "merged";
74
+ readonly message: string;
75
+ readonly nextHead?: string;
76
+ };
77
+
78
+ export class PrIntakeAutomationError extends Error {}
79
+ class ReviewedMaterialChanged extends PrIntakeAutomationError {}
80
+
81
+ function decode(raw: string): Ledger {
82
+ try { return parseWire(ledger, raw); }
83
+ catch (error) {
84
+ if (error instanceof PrReadError) throw new PrIntakeAutomationError("Invalid durable PR automation state.", { cause: error });
85
+ throw error;
86
+ }
87
+ }
88
+
89
+ export function readPrIntakeAutomation(store: Pick<StorePort, "getMeta">, scope: Scope): PrIntakeAutomationState | null {
90
+ const raw = store.getMeta(key(scope));
91
+ if (raw === null) return null;
92
+ const saved = decode(raw);
93
+ const commitReceipt = (entry: Receipt | undefined): CommitReceipt | undefined =>
94
+ entry?.state === "confirmed" ? { ...entry, sha: entry.id } : entry;
95
+ return { ...saved, comment: saved.comments.at(-1), fix: commitReceipt(saved.fix), merge: commitReceipt(saved.merge) };
96
+ }
97
+
98
+ function unresolved(receipt: Receipt | undefined): receipt is Extract<Receipt, { state: "pending" | "unknown" }> {
99
+ return receipt?.state === "pending" || receipt?.state === "unknown";
100
+ }
101
+
102
+ export function prIntakeManualHold(
103
+ store: Pick<StorePort, "getMeta">, scope: Scope, action: "pr-review" | "pr-fix" | "pr-merge", head?: string,
104
+ ): string | null {
105
+ const state = readPrIntakeAutomation(store, scope);
106
+ if (!state) return null;
107
+ if (state.comments.some(unresolved) || unresolved(state.fix) || unresolved(state.merge))
108
+ return "An automatic GitHub write is unresolved for this PR. Reconcile it read-only before any new review or write.";
109
+ if (state.merge?.state === "confirmed") return `GitHub already confirmed merge ${state.merge.id}.`;
110
+ if (state.fix?.state === "confirmed" && state.fix.head === head)
111
+ return `GitHub already confirmed fix ${state.fix.id}. Review the current head instead.`;
112
+ if (action !== "pr-review" && state.nextHead && head === state.lineage.heads.at(-1))
113
+ return `The PR moved to ${state.nextHead}. Review the current head instead.`;
114
+ return null;
115
+ }
116
+
117
+ function parseVerdict(answer: string) {
118
+ if (Buffer.byteLength(answer) > 64 * 1024) return null;
119
+ try {
120
+ const value = parseWire(verdictSchema, answer);
121
+ if (!value.summary.trim()) return null;
122
+ if (value.verdict === "fix") {
123
+ const proposal = parseIntakeFix(answer);
124
+ if (!proposal) return null;
125
+ // A model may echo the proposed source inside its prose, not just in the fix fields.
126
+ const snippets = [proposal.old, proposal.replacement].sort((a, b) => b.length - a.length);
127
+ const summary = snippets.reduce((text, snippet) => snippet ? text.replaceAll(snippet, "[source omitted]") : text, value.summary);
128
+ return { verdict: "fix" as const, summary, proposal };
129
+ }
130
+ const keys = [...answer.matchAll(/"(?:[^"\\]|\\[\s\S])*"/g)]
131
+ .filter(token => /^\s*:/.test(answer.slice(token.index + token[0].length)));
132
+ return keys.length === 2 && Object.keys(value).length === 2 ? { ...value, verdict: value.verdict } : null;
133
+ } catch (error) {
134
+ if (error instanceof PrReadError) return null;
135
+ throw error;
136
+ }
137
+ }
138
+
139
+ const waiting = (message: string): PrIntakeAutomationProgress => ({ status: "waiting", message });
140
+ const held = (message: string): PrIntakeAutomationProgress => ({ status: "held", message });
141
+
142
+ export async function advancePrIntakeAutomation(r: ReviewRound, d: PrIntakeAutomationDeps): Promise<PrIntakeAutomationProgress> {
143
+ if (!r.automation || d.signal.aborted) return held("No live unattended review registration.");
144
+ const { revision } = r.automation;
145
+ const api = { ...prIntakeAutomationApis, ...d.api };
146
+ const { repository, number, head } = r;
147
+ const { signal, evidence } = d;
148
+ const observed = d.observedHead;
149
+ let raw = d.store.getMeta(key(r));
150
+ let state: Ledger = raw === null ? { ownerId: r.ownerId, lineage: { revision, heads: [] }, comments: [] } : decode(raw);
151
+ if (state.ownerId !== r.ownerId) return held("The original automatic PR owner does not match.");
152
+ if (state.merge?.state === "confirmed") return { status: "merged", message: `GitHub confirmed merge ${state.merge.id}.` };
153
+ const check = (stage: PrIntakeMode) => {
154
+ if (signal.aborted || !(rank[d.mode] >= rank[stage])) throw new PrIntakeAutomationError("The unattended stage is no longer permitted.");
155
+ d.verify(stage);
156
+ };
157
+ const save = (next: Ledger) => {
158
+ if (d.store.getMeta(key(r)) !== raw) throw new PrIntakeAutomationError("The durable automatic PR state changed.");
159
+ const value = JSON.stringify(next);
160
+ d.store.setMeta(key(r), value);
161
+ raw = value;
162
+ state = next;
163
+ };
164
+ const saveEffect = (effect: Effect, entry: Receipt) => save(effect === "comment"
165
+ ? { ...state, comments: [...state.comments.filter(item => item.head !== entry.head), entry] }
166
+ : { ...state, [effect]: entry });
167
+ const answerDigest = evidence && digest(evidence.answer);
168
+ const verdict = evidence && parseVerdict(evidence.answer);
169
+ const pendingComment = state.comments.find(unresolved);
170
+ const pending = pendingComment ? { kind: "comment", entry: pendingComment } as const
171
+ : unresolved(state.fix) ? { kind: "fix", entry: state.fix } as const
172
+ : unresolved(state.merge) ? { kind: "merge", entry: state.merge } as const : null;
173
+ if (pending) {
174
+ const { kind, entry } = pending;
175
+ const unknown: PrIntakeAutomationProgress = { status: "unknown", message: `Automatic ${kind} remains unconfirmed. No write was repeated.` };
176
+ if (entry.inputId !== r.inputId || entry.head !== head) return unknown;
177
+ const target = { ...r, ...entry.material };
178
+ switch (kind) {
179
+ case "comment": {
180
+ if (!verdict || entry.answerDigest !== answerDigest) return unknown;
181
+ const result = await api.inspectIntakeComment(repository, number, head, verdict.summary, signal, target);
182
+ if (result.status !== "posted") return unknown;
183
+ saveEffect(kind, { ...entry, state: "confirmed", id: result.id });
184
+ return { status: "commented", message: `GitHub confirmed the review comment for ${head}.` };
185
+ }
186
+ case "fix": {
187
+ if (verdict?.verdict !== "fix" || entry.answerDigest !== answerDigest) return unknown;
188
+ const result = await api.reconcileIntakeFix(repository, number, head, verdict.proposal, signal, target.headRef, r);
189
+ if (result.status !== "applied") return unknown;
190
+ saveEffect(kind, { ...entry, state: "confirmed", id: result.sha });
191
+ return { status: "fixed", message: `GitHub confirmed fix ${result.sha}.` };
192
+ }
193
+ case "merge": {
194
+ const result = await api.inspectIntakeMerge(repository, number, head, signal, target);
195
+ if (result.status !== "merged") return unknown;
196
+ saveEffect(kind, { ...entry, state: "confirmed", id: result.sha });
197
+ return { status: "merged", message: `GitHub confirmed merge ${result.sha}.` };
198
+ }
199
+ }
200
+ }
201
+ if (d.reconcileOnly) return waiting("No unresolved automatic GitHub write for this PR.");
202
+
203
+ check("review");
204
+ const fixed = state.fix?.state === "confirmed" ? state.fix : null;
205
+ if (fixed && fixed.head === head && (observed === head || !observed))
206
+ return { status: "fixed", message: `GitHub confirmed fix ${fixed.id}; a review of the current head is required before merge.` };
207
+ if (!observed) return waiting("The current open PR head was not observed. No GitHub write was attempted.");
208
+ const heads = state.lineage.revision === revision ? state.lineage.heads : [];
209
+ if (heads.at(-1) !== head) {
210
+ if (heads.includes(head) || heads.length >= maxHeads) return held("Automatic review head limit reached; use a fresh owner review.");
211
+ const { nextHead, ...rest } = state;
212
+ if (nextHead && state.lineage.revision === revision && nextHead !== head)
213
+ return held("The newly placed review does not match the reserved automatic head.");
214
+ save({ ...rest, lineage: { revision, heads: [...heads, head] } });
215
+ }
216
+ if (observed !== head) {
217
+ if (state.lineage.heads.includes(observed) || state.lineage.heads.length >= maxHeads)
218
+ return held("The head changed to a prior revision or reached the automatic review limit; use a fresh owner review.");
219
+ if (state.nextHead !== observed) save({ ...state, nextHead: observed });
220
+ return { status: "waiting", message: `The head changed; full static review required for ${observed}.`, nextHead: observed };
221
+ }
222
+ // A reservation may have become obsolete before its review started (e.g. a force push).
223
+ if (state.nextHead) {
224
+ const { nextHead: _, ...current } = state;
225
+ save(current);
226
+ }
227
+ if (!evidence || !answerDigest) return waiting("Waiting for the original native review and its confirmed delivery.");
228
+ if (!verdict) return held("The delivered native review is not an exact supported verdict.");
229
+ const savedComment = state.comments.find(item => item.head === head);
230
+ if (savedComment?.state === "refused") return held(savedComment.reason);
231
+ if (savedComment?.state === "confirmed"
232
+ && (savedComment.answerDigest !== answerDigest || savedComment.material.digest !== evidence.material.digest))
233
+ return held("A review comment already exists for this head, but not for the current review evidence.");
234
+
235
+ const entry = { head, inputId: r.inputId, answerDigest, material: evidence.material };
236
+ const target = { ...r, ...evidence.material };
237
+ const verifyMaterial = (material: string) => {
238
+ const parsed = readIntakeMaterialTarget(material);
239
+ if (digest(material) !== target.digest || parsed.baseRef !== target.baseRef
240
+ || parsed.baseSha !== target.baseSha || parsed.headRef !== target.headRef)
241
+ throw new ReviewedMaterialChanged("The current PR material does not match the delivered review.");
242
+ };
243
+ const readReviewed = async () => {
244
+ verifyMaterial(await api.readIntakeMaterial(repository, number, head, signal, r));
245
+ };
246
+
247
+ const submit = async (kind: Effect, stage: PrIntakeMode, run: (beforeWrite: () => void) => Promise<Submission>) => {
248
+ check(stage);
249
+ let attempted = false;
250
+ const result = await run(() => {
251
+ check(stage);
252
+ if (attempted) throw new PrIntakeAutomationError("An automatic GitHub write cannot be sent a second time.");
253
+ saveEffect(kind, { ...entry, state: "pending" });
254
+ attempted = true;
255
+ });
256
+ switch (result.status) {
257
+ case "confirmed":
258
+ if (kind === "fix" && !attempted) throw new PrIntakeAutomationError("Fix confirmation lacks its durable send fence.");
259
+ saveEffect(kind, { ...entry, state: "confirmed", id: result.id });
260
+ return { ...result, attempted };
261
+ case "unknown":
262
+ saveEffect(kind, { ...entry, state: "unknown" });
263
+ return { ...result, attempted };
264
+ case "blocked":
265
+ if (attempted) saveEffect(kind, { ...entry, state: "refused", reason: result.reason });
266
+ return { ...result, attempted };
267
+ }
268
+ };
269
+ try {
270
+ if (!savedComment) {
271
+ await readReviewed();
272
+ const result = await submit("comment", "review", async beforeWrite => {
273
+ const result = await api.publishIntakeComment(repository, number, head, verdict.summary, signal, beforeWrite, target);
274
+ return result.status === "posted" ? { status: "confirmed", id: result.id } : result;
275
+ });
276
+ if (result.status !== "confirmed") return { status: result.status === "unknown" ? "unknown" : "held", message: result.reason };
277
+ }
278
+ if (d.mode === "review" || verdict.verdict === "blocked")
279
+ return { status: "commented", message: "GitHub review comment confirmed; no higher unattended action." };
280
+ if (verdict.verdict === "fix") {
281
+ if (state.fix || state.lineage.heads.length >= maxHeads)
282
+ return held("No further automatic fix is permitted; a fresh owner decision is required.");
283
+ const result = await submit("fix", "fix", async beforeWrite => {
284
+ const result = await api.applyIntakeFix(repository, number, head, verdict.proposal, signal, material => {
285
+ verifyMaterial(material);
286
+ beforeWrite();
287
+ }, r);
288
+ return result.status === "applied" ? { status: "confirmed", id: result.sha } : result;
289
+ });
290
+ return result.status === "confirmed" ? { status: "fixed", message: `GitHub confirmed fix ${result.id}; waiting for a new review.` }
291
+ : { status: result.status === "unknown" ? "unknown" : "held", message: result.reason };
292
+ }
293
+ if (d.mode !== "merge")
294
+ return { status: "commented", message: "GitHub review comment confirmed; merge requires explicit owner approval." };
295
+ if (state.merge?.state === "refused" && state.merge.head === head) return held(state.merge.reason);
296
+ check("merge");
297
+ // A declined inspection (including pending CI) does not claim a write.
298
+ const observedMerge = await api.inspectIntakeMerge(repository, number, head, signal, target);
299
+ if (observedMerge.status === "blocked") return waiting(observedMerge.reason);
300
+ if (observedMerge.status === "merged") {
301
+ saveEffect("merge", { ...entry, state: "confirmed", id: observedMerge.sha });
302
+ return { status: "merged", message: `GitHub confirmed merge ${observedMerge.sha}.` };
303
+ }
304
+ await readReviewed();
305
+ const result = await submit("merge", "merge", async beforeWrite => {
306
+ const result = await api.mergeIntakePull(repository, number, head, signal, beforeWrite, target);
307
+ return result.status === "merged" ? { status: "confirmed", id: result.sha } : result;
308
+ });
309
+ return result.status === "confirmed" ? { status: "merged", message: `GitHub confirmed merge ${result.id}.` }
310
+ : { status: result.status === "unknown" ? "unknown" : result.attempted ? "held" : "waiting", message: result.reason };
311
+ } catch (error) {
312
+ if (error instanceof IntakeMaterialError || error instanceof PrReadError || error instanceof ReviewedMaterialChanged)
313
+ return held(error.message);
314
+ throw error;
315
+ }
316
+ }