omp-superagent 0.1.7 → 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.
- package/DESIGN.md +21 -14
- package/README.ko.md +33 -15
- package/README.md +35 -14
- package/THIRD_PARTY_NOTICES.md +3 -3
- package/config.example.json +2 -1
- package/docs/OPERATIONS.md +232 -74
- package/docs/design/execution.md +54 -10
- package/docs/design/messaging.md +177 -43
- package/docs/discord-voice.md +8 -4
- package/docs/releases/0.1.8.md +21 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +8 -8
- package/scripts/ci.ts +3 -3
- package/scripts/test-omp.sh +2 -1
- package/src/cli.ts +3 -0
- package/src/config.ts +5 -0
- package/src/contracts.ts +26 -5
- package/src/cron-jobs.ts +443 -19
- package/src/cron-pr-intake.ts +257 -0
- package/src/discord-markdown.ts +350 -123
- package/src/extension.ts +9 -1
- package/src/head-quota.ts +80 -0
- package/src/head-recovery.ts +40 -1
- package/src/host-extension.ts +120 -4
- package/src/host-protocol.ts +11 -0
- package/src/host-sdk-helper.ts +105 -10
- package/src/host.ts +111 -29
- package/src/installed-omp.ts +116 -4
- package/src/managed-ulw.ts +137 -24
- package/src/messenger-command-catalog.json +1 -1
- package/src/native-presets.ts +32 -5
- package/src/omp-usage.ts +254 -36
- package/src/pr-github.ts +4 -2
- package/src/pr-intake-automation.ts +316 -0
- package/src/pr-intake-comment.ts +226 -0
- package/src/pr-intake-fix.ts +233 -0
- package/src/pr-intake-github.ts +480 -0
- package/src/pr-intake-material.ts +230 -0
- package/src/pr-intake-mode.ts +59 -0
- package/src/pr-intake-review.ts +397 -0
- package/src/pr-intake-tree.ts +69 -0
- package/src/pr-intake-work.ts +29 -0
- package/src/runtime.ts +1504 -192
- package/src/store.ts +249 -49
- package/src/topic-history.ts +30 -17
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Type, type Static, type TSchema } from "@sinclair/typebox/type";
|
|
3
|
+
import { parsePrRef } from "./pr-github";
|
|
4
|
+
import { loginSchema, parseWire, PrReadError } from "./pr-github-schema";
|
|
5
|
+
import { openIntakeGitHubSession, queryIntakeGitHub, type IntakeMergeIdentity } from "./pr-intake-github";
|
|
6
|
+
import { intakeEvidenceDeadlineMs } from "./pr-intake-material";
|
|
7
|
+
|
|
8
|
+
const id = Type.String({ pattern: "^[A-Za-z0-9_+/=-]{1,256}$" });
|
|
9
|
+
const sha = Type.String({ pattern: "^[0-9a-f]{40}$" });
|
|
10
|
+
const databaseId = Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER });
|
|
11
|
+
const user = Type.Object({ login: loginSchema.properties.login, databaseId });
|
|
12
|
+
const actor = Type.Object({ login: Type.String(), databaseId: Type.Optional(Type.Union([databaseId, Type.Null()])) });
|
|
13
|
+
const actorFields = "login ... on User { databaseId }";
|
|
14
|
+
const pull = Type.Object({
|
|
15
|
+
id, number: databaseId, state: Type.Union([Type.Literal("OPEN"), Type.Literal("CLOSED"), Type.Literal("MERGED")]), author: actor, headRefOid: sha,
|
|
16
|
+
baseRefOid: sha, baseRefName: Type.String(),
|
|
17
|
+
repository: Type.Object({
|
|
18
|
+
id, databaseId, nameWithOwner: Type.String(), owner: user,
|
|
19
|
+
isArchived: Type.Literal(false), isDisabled: Type.Literal(false),
|
|
20
|
+
}),
|
|
21
|
+
});
|
|
22
|
+
const pullFields = `
|
|
23
|
+
id number state author { ${actorFields} } headRefOid baseRefOid baseRefName
|
|
24
|
+
repository { id databaseId nameWithOwner owner { ${actorFields} } isArchived isDisabled }
|
|
25
|
+
`;
|
|
26
|
+
const review = Type.Object({
|
|
27
|
+
id, body: Type.String(), state: Type.String(), submittedAt: Type.Union([Type.String(), Type.Null()]),
|
|
28
|
+
commit: Type.Union([Type.Object({ oid: sha }), Type.Null()]),
|
|
29
|
+
author: Type.Union([actor, Type.Null()]),
|
|
30
|
+
});
|
|
31
|
+
const reviewFields = `id body state submittedAt commit { oid } author { ${actorFields} }`;
|
|
32
|
+
const graph = <T extends TSchema>(data: T) => Type.Object({
|
|
33
|
+
data, errors: Type.Optional(Type.Array(Type.Unknown(), { maxItems: 0 })),
|
|
34
|
+
});
|
|
35
|
+
const targetSchema = graph(Type.Object({ viewer: user, repository: Type.Object({ pullRequest: pull }) }));
|
|
36
|
+
const targetQuery = `query IntakeCommentTarget($owner: String!, $repo: String!, $number: Int!) {
|
|
37
|
+
viewer { login databaseId }
|
|
38
|
+
repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${pullFields} } }
|
|
39
|
+
}`;
|
|
40
|
+
const pageSchema = graph(Type.Object({
|
|
41
|
+
node: Type.Intersect([pull, Type.Object({
|
|
42
|
+
reviews: Type.Object({
|
|
43
|
+
totalCount: Type.Integer({ minimum: 0 }),
|
|
44
|
+
nodes: Type.Array(review, { maxItems: 30 }),
|
|
45
|
+
pageInfo: Type.Object({
|
|
46
|
+
hasNextPage: Type.Boolean(), endCursor: Type.Union([Type.String({ minLength: 1, maxLength: 4096 }), Type.Null()]),
|
|
47
|
+
}),
|
|
48
|
+
}),
|
|
49
|
+
})]),
|
|
50
|
+
}));
|
|
51
|
+
const pageQuery = `query IntakeCommentHistory($pullId: ID!, $cursor: String) {
|
|
52
|
+
node(id: $pullId) {
|
|
53
|
+
... on PullRequest {
|
|
54
|
+
${pullFields}
|
|
55
|
+
reviews(first: 30, after: $cursor) {
|
|
56
|
+
totalCount nodes { ${reviewFields} } pageInfo { hasNextPage endCursor }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}`;
|
|
61
|
+
const submitSchema = graph(Type.Object({ addPullRequestReview: Type.Object({
|
|
62
|
+
clientMutationId: Type.String(), pullRequestReview: Type.Object({ id }),
|
|
63
|
+
}) }));
|
|
64
|
+
const submitMutation = `mutation IntakeCommentSubmit($input: AddPullRequestReviewInput!) {
|
|
65
|
+
addPullRequestReview(input: $input) { clientMutationId pullRequestReview { id } }
|
|
66
|
+
}`;
|
|
67
|
+
const reviewSchema = graph(Type.Object({ node: Type.Intersect([review, Type.Object({ pullRequest: pull })]) }));
|
|
68
|
+
const reviewQuery = `query IntakeCommentReceipt($reviewId: ID!) {
|
|
69
|
+
node(id: $reviewId) {
|
|
70
|
+
... on PullRequestReview { ${reviewFields} pullRequest { ${pullFields} } }
|
|
71
|
+
}
|
|
72
|
+
}`;
|
|
73
|
+
|
|
74
|
+
type Request = IntakeMergeIdentity & { readonly number: number; readonly head: string; readonly summary: string };
|
|
75
|
+
type Target = {
|
|
76
|
+
readonly session: Awaited<ReturnType<typeof openIntakeGitHubSession>>;
|
|
77
|
+
readonly request: Request;
|
|
78
|
+
readonly pullId: string;
|
|
79
|
+
readonly repoId: string;
|
|
80
|
+
readonly digest: string;
|
|
81
|
+
readonly marker: string;
|
|
82
|
+
readonly body: string;
|
|
83
|
+
readonly historical: boolean;
|
|
84
|
+
};
|
|
85
|
+
export type IntakeCommentResult =
|
|
86
|
+
| { readonly status: "posted"; readonly id: string }
|
|
87
|
+
| { readonly status: "blocked" | "unknown"; readonly reason: string };
|
|
88
|
+
|
|
89
|
+
function matchesPull(row: Static<typeof pull>, session: Target["session"], request: Request, historical = false): boolean {
|
|
90
|
+
return row.number === request.number && (historical || row.state === "OPEN" && row.headRefOid === request.head
|
|
91
|
+
&& row.baseRefName === request.baseRef && row.baseRefOid === request.baseSha)
|
|
92
|
+
&& row.repository.databaseId === request.repositoryId && row.repository.nameWithOwner.toLowerCase() === session.repository
|
|
93
|
+
&& row.repository.owner.databaseId === request.ownerId && row.repository.owner.login.toLowerCase() === session.owner
|
|
94
|
+
&& row.author.databaseId !== request.ownerId && row.author.login.toLowerCase() !== session.owner;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function signedReview(row: Static<typeof review>, target: Target): boolean {
|
|
98
|
+
return row.author?.databaseId === target.request.ownerId && row.author.login.toLowerCase() === target.session.owner;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function confirmsReview(row: Static<typeof review>, target: Target): boolean {
|
|
102
|
+
return signedReview(row, target) && row.body === target.body && row.commit?.oid === target.request.head
|
|
103
|
+
&& row.state === "COMMENTED" && row.submittedAt !== null && Number.isFinite(Date.parse(row.submittedAt));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function prepare(repository: string, request: Request, signal: AbortSignal, historical = false): Promise<Target> {
|
|
107
|
+
const { owner, repo, number } = parsePrRef(`${repository}#${request.number}`);
|
|
108
|
+
parseWire(sha, JSON.stringify(request.head));
|
|
109
|
+
parseWire(sha, JSON.stringify(request.baseSha));
|
|
110
|
+
// Only the provided summary is rendered, never the surrounding verdict or replacement.
|
|
111
|
+
// One literal line cannot close the fenced block or introduce slash commands. Neutralize
|
|
112
|
+
// mentions even for consumers which inspect the review's raw Markdown.
|
|
113
|
+
const summary = request.summary.toWellFormed().replace(/[\s\p{Cc}\p{Cf}]+/gu, " ").trim().replaceAll("@", "@");
|
|
114
|
+
if (!summary) throw new PrReadError("reference");
|
|
115
|
+
const clipped = [...summary].slice(0, 400).join("");
|
|
116
|
+
const session = await openIntakeGitHubSession(repository, signal);
|
|
117
|
+
const { data } = await queryIntakeGitHub(session, signal, {
|
|
118
|
+
query: targetQuery, schema: targetSchema, variables: { owner, repo, number },
|
|
119
|
+
});
|
|
120
|
+
const row = data.repository.pullRequest;
|
|
121
|
+
if (data.viewer.login.toLowerCase() !== session.owner || data.viewer.databaseId !== request.ownerId
|
|
122
|
+
|| !matchesPull(row, session, request, historical)) throw new PrReadError("changed");
|
|
123
|
+
const digest = createHash("sha256").update(JSON.stringify([
|
|
124
|
+
"omp-superagent:intake-comment:v1", request.ownerId, request.repositoryId, row.id, number,
|
|
125
|
+
request.baseRef, request.baseSha, request.head, request.summary,
|
|
126
|
+
])).digest("hex");
|
|
127
|
+
const marker = `<!-- omp-superagent:intake-comment:v1:${digest} -->`;
|
|
128
|
+
const body = `Static review of commit ${request.head} (comment only)\n\n~~~text\nSummary: ${clipped}${clipped === summary ? "" : "…"}\n~~~\n\n${marker}`;
|
|
129
|
+
return { session, request, pullId: row.id, repoId: row.repository.id, digest, marker, body, historical };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function findReview(target: Target, signal: AbortSignal): Promise<IntakeCommentResult | null> {
|
|
133
|
+
const { session, request, pullId } = target;
|
|
134
|
+
const seen = new Set<string>();
|
|
135
|
+
const cursors = new Set<string>();
|
|
136
|
+
const matching: Static<typeof review>[] = [];
|
|
137
|
+
let cursor: string | null = null;
|
|
138
|
+
let total: number | undefined;
|
|
139
|
+
for (let i = 0; i < 10; i++) {
|
|
140
|
+
const response: Static<typeof pageSchema> = await queryIntakeGitHub(session, signal, {
|
|
141
|
+
query: pageQuery, schema: pageSchema, variables: { pullId, cursor },
|
|
142
|
+
});
|
|
143
|
+
const row: Static<typeof pageSchema>["data"]["node"] = response.data.node;
|
|
144
|
+
if (row.id !== pullId || row.repository.id !== target.repoId || !matchesPull(row, session, request, target.historical))
|
|
145
|
+
throw new PrReadError("changed");
|
|
146
|
+
const { nodes, pageInfo, totalCount }: typeof row.reviews = row.reviews;
|
|
147
|
+
total ??= totalCount;
|
|
148
|
+
if (total !== totalCount || total > 300) throw new PrReadError("response");
|
|
149
|
+
for (const item of nodes) {
|
|
150
|
+
if (seen.has(item.id)) throw new PrReadError("response");
|
|
151
|
+
seen.add(item.id);
|
|
152
|
+
if (signedReview(item, target) && item.body.split(/\r?\n/).includes(target.marker)) matching.push(item);
|
|
153
|
+
}
|
|
154
|
+
if (!pageInfo.hasNextPage) {
|
|
155
|
+
if (seen.size !== total) throw new PrReadError("response");
|
|
156
|
+
if (matching.length === 0) return null;
|
|
157
|
+
const [item] = matching;
|
|
158
|
+
return matching.length === 1 && confirmsReview(item, target)
|
|
159
|
+
? { status: "posted", id: item.id }
|
|
160
|
+
: { status: "unknown", reason: "GitHub has a matching review marker but not one exact verified comment. Do not resubmit." };
|
|
161
|
+
}
|
|
162
|
+
cursor = pageInfo.endCursor;
|
|
163
|
+
if (!cursor || cursors.has(cursor) || nodes.length === 0 || seen.size >= total) throw new PrReadError("response");
|
|
164
|
+
cursors.add(cursor);
|
|
165
|
+
}
|
|
166
|
+
throw new PrReadError("response");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Read-only reconciliation; absence is not proof that a fenced request never reached GitHub. */
|
|
170
|
+
export async function inspectIntakeComment(
|
|
171
|
+
repository: string, number: number, head: string, summary: string, signal: AbortSignal, identity: IntakeMergeIdentity,
|
|
172
|
+
): Promise<IntakeCommentResult> {
|
|
173
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(intakeEvidenceDeadlineMs)]);
|
|
174
|
+
try {
|
|
175
|
+
// A later push/retarget/close does not erase a historical commit-pinned COMMENT.
|
|
176
|
+
// This mode only reads; it never claims the newer head has been reviewed.
|
|
177
|
+
const target = await prepare(repository, { ...identity, number, head, summary }, deadline, true);
|
|
178
|
+
const receipt = await findReview(target, deadline);
|
|
179
|
+
if (receipt) return receipt;
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (!(error instanceof PrReadError)) throw error;
|
|
182
|
+
}
|
|
183
|
+
return { status: "unknown", reason: "GitHub does not establish the exact submitted review comment. Do not resubmit." };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** The caller must persist the no-replay fence before sending an otherwise non-idempotent mutation. */
|
|
187
|
+
export async function publishIntakeComment(
|
|
188
|
+
repository: string, number: number, head: string, summary: string, signal: AbortSignal,
|
|
189
|
+
beforeWrite: () => void, identity: IntakeMergeIdentity,
|
|
190
|
+
): Promise<IntakeCommentResult> {
|
|
191
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(intakeEvidenceDeadlineMs)]);
|
|
192
|
+
let target: Target;
|
|
193
|
+
try {
|
|
194
|
+
target = await prepare(repository, { ...identity, number, head, summary }, deadline);
|
|
195
|
+
const existing = await findReview(target, deadline);
|
|
196
|
+
if (existing) return existing;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (!(error instanceof PrReadError)) throw error;
|
|
199
|
+
return { status: "blocked", reason: "GitHub ownership, reviewed base/head or complete comment preflight could not be established." };
|
|
200
|
+
}
|
|
201
|
+
if (deadline.aborted) return { status: "blocked", reason: "The review comment was cancelled before writing." };
|
|
202
|
+
const { session, digest, pullId, body } = target;
|
|
203
|
+
beforeWrite();
|
|
204
|
+
try {
|
|
205
|
+
// GitHub pins the comment's commit, not the live PR base or head. It never casts an approval.
|
|
206
|
+
const { data } = await queryIntakeGitHub(session, deadline, {
|
|
207
|
+
query: submitMutation, schema: submitSchema, variables: {
|
|
208
|
+
input: { pullRequestId: pullId, commitOID: head, clientMutationId: digest, event: "COMMENT", body },
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
const receipt = data.addPullRequestReview;
|
|
212
|
+
if (receipt.clientMutationId === digest) {
|
|
213
|
+
const reviewId = receipt.pullRequestReview.id;
|
|
214
|
+
const observed = await queryIntakeGitHub(session, deadline, {
|
|
215
|
+
query: reviewQuery, schema: reviewSchema, variables: { reviewId },
|
|
216
|
+
});
|
|
217
|
+
const row = observed.data.node;
|
|
218
|
+
if (row.id === reviewId && row.pullRequest.id === pullId && row.pullRequest.repository.id === target.repoId
|
|
219
|
+
&& matchesPull(row.pullRequest, session, target.request) && confirmsReview(row, target))
|
|
220
|
+
return { status: "posted", id: row.id };
|
|
221
|
+
}
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (!(error instanceof PrReadError)) throw error;
|
|
224
|
+
}
|
|
225
|
+
return { status: "unknown", reason: "GitHub review comment outcome is unconfirmed; reconcile without resubmitting." };
|
|
226
|
+
}
|