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.
Files changed (52) hide show
  1. package/DESIGN.md +21 -14
  2. package/README.ko.md +33 -15
  3. package/README.md +35 -14
  4. package/THIRD_PARTY_NOTICES.md +3 -3
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +232 -74
  7. package/docs/design/execution.md +54 -10
  8. package/docs/design/messaging.md +177 -43
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  13. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  17. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  19. package/package.json +8 -8
  20. package/scripts/ci.ts +3 -3
  21. package/scripts/test-omp.sh +2 -1
  22. package/src/cli.ts +3 -0
  23. package/src/config.ts +5 -0
  24. package/src/contracts.ts +26 -5
  25. package/src/cron-jobs.ts +443 -19
  26. package/src/cron-pr-intake.ts +257 -0
  27. package/src/discord-markdown.ts +350 -123
  28. package/src/extension.ts +9 -1
  29. package/src/head-quota.ts +80 -0
  30. package/src/head-recovery.ts +40 -1
  31. package/src/host-extension.ts +120 -4
  32. package/src/host-protocol.ts +11 -0
  33. package/src/host-sdk-helper.ts +105 -10
  34. package/src/host.ts +111 -29
  35. package/src/installed-omp.ts +116 -4
  36. package/src/managed-ulw.ts +137 -24
  37. package/src/messenger-command-catalog.json +1 -1
  38. package/src/native-presets.ts +32 -5
  39. package/src/omp-usage.ts +254 -36
  40. package/src/pr-github.ts +4 -2
  41. package/src/pr-intake-automation.ts +316 -0
  42. package/src/pr-intake-comment.ts +226 -0
  43. package/src/pr-intake-fix.ts +233 -0
  44. package/src/pr-intake-github.ts +480 -0
  45. package/src/pr-intake-material.ts +230 -0
  46. package/src/pr-intake-mode.ts +59 -0
  47. package/src/pr-intake-review.ts +397 -0
  48. package/src/pr-intake-tree.ts +69 -0
  49. package/src/pr-intake-work.ts +29 -0
  50. package/src/runtime.ts +1504 -192
  51. package/src/store.ts +249 -49
  52. package/src/topic-history.ts +30 -17
@@ -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
+ }