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
@@ -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
+ }
@@ -0,0 +1,233 @@
1
+ import { createHash } from "node:crypto";
2
+ import { Type, type Static } from "@sinclair/typebox/type";
3
+ import { parseWire, PrReadError } from "./pr-github-schema";
4
+ import { openIntakeGitHubSession, queryIntakeGitHub, type IntakeRepositoryIdentity } from "./pr-intake-github";
5
+ import {
6
+ intakeEvidenceDeadlineMs, IntakeMaterialError, readIntakeDiff, readIntakePullIdentity, serializeIntakeDiff,
7
+ type IntakeMaterialTarget,
8
+ } from "./pr-intake-material";
9
+ import { openIntakeTree, readIntakeBlob } from "./pr-intake-tree";
10
+
11
+ const maxSnippet = 8 * 1024;
12
+ const maxSource = 96 * 1024;
13
+ const oid = Type.String({ pattern: "^[0-9a-f]{40}$" });
14
+ const id = Type.String({ minLength: 1, maxLength: 256, pattern: "^[A-Za-z0-9_+=/-]+$" });
15
+ const fix = Type.Object({
16
+ path: Type.String({ minLength: 1, maxLength: 256 }),
17
+ old: Type.String({ minLength: 1, maxLength: maxSnippet }),
18
+ replacement: Type.String({ maxLength: maxSnippet }),
19
+ });
20
+ const verdict = Type.Object({
21
+ ...fix.properties, verdict: Type.Literal("fix"), summary: Type.String({ minLength: 1, maxLength: 2048 }),
22
+ }, { additionalProperties: false });
23
+ const branchSchema = Type.Object({ name: Type.String(), protected: Type.Boolean(), commit: Type.Object({ sha: oid }) });
24
+ const branchRead = Type.Object({ data: Type.Object({
25
+ viewer: Type.Object({ login: Type.String(), databaseId: Type.Integer() }),
26
+ repository: Type.Object({
27
+ id, databaseId: Type.Integer(), isArchived: Type.Literal(false), isDisabled: Type.Literal(false),
28
+ nameWithOwner: Type.String(), defaultBranchRef: Type.Object({ name: Type.String() }),
29
+ ref: Type.Object({ id, name: Type.String(), target: Type.Object({ oid }) }),
30
+ pullRequest: Type.Object({
31
+ state: Type.Literal("OPEN"), isDraft: Type.Literal(false), baseRefName: Type.String(), baseRefOid: oid,
32
+ headRefName: Type.String(), headRefOid: oid, headRepository: Type.Object({ id }),
33
+ }),
34
+ }),
35
+ }), errors: Type.Optional(Type.Array(Type.Unknown(), { maxItems: 0 })) });
36
+ const branchQuery = `query IntakeFixBranch($owner: String!, $repo: String!, $ref: String!, $number: Int!) {
37
+ viewer { login databaseId }
38
+ repository(owner: $owner, name: $repo) {
39
+ id databaseId isArchived isDisabled nameWithOwner defaultBranchRef { name }
40
+ ref(qualifiedName: $ref) { id name target { oid } }
41
+ pullRequest(number: $number) {
42
+ state isDraft baseRefName baseRefOid headRefName headRefOid headRepository { id }
43
+ }
44
+ }
45
+ }`;
46
+ const mutation = `mutation IntakeFixCommit($input: CreateCommitOnBranchInput!) {
47
+ createCommitOnBranch(input: $input) {
48
+ clientMutationId ref { id } commit { oid parents(first: 2) { totalCount nodes { oid } } }
49
+ }
50
+ }`;
51
+ const receipt = Type.Object({ data: Type.Object({
52
+ createCommitOnBranch: Type.Object({
53
+ clientMutationId: Type.String(), ref: Type.Object({ id }),
54
+ commit: Type.Object({ oid, parents: Type.Object({
55
+ totalCount: Type.Literal(1), nodes: Type.Tuple([Type.Object({ oid })]),
56
+ }) }),
57
+ }),
58
+ }), errors: Type.Optional(Type.Array(Type.Unknown(), { maxItems: 0 })) });
59
+ const commitSchema = Type.Object({
60
+ sha: oid, parents: Type.Tuple([Type.Object({ sha: oid })]),
61
+ commit: Type.Object({ message: Type.String() }),
62
+ files: Type.Tuple([Type.Object({ filename: Type.String(), status: Type.Literal("modified"), sha: oid })]),
63
+ });
64
+
65
+ type Target = IntakeMaterialTarget;
66
+ type Session = Awaited<ReturnType<typeof openIntakeGitHubSession>>;
67
+ export type IntakeFixProposal = Readonly<Static<typeof fix>>;
68
+ export type IntakeFixResult =
69
+ | { readonly status: "applied"; readonly sha: string }
70
+ | { readonly status: "blocked" | "unknown"; readonly reason: string };
71
+
72
+ function safePath(path: string): boolean {
73
+ return /^(?:src|lib|test|tests)\/(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\/)*[A-Za-z0-9_-][A-Za-z0-9_.-]*\.(?:[cm]?[jt]sx?|py|go|rs|java|cs|c|cc|cpp|h|hpp|rb|php|swift|kt)$/.test(path)
74
+ && !/(?:^|[./_-])(?:config|configs|settings|metadata|ci|workflows?|scripts?|build|setup|conftest)(?=$|[./_-])/i.test(path);
75
+ }
76
+
77
+ function safeSnippet(value: string): boolean {
78
+ return Buffer.byteLength(value) <= maxSnippet && value.isWellFormed()
79
+ && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\p{Cf}]|\r(?!\n)/u.test(value);
80
+ }
81
+
82
+ function safeProposal({ path, old, replacement }: IntakeFixProposal): boolean {
83
+ return path.length <= 256 && safePath(path) && old.length > 0 && old !== replacement
84
+ && safeSnippet(old) && safeSnippet(replacement);
85
+ }
86
+
87
+ export function parseIntakeFix(text: string): IntakeFixProposal | null {
88
+ if (Buffer.byteLength(text) > 64 * 1024) return null;
89
+ try {
90
+ const { path, old, replacement, summary } = parseWire(verdict, text);
91
+ // JSON.parse alone silently accepts an object that states two different verdicts.
92
+ const keys = [...text.matchAll(/"(?:[^"\\]|\\[\s\S])*"/g)]
93
+ .filter(token => /^\s*:/.test(text.slice(token.index + token[0].length)));
94
+ if (keys.length !== Object.keys(verdict.properties).length) return null;
95
+ const proposal = { path, old, replacement };
96
+ return summary.trim() && safeProposal(proposal) ? proposal : null;
97
+ } catch (error) {
98
+ if (error instanceof PrReadError) return null;
99
+ throw error;
100
+ }
101
+ }
102
+
103
+ export function intakeFixDigest(repository: string, number: number, head: string, proposal: IntakeFixProposal): string {
104
+ return createHash("sha256").update(JSON.stringify([
105
+ "omp-superagent:intake-fix:v1", repository.toLowerCase(), number, head, proposal.path, proposal.old, proposal.replacement,
106
+ ])).digest("hex");
107
+ }
108
+
109
+ type Pull = Awaited<ReturnType<typeof readIntakePullIdentity>>;
110
+ function sameRepoHead(session: Session, target: Target, head: Pull["head"]): boolean {
111
+ return head.repo.id === target.identity.repositoryId && head.repo.owner.id === target.identity.ownerId
112
+ && head.repo.full_name.toLowerCase() === session.repository && head.repo.owner.login.toLowerCase() === session.owner;
113
+ }
114
+
115
+ async function prepareContents(session: Session, head: string, proposal: IntakeFixProposal, expectedBlob?: string) {
116
+ const tree = await openIntakeTree(session, head);
117
+ const file = await tree(proposal.path);
118
+ if (file?.mode !== "100644" || (expectedBlob !== undefined && file.sha !== expectedBlob))
119
+ throw new IntakeMaterialError("Fix requires the exact reviewed, non-executable regular source file.");
120
+ const original = await readIntakeBlob(session, file.sha, maxSource);
121
+ const offset = original.indexOf(proposal.old);
122
+ if (offset < 0 || offset !== original.lastIndexOf(proposal.old))
123
+ throw new IntakeMaterialError("The old fix snippet must match the pinned file exactly once.");
124
+ const contents = original.slice(0, offset) + proposal.replacement + original.slice(offset + proposal.old.length);
125
+ if (Buffer.byteLength(contents) > maxSource) throw new IntakeMaterialError("The resulting source file is too large.");
126
+ return contents;
127
+ }
128
+
129
+ async function prepareWrite(session: Session, target: Target, proposal: IntakeFixProposal, signal: AbortSignal) {
130
+ const snapshot = await readIntakeDiff(session, target);
131
+ const material = serializeIntakeDiff(snapshot);
132
+ const { head, base, draft } = snapshot.pull;
133
+ if (draft || head.name !== session.repository || head.repositoryId !== target.identity.repositoryId
134
+ || head.owner !== session.owner || head.ownerId !== target.identity.ownerId)
135
+ throw new IntakeMaterialError("Fixes require an open non-draft PR with a same-repository head branch.");
136
+ if (head.ref === base.ref || !/^[A-Za-z0-9][A-Za-z0-9/_.-]{0,149}$/.test(head.ref))
137
+ throw new IntakeMaterialError("Fixes cannot write the PR base or an unsupported branch name.");
138
+ const file = snapshot.files.find(row => row.filename === proposal.path);
139
+ if (!file || (file.status !== "modified" && file.status !== "added") || file.afterMode !== "100644")
140
+ throw new IntakeMaterialError("Fixes may only replace text in one reviewed added or modified source file.");
141
+ const contents = await prepareContents(session, target.head, proposal, file.sha);
142
+ const encoded = encodeURIComponent(head.ref);
143
+ const [rules] = await session.get(`${session.root}/rules/branches/${encoded}`, Type.Tuple([Type.Array(Type.Unknown())]));
144
+ const [branch] = await session.get(`${session.root}/branches/${encoded}`, Type.Tuple([branchSchema]));
145
+ if (rules.length || branch.protected || branch.name !== head.ref || branch.commit.sha !== target.head)
146
+ throw new IntakeMaterialError("GitHub does not establish an unprotected branch at the approved head.");
147
+ const { data } = await queryIntakeGitHub(session, signal, { query: branchQuery, schema: branchRead, variables: {
148
+ owner: session.owner, repo: session.repository.slice(session.owner.length + 1),
149
+ ref: `refs/heads/${head.ref}`, number: target.number,
150
+ } });
151
+ const { repository, viewer } = data;
152
+ const pr = repository.pullRequest;
153
+ if (viewer.databaseId !== target.identity.ownerId || viewer.login.toLowerCase() !== session.owner
154
+ || repository.databaseId !== target.identity.repositoryId || repository.nameWithOwner.toLowerCase() !== session.repository
155
+ || repository.defaultBranchRef.name === head.ref || repository.ref.name !== head.ref || repository.ref.target.oid !== target.head
156
+ || pr.baseRefName !== base.ref || pr.baseRefOid !== base.sha || pr.headRefName !== head.ref
157
+ || pr.headRefOid !== target.head || pr.headRepository.id !== repository.id)
158
+ throw new IntakeMaterialError("GitHub repository, owner, PR, or write-eligible branch changed during fix preflight.");
159
+ return { branchId: repository.ref.id, material, contents };
160
+ }
161
+
162
+ export async function applyIntakeFix(
163
+ repository: string, number: number, head: string, proposal: IntakeFixProposal, signal: AbortSignal,
164
+ beforeWrite: (material: string) => void, identity: IntakeRepositoryIdentity,
165
+ ): Promise<IntakeFixResult> {
166
+ if (!safeProposal(proposal)) return { status: "blocked", reason: "The exact fix proposal is not a safe source replacement." };
167
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(intakeEvidenceDeadlineMs)]);
168
+ let session: Session, prepared: Awaited<ReturnType<typeof prepareWrite>>;
169
+ try {
170
+ session = await openIntakeGitHubSession(repository, deadline);
171
+ prepared = await prepareWrite(session, { number, head, identity }, proposal, deadline);
172
+ } catch (error) {
173
+ if (error instanceof IntakeMaterialError) return { status: "blocked", reason: error.message };
174
+ if (error instanceof PrReadError) return { status: "blocked", reason: "GitHub fix preflight evidence could not be established." };
175
+ throw error;
176
+ }
177
+ const digest = intakeFixDigest(session.repository, number, head, proposal);
178
+ const input = {
179
+ branch: { id: prepared.branchId }, expectedHeadOid: head, clientMutationId: digest,
180
+ message: { headline: `Superagent intake fix ${digest}` },
181
+ fileChanges: { additions: [{ path: proposal.path, contents: Buffer.from(prepared.contents).toString("base64") }] },
182
+ };
183
+ if (deadline.aborted) return { status: "blocked", reason: "The fix was cancelled before writing." };
184
+ beforeWrite(prepared.material);
185
+ try {
186
+ const { data } = await queryIntakeGitHub(session, signal, { query: mutation, schema: receipt, variables: { input } });
187
+ const result = data.createCommitOnBranch;
188
+ if (result.clientMutationId === digest && result.ref.id === prepared.branchId
189
+ && result.commit.oid !== head && result.commit.parents.nodes[0].oid === head)
190
+ return { status: "applied", sha: result.commit.oid };
191
+ } catch (error) {
192
+ if (!(error instanceof PrReadError)) throw error;
193
+ }
194
+ return { status: "unknown", reason: "GitHub did not confirm the conditional write. Reconcile without resubmitting." };
195
+ }
196
+
197
+ export async function reconcileIntakeFix(
198
+ repository: string, number: number, head: string, proposal: IntakeFixProposal, signal: AbortSignal,
199
+ expectedBranch: string, identity: IntakeRepositoryIdentity,
200
+ ): Promise<IntakeFixResult> {
201
+ const unknown = { status: "unknown", reason: "GitHub does not establish the exact approved fix at the current PR head. Do not resubmit." } as const;
202
+ if (!safeProposal(proposal) || !expectedBranch) return unknown;
203
+ try {
204
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(intakeEvidenceDeadlineMs)]);
205
+ const session = await openIntakeGitHubSession(repository, deadline);
206
+ const target = { number, head, identity };
207
+ const current = await readIntakePullIdentity(session, target);
208
+ if (!sameRepoHead(session, target, current.head) || current.head.ref !== expectedBranch || current.head.sha === head
209
+ || current.base.ref === expectedBranch)
210
+ return unknown;
211
+ const observed = current.head.sha;
212
+ const [candidate] = await session.get(`${session.root}/commits/${observed}?per_page=100`, Type.Tuple([commitSchema]));
213
+ const digest = intakeFixDigest(session.repository, number, head, proposal);
214
+ if (candidate.sha !== observed || candidate.parents[0].sha !== head || candidate.files[0].filename !== proposal.path
215
+ || candidate.commit.message.replace(/\n+$/, "") !== `Superagent intake fix ${digest}`) return unknown;
216
+ const tree = await openIntakeTree(session, observed);
217
+ const file = await tree(proposal.path);
218
+ if (file?.mode !== "100644" || file.sha !== candidate.files[0].sha
219
+ || await readIntakeBlob(session, file.sha, maxSource) !== await prepareContents(session, head, proposal))
220
+ return unknown;
221
+ const [branch] = await session.get(`${session.root}/branches/${encodeURIComponent(expectedBranch)}`, Type.Tuple([branchSchema]));
222
+ const confirmed = await readIntakePullIdentity(session, target);
223
+ // This proves the observed effect, not who caused it or whether our response was lost.
224
+ if (branch.name === expectedBranch && branch.commit.sha === observed && confirmed.head.sha === observed
225
+ && confirmed.head.ref === expectedBranch && confirmed.base.ref === current.base.ref
226
+ && confirmed.base.sha === current.base.sha
227
+ && confirmed.user.id === current.user.id && sameRepoHead(session, target, confirmed.head))
228
+ return { status: "applied", sha: observed };
229
+ } catch (error) {
230
+ if (!(error instanceof PrReadError) && !(error instanceof IntakeMaterialError)) throw error;
231
+ }
232
+ return unknown;
233
+ }