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,397 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { physicalRoute, routeKey, type Inbound, type InputRecord, type Lane, type Route, type StorePort } from "./contracts";
|
|
3
|
+
import { compareMessageIds } from "./message-order";
|
|
4
|
+
import type { CronJobs } from "./cron-jobs";
|
|
5
|
+
import type { CronPrCandidate, CronPrIntake } from "./cron-pr-intake";
|
|
6
|
+
import type { CronPrJob } from "./cron-jobs";
|
|
7
|
+
import { hasIntakeReplyRoute, intakeThreadKey, intakeStatusKey, intakeWorkId, intakeWorkPrefix } from "./pr-intake-work";
|
|
8
|
+
import { inspectIntakeMerge, mergeIntakePull } from "./pr-intake-github";
|
|
9
|
+
import { applyIntakeFix, intakeFixDigest, parseIntakeFix, reconcileIntakeFix } from "./pr-intake-fix";
|
|
10
|
+
import { readIntakeMaterial, readIntakeMaterialTarget } from "./pr-intake-material";
|
|
11
|
+
import { inspectIntakeComment, publishIntakeComment } from "./pr-intake-comment";
|
|
12
|
+
import { advancePrIntakeAutomation, prIntakeManualHold, readPrIntakeAutomation } from "./pr-intake-automation";
|
|
13
|
+
import type { PrIntakeMode } from "./pr-intake-mode";
|
|
14
|
+
|
|
15
|
+
export class PrControlError extends Error {}
|
|
16
|
+
export const prAction = /^(?:pr-review|pr-merge|pr-fix|pr-status)(?:\s|$)/;
|
|
17
|
+
type Action = "pr-review" | "pr-merge" | "pr-fix" | "pr-status";
|
|
18
|
+
export interface ReviewRound {
|
|
19
|
+
readonly job: string;
|
|
20
|
+
readonly repository: string;
|
|
21
|
+
readonly repositoryId: number;
|
|
22
|
+
readonly ownerId: number;
|
|
23
|
+
readonly number: number;
|
|
24
|
+
readonly laneId: string;
|
|
25
|
+
readonly opener: string;
|
|
26
|
+
readonly source: string;
|
|
27
|
+
readonly inputId: string;
|
|
28
|
+
readonly head: string;
|
|
29
|
+
readonly epoch: string;
|
|
30
|
+
readonly automation?: { readonly revision: string; readonly anchor: string };
|
|
31
|
+
}
|
|
32
|
+
interface Effect {
|
|
33
|
+
readonly action: "pr-fix" | "pr-merge";
|
|
34
|
+
readonly source: string;
|
|
35
|
+
readonly state: "unknown" | "confirmed";
|
|
36
|
+
readonly sha?: string;
|
|
37
|
+
}
|
|
38
|
+
export const prReviewApis = { readIntakeMaterial, applyIntakeFix, reconcileIntakeFix, inspectIntakeMerge, mergeIntakePull,
|
|
39
|
+
inspectIntakeComment, publishIntakeComment };
|
|
40
|
+
const digest = (s: string) => createHash("sha256").update(s).digest("hex");
|
|
41
|
+
const scopeKey = (job: string, number: number) => `pr-review:${job}:${number}`;
|
|
42
|
+
const pointer = (laneId: string) => `pr-review-lane:${laneId}`;
|
|
43
|
+
export function isPrReviewLane(store: StorePort, laneId: string): boolean {
|
|
44
|
+
return store.getMeta(pointer(laneId)) !== null;
|
|
45
|
+
}
|
|
46
|
+
const materialKey = (round: ReviewRound) => `pr-review-material:${round.inputId}`;
|
|
47
|
+
const effectKey = (round: ReviewRound) => `pr-review-effect:${round.inputId}`;
|
|
48
|
+
const args = /^(pr-review|pr-status|pr-merge|pr-fix) ([\da-f-]{36}) ([1-9]\d*)(?: ([a-f0-9]{40}|[a-f0-9]{64}))?(?: ([a-f0-9]{64}))?$/;
|
|
49
|
+
|
|
50
|
+
function approved(text: string): boolean {
|
|
51
|
+
try {
|
|
52
|
+
const result: unknown = JSON.parse(text);
|
|
53
|
+
return typeof result === "object" && result !== null && Object.keys(result).length === 2
|
|
54
|
+
&& [...text.matchAll(/"(?:[^"\\]|\\[\s\S])*"/g)].filter(token => /^\s*:/.test(text.slice(token.index + token[0].length))).length === 2
|
|
55
|
+
&& "verdict" in result && result.verdict === "approve" && "summary" in result
|
|
56
|
+
&& typeof result.summary === "string" && result.summary.trim().length > 0;
|
|
57
|
+
} catch { return false; }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export class PrReviews {
|
|
61
|
+
constructor(private readonly store: StorePort, private readonly cron: CronJobs,
|
|
62
|
+
private readonly intake: CronPrIntake, private readonly api: typeof prReviewApis) {}
|
|
63
|
+
|
|
64
|
+
saved(job: string, number: number): ReviewRound | null {
|
|
65
|
+
const value = this.store.getMeta(scopeKey(job, number));
|
|
66
|
+
return value === null ? null : JSON.parse(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
needsReconciliation(scope: Pick<ReviewRound, "repositoryId" | "number">): boolean {
|
|
70
|
+
const state = readPrIntakeAutomation(this.store, scope);
|
|
71
|
+
return !!state && [...state.comments, state.fix, state.merge].some(entry => entry?.state === "unknown" || entry?.state === "pending");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
laneRound(laneId: string): ReviewRound | null {
|
|
75
|
+
const claim = this.store.getMeta(pointer(laneId));
|
|
76
|
+
if (claim === null) return null;
|
|
77
|
+
const value = this.store.getMeta(claim);
|
|
78
|
+
if (!value) throw new PrControlError("PR 레인 등록이 손상되어 실행을 보류했습니다.");
|
|
79
|
+
const round: ReviewRound = JSON.parse(value);
|
|
80
|
+
if (round.laneId !== laneId) throw new PrControlError("PR 레인 식별자가 일치하지 않습니다.");
|
|
81
|
+
return round;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private effect(r: ReviewRound): Effect | null {
|
|
85
|
+
return JSON.parse(this.store.getMeta(effectKey(r)) ?? "null");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
assertActive(r: ReviewRound): void {
|
|
89
|
+
const source = this.store.input(r.source);
|
|
90
|
+
if (!source || this.store.getMeta(scopeKey(r.job, r.number)) !== JSON.stringify(r))
|
|
91
|
+
throw new PrControlError("PR 검토 등록이 중단되거나 변경되었습니다. 새 소유자 검토 명령이 필요합니다.");
|
|
92
|
+
const parent = { ...physicalRoute(source.route), threadId: null };
|
|
93
|
+
if (r.automation) {
|
|
94
|
+
const active = this.cron.activePrEnrollment(r.job);
|
|
95
|
+
const candidate = active && this.intake.candidate(active.job, r.number);
|
|
96
|
+
const offer = candidate && this.store.output(candidate.outputId);
|
|
97
|
+
if (!active || active.job.epoch !== r.epoch || active.job.repository !== r.repository
|
|
98
|
+
|| this.cron.prPolicy(r.job)?.revision !== r.automation.revision
|
|
99
|
+
|| !candidate || candidate.repositoryId !== r.repositoryId || candidate.ownerId !== r.ownerId
|
|
100
|
+
|| candidate.policyRevision !== r.automation.revision || candidate.epoch !== r.epoch
|
|
101
|
+
|| !offer || offer.state !== "sent" || offer.remoteId !== r.automation.anchor || !this.intake.canDeliver(offer)
|
|
102
|
+
|| routeKey(parent) !== routeKey(active.source.route) || source.route.threadId !== offer.remoteId
|
|
103
|
+
|| (source.state !== "pending" && source.state !== "done")
|
|
104
|
+
|| !source.id.startsWith(intakeWorkPrefix) || source.messageId !== null || source.interactionId !== undefined
|
|
105
|
+
|| this.store.getMeta(`user-source:${source.id}`) !== null)
|
|
106
|
+
throw new PrControlError("등록한 자동 단계 또는 원래 PR·스레드 영수증을 확인하지 못했습니다.");
|
|
107
|
+
} else if (this.cron.requireActivePrJob(source, r.job, parent).epoch !== r.epoch)
|
|
108
|
+
throw new PrControlError("원래 PR 등록이 변경되었습니다.");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private placed(r: ReviewRound): Lane {
|
|
112
|
+
if (r.opener.startsWith(intakeWorkPrefix)) {
|
|
113
|
+
const lane = this.store.lane(r.laneId);
|
|
114
|
+
const opening = this.store.input(`handoff:${r.opener}:lane`);
|
|
115
|
+
const kickoff = this.store.output(`${r.opener}:kickoff`);
|
|
116
|
+
const original = this.store.input(r.opener);
|
|
117
|
+
const anchor = this.store.getMeta(intakeThreadKey(r.job, r.number));
|
|
118
|
+
if (lane && original && opening?.target === lane.id && !lane.remote && anchor === lane.route.threadId
|
|
119
|
+
&& this.store.getMeta(`handoff-source:${opening.id}`) === original.id
|
|
120
|
+
&& routeKey(original.route) === routeKey(lane.route) && routeKey(opening.route) === routeKey(lane.route)
|
|
121
|
+
&& kickoff?.sourceId === opening.id && kickoff.state === "sent" && kickoff.remoteId
|
|
122
|
+
&& routeKey(kickoff.route) === routeKey(lane.route)) return lane;
|
|
123
|
+
throw new PrControlError("PR 자동 검토 스레드·레인 또는 시작 메시지 전송을 확인할 수 없습니다.");
|
|
124
|
+
}
|
|
125
|
+
const lane = this.store.headLanePlacement(r.opener);
|
|
126
|
+
if (!lane || lane === "unverified" || lane.id !== r.laneId || !lane.route.threadId || lane.remote)
|
|
127
|
+
throw new PrControlError("스레드 생성·레인 배정·시작 메시지 중 확인되지 않은 단계가 있습니다. 원래 명령과 Discord 전송 기록을 대조하세요. 스레드를 다시 만들지 않습니다.");
|
|
128
|
+
return lane;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async material(r: ReviewRound, signal: AbortSignal): Promise<string> {
|
|
132
|
+
this.assertActive(r);
|
|
133
|
+
const material = await this.api.readIntakeMaterial(r.repository, r.number, r.head, signal, r);
|
|
134
|
+
this.assertActive(r);
|
|
135
|
+
this.store.setMeta(materialKey(r), JSON.stringify({ digest: digest(material), ...readIntakeMaterialTarget(material) }));
|
|
136
|
+
return material;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
answer(r: ReviewRound): string | null {
|
|
140
|
+
const input = this.store.input(r.inputId);
|
|
141
|
+
const lane = this.placed(r);
|
|
142
|
+
const answer = this.store.output(`${r.inputId}:answer`);
|
|
143
|
+
const delivery = r.automation && input && hasIntakeReplyRoute(this.store, input, r.source)
|
|
144
|
+
? { source: { id: r.source }, outputSourceId: input.id } : this.store.topicDelivery(r.inputId);
|
|
145
|
+
return input?.state === "done" && input.target === lane.id && input.requestId && input.generation !== null
|
|
146
|
+
&& this.store.getMeta(materialKey(r)) && delivery?.source.id === r.source && answer?.state === "sent"
|
|
147
|
+
&& answer.remoteId && delivery.outputSourceId === answer.sourceId && routeKey(answer.route) === routeKey(lane.route)
|
|
148
|
+
? answer.text : null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async advance(r: ReviewRound, observedHead: string | null, policy: NonNullable<ReturnType<CronJobs["prPolicy"]>>,
|
|
152
|
+
signal: AbortSignal, verifyRound: () => void): Promise<{ text: string; nextHead: string | null }> {
|
|
153
|
+
const manual = this.effect(r);
|
|
154
|
+
if (manual) return { text: `별도의 소유자 명령 ${manual.action}: ${manual.state}. /cron pr-status ${r.job} ${r.number}`, nextHead: null };
|
|
155
|
+
const input = this.store.input(r.inputId);
|
|
156
|
+
if (!input || input.state === "pending" || input.state === "submitted" || input.state === "uncertain")
|
|
157
|
+
return { text: `PR #${r.number} ${r.head}: 검토 ${input?.state ?? "미확인"}.`, nextHead: null };
|
|
158
|
+
if (input.state === "cancelled" && observedHead === r.head) {
|
|
159
|
+
const why = this.store.output(`${r.inputId}:held`)?.text ?? "검토가 취소되어 이 SHA에는 완료된 결과가 없습니다.";
|
|
160
|
+
return { text: `${why} 원인을 해결한 뒤 이 스레드에서 /cron pr-review ${r.job} ${r.number} ${r.head}`, nextHead: null };
|
|
161
|
+
}
|
|
162
|
+
const answer = this.answer(r);
|
|
163
|
+
const material = this.store.getMeta(materialKey(r));
|
|
164
|
+
if (input.state === "done" && !answer)
|
|
165
|
+
return { text: "원래 검토 답변의 Discord 전달이 확인되지 않아 새 검토·쓰기를 보류했습니다.", nextHead: null };
|
|
166
|
+
const rank = { review: 1, fix: 2, merge: 3 } as const;
|
|
167
|
+
const verify = (stage: PrIntakeMode) => {
|
|
168
|
+
verifyRound();
|
|
169
|
+
if (rank[stage] > rank[policy.mode] || r.automation?.revision !== policy.revision || this.effect(r)
|
|
170
|
+
|| this.answer(r) !== answer || this.store.getMeta(materialKey(r)) !== material)
|
|
171
|
+
throw new PrControlError("자동 단계 또는 전달된 검토 결과가 변경되었습니다.");
|
|
172
|
+
};
|
|
173
|
+
const result = await advancePrIntakeAutomation(r, { store: this.store, mode: policy.mode, observedHead, signal, verify,
|
|
174
|
+
evidence: answer && material ? { answer, material: JSON.parse(material) } : null, api: this.api });
|
|
175
|
+
return { text: result.message, nextHead: result.nextHead ?? null };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
startAutomated(job: CronPrJob, candidate: CronPrCandidate, head: string, route: Route, laneId: string, revision: string): ReviewRound {
|
|
179
|
+
const previous = this.saved(job.id, candidate.number);
|
|
180
|
+
if (!route.threadId || previous && (!previous.automation || previous.laneId !== laneId))
|
|
181
|
+
throw new PrControlError("다른 작업이 이미 이 PR의 검토 레인을 소유합니다.");
|
|
182
|
+
const source = intakeWorkId(job.id, candidate.number, revision, head);
|
|
183
|
+
if (this.store.input(source)) throw new PrControlError("이미 접수한 SHA입니다. 자동으로 재실행하지 않습니다.");
|
|
184
|
+
const round: ReviewRound = { job: job.id, number: candidate.number, repository: job.repository, laneId,
|
|
185
|
+
repositoryId: candidate.repositoryId, ownerId: candidate.ownerId, head, epoch: job.epoch, source,
|
|
186
|
+
opener: previous?.opener ?? source, inputId: `handoff:${source}:${previous ? laneId : "lane"}`,
|
|
187
|
+
automation: { revision, anchor: route.threadId } };
|
|
188
|
+
this.store.receivePrWork({ id: source, route, receivedAt: Date.now(), attachments: [], messageId: null,
|
|
189
|
+
text: `Static PR review: ${job.repository}#${candidate.number} ${head}` }, null, round);
|
|
190
|
+
return round;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Captured in the receipt of an incoming owner command, never filled in by
|
|
194
|
+
* the pump later. A queued command cannot borrow a subsequently delivered review. */
|
|
195
|
+
approvalAt(command: Inbound, argument: string): string | null {
|
|
196
|
+
const { route } = command;
|
|
197
|
+
const match = args.exec(argument);
|
|
198
|
+
if (!match || (match[1] !== "pr-fix" && match[1] !== "pr-merge") || !match[2] || !route.threadId) return null;
|
|
199
|
+
const r = this.saved(match[2], Number(match[3]));
|
|
200
|
+
if (!r || r.head !== match[4]) return null;
|
|
201
|
+
let lane: Lane;
|
|
202
|
+
try { lane = this.placed(r); } catch { return null; }
|
|
203
|
+
if (lane.workState !== "open" || routeKey(lane.route) !== routeKey(route)) return null;
|
|
204
|
+
const answer = this.answer(r);
|
|
205
|
+
if (!answer) return null;
|
|
206
|
+
const input = this.store.input(r.inputId);
|
|
207
|
+
const output = this.store.output(`${r.inputId}:answer`);
|
|
208
|
+
// A Gateway catch-up may admit an earlier physical owner message only
|
|
209
|
+
// after the answer has been sent. It is not a later confirmation.
|
|
210
|
+
const event = command.messageId ?? command.interactionId;
|
|
211
|
+
if (!output?.remoteId || !event || compareMessageIds("discord", event, output.remoteId) !== 1) return null;
|
|
212
|
+
return digest(JSON.stringify([r.inputId, r.epoch, input?.requestId, input?.generation, output?.remoteId, answer]));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
private next(r: ReviewRound): string {
|
|
216
|
+
const text = this.answer(r);
|
|
217
|
+
const cmd = `${r.job} ${r.number} ${r.head}`;
|
|
218
|
+
const state = this.store.input(r.inputId)?.state ?? "not admitted";
|
|
219
|
+
if (!text) return `${r.head}: ${state}. 검토 답변의 전송이 확인되기 전에는 병합하거나 수정할 수 없습니다.`;
|
|
220
|
+
if (approved(text)) return prIntakeManualHold(this.store, r, "pr-merge", r.head)
|
|
221
|
+
?? `검토한 SHA: ${r.head}. 현재 CI·보호 규칙을 다시 확인한 뒤 병합하려면 이 스레드에서 /cron pr-merge ${cmd}`;
|
|
222
|
+
const fix = parseIntakeFix(text);
|
|
223
|
+
if (fix) return prIntakeManualHold(this.store, r, "pr-fix", r.head)
|
|
224
|
+
?? `수정 제안: ${fix.path}. 위 답변의 정확한 변경을 확인한 뒤 이 스레드에서 /cron pr-fix ${cmd} ${intakeFixDigest(r.repository, r.number, r.head, fix)}`;
|
|
225
|
+
return `병합 승인 없음. 수정 후 이 스레드에서 /cron pr-review ${r.job} ${r.number} <새 HEAD SHA> 로 다시 검토하세요.`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async control(input: InputRecord, argument: string, options: {
|
|
229
|
+
readonly signal: AbortSignal; readonly verify: () => void;
|
|
230
|
+
readonly newLaneId: string; readonly place: (round: ReviewRound, first: boolean) => Promise<void>;
|
|
231
|
+
}): Promise<string> {
|
|
232
|
+
const match = args.exec(argument);
|
|
233
|
+
if (!match || input.attachments.length || input.pickerSelection || input.target !== "main")
|
|
234
|
+
throw new PrControlError("형식: /cron pr-status JOB NUMBER | pr-review/pr-merge JOB NUMBER SHA | pr-fix JOB NUMBER SHA DIGEST (첨부 없이 새 소유자 명령)");
|
|
235
|
+
const [, verb, jobId, n, head, hash] = match;
|
|
236
|
+
const action = verb as Action;
|
|
237
|
+
const number = Number(n);
|
|
238
|
+
if (!jobId || !Number.isSafeInteger(number) || (action === "pr-status") !== !head || (action === "pr-fix") !== !!hash)
|
|
239
|
+
throw new PrControlError("PR 번호·전체 SHA·수정 승인 해시를 확인하세요.");
|
|
240
|
+
const parent = { ...physicalRoute(input.route), threadId: null };
|
|
241
|
+
const job = this.cron.requireActivePrJob(input, jobId, parent);
|
|
242
|
+
if (this.store.getMeta(`pr-control-epoch:${input.id}`) !== job.epoch)
|
|
243
|
+
throw new PrControlError("명령 접수 이후 등록이 변경되었습니다. 현재 등록을 확인한 뒤 새 명령을 보내세요.");
|
|
244
|
+
const candidate = this.intake.candidate(job, number);
|
|
245
|
+
if (!candidate) throw new PrControlError("이 등록에서 발견한 PR이 아닙니다.");
|
|
246
|
+
let previous = this.saved(jobId, number);
|
|
247
|
+
const automaticStatus = this.store.getMeta(intakeStatusKey(jobId, number));
|
|
248
|
+
if (action === "pr-status" && automaticStatus && !input.route.threadId)
|
|
249
|
+
return automaticStatus;
|
|
250
|
+
let anchored = false;
|
|
251
|
+
const anchor = this.store.getMeta(intakeThreadKey(jobId, number));
|
|
252
|
+
const offer = !previous && anchor ? this.store.output(candidate.outputId) : null;
|
|
253
|
+
const declined = offer?.state === "sent" && !!offer.remoteId && routeKey(parent) === routeKey(offer.route)
|
|
254
|
+
&& anchor === `rejected:${offer.remoteId}`;
|
|
255
|
+
if (!previous && anchor && !declined) {
|
|
256
|
+
anchored = action === "pr-review" && input.route.threadId === anchor && offer?.state === "sent"
|
|
257
|
+
&& offer.remoteId === anchor && routeKey(parent) === routeKey(offer.route) && !this.store.laneForRoute(input.route);
|
|
258
|
+
if (!anchored)
|
|
259
|
+
throw new PrControlError("자동 스레드 생성 영수증이 있습니다. 원래 알림의 스레드를 확인하세요. 두 번째 스레드는 만들지 않습니다.");
|
|
260
|
+
}
|
|
261
|
+
const verify = () => {
|
|
262
|
+
options.verify();
|
|
263
|
+
if (this.store.input(input.id)?.state !== "pending" || this.cron.requireActivePrJob(input, jobId, parent).epoch !== job.epoch)
|
|
264
|
+
throw new PrControlError("원래 명령이 더 이상 활성 상태가 아닙니다.");
|
|
265
|
+
};
|
|
266
|
+
verify();
|
|
267
|
+
const opener = previous ? this.store.input(previous.opener) : null;
|
|
268
|
+
// A definitive preflight refusal before any send can be corrected by a new
|
|
269
|
+
// original owner action. Never reuse a possibly submitted createThread.
|
|
270
|
+
if (previous && action === "pr-review" && !input.route.threadId
|
|
271
|
+
&& opener?.state === "cancelled" && opener.route.threadId === null
|
|
272
|
+
&& this.store.getMeta(`handoff-route:${previous.opener}`) === null
|
|
273
|
+
&& !this.store.input(`handoff:${previous.opener}:lane`) && !this.store.lane(previous.laneId)) previous = null;
|
|
274
|
+
// Discord uses the starter message snowflake as its thread ID. A fresh
|
|
275
|
+
// owner command inside that exact thread can finish a lost create receipt
|
|
276
|
+
// without repeating createThread or adopting a thread by name.
|
|
277
|
+
const destination = previous && this.store.getMeta(`handoff-route:${previous.opener}`);
|
|
278
|
+
const known = destination === "uncertain" && previous ? this.store.getMeta(`handoff-route-result:${previous.opener}`) : destination;
|
|
279
|
+
if (previous && input.route.threadId && action === "pr-review" && input.id !== previous.opener
|
|
280
|
+
&& (known && known !== "uncertain" && routeKey(JSON.parse(known)) === routeKey(input.route)
|
|
281
|
+
|| opener?.route.threadId === null && destination === "uncertain" && opener.messageId === input.route.threadId
|
|
282
|
+
|| opener?.route.threadId === input.route.threadId)
|
|
283
|
+
&& !this.store.input(`handoff:${previous.opener}:lane`) && !this.store.lane(previous.laneId)
|
|
284
|
+
&& !this.store.laneForRoute(input.route)) {
|
|
285
|
+
anchored = true;
|
|
286
|
+
previous = null;
|
|
287
|
+
}
|
|
288
|
+
if (!previous) {
|
|
289
|
+
if (input.route.threadId && !anchored || action !== "pr-review" || !head) throw new PrControlError("원래 등록한 부모 채널에서 /cron pr-review JOB NUMBER SHA 를 보내세요.");
|
|
290
|
+
if (head !== candidate.head) throw new PrControlError("최초 검토는 원래 제안에 표시된 SHA를 지정해야 합니다. 이후 변경은 전용 스레드에서 검토하세요.");
|
|
291
|
+
} else {
|
|
292
|
+
if (!input.route.threadId) {
|
|
293
|
+
if (previous.opener === input.id && !this.store.headLanePlacement(input.id)) {
|
|
294
|
+
throw new PrControlError("이전 배정이 중단되었습니다. 원래 명령·스레드의 실제 상태를 확인하세요. 자동으로 반복하지 않습니다.");
|
|
295
|
+
}
|
|
296
|
+
return `이 PR에는 이미 전용 레인이 있습니다: <#${this.placed(previous).route.threadId}>. 그 스레드에서 /cron pr-status ${jobId} ${number}`;
|
|
297
|
+
}
|
|
298
|
+
const lane = this.placed(previous);
|
|
299
|
+
if (routeKey(lane.route) !== routeKey(input.route)) throw new PrControlError("이 PR의 원래 스레드가 아닙니다.");
|
|
300
|
+
if (lane.workState !== "open" && action !== "pr-status") throw new PrControlError("원래 PR 레인이 중단되었습니다. 먼저 해당 레인의 상태를 확인하세요.");
|
|
301
|
+
const effect = this.effect(previous);
|
|
302
|
+
if (effect?.state === "unknown") {
|
|
303
|
+
if (action !== "pr-status") throw new PrControlError(`GitHub 요청 ${effect.source} 결과 미확인. /cron pr-status ${jobId} ${number} 로 읽기 전용 확인하세요. 반복 실행하지 않습니다.`);
|
|
304
|
+
const fix = parseIntakeFix(this.answer(previous) ?? "");
|
|
305
|
+
const target = JSON.parse(this.store.getMeta(materialKey(previous)) ?? "null");
|
|
306
|
+
const result = effect.action === "pr-merge" && typeof target?.baseRef === "string" && typeof target.baseSha === "string"
|
|
307
|
+
? await this.api.inspectIntakeMerge(job.repository, number, previous.head, options.signal, { ...previous, baseRef: target.baseRef, baseSha: target.baseSha })
|
|
308
|
+
: fix && typeof target?.headRef === "string" ? await this.api.reconcileIntakeFix(job.repository, number, previous.head, fix, options.signal, target.headRef, previous) : null;
|
|
309
|
+
verify();
|
|
310
|
+
if (result?.status === "merged" || result?.status === "applied") {
|
|
311
|
+
this.store.setMeta(effectKey(previous), JSON.stringify({ ...effect, state: "confirmed", sha: result.sha }));
|
|
312
|
+
return `GitHub에서 확인: ${result.status} ${result.sha}. 재시도하지 않았습니다.`;
|
|
313
|
+
}
|
|
314
|
+
return "이전 GitHub 변경을 확인하지 못했습니다. GitHub PR과 커밋 이력을 직접 대조하세요. 이 등록에서는 모호한 쓰기를 다시 보내지 않습니다.";
|
|
315
|
+
}
|
|
316
|
+
if (effect?.state === "confirmed") {
|
|
317
|
+
if (action === "pr-status" || action !== "pr-review" || effect.action === "pr-merge" || head === previous.head)
|
|
318
|
+
return `GitHub 확인: ${effect.action} ${effect.sha}. ${effect.action === "pr-fix" ? `이 스레드에서 /cron pr-review ${jobId} ${number} ${effect.sha} 로 새 HEAD를 다시 검토하세요.` : "종료되었습니다."}`;
|
|
319
|
+
}
|
|
320
|
+
if (action === "pr-status") {
|
|
321
|
+
if (previous.automation && this.needsReconciliation(previous)) {
|
|
322
|
+
const answer = this.answer(previous);
|
|
323
|
+
const material = this.store.getMeta(materialKey(previous));
|
|
324
|
+
const result = await advancePrIntakeAutomation(previous, { store: this.store, mode: "review", observedHead: null,
|
|
325
|
+
reconcileOnly: true, evidence: answer && material ? { answer, material: JSON.parse(material) } : null,
|
|
326
|
+
signal: options.signal, api: this.api, verify: () => { throw new PrControlError("상태 조회는 쓰기 권한이 없습니다."); } });
|
|
327
|
+
verify();
|
|
328
|
+
this.store.setMeta(intakeStatusKey(jobId, number), result.message);
|
|
329
|
+
return result.message;
|
|
330
|
+
}
|
|
331
|
+
return previous.epoch === job.epoch && (!previous.automation || this.cron.prPolicy(job.id)?.revision === previous.automation.revision)
|
|
332
|
+
? [automaticStatus, this.next(previous)].filter(Boolean).join("\n")
|
|
333
|
+
: `이전 등록의 검토입니다. 이 스레드에서 /cron pr-review ${jobId} ${number} <현재 HEAD SHA> 로 다시 검토하세요.`;
|
|
334
|
+
}
|
|
335
|
+
const hold = prIntakeManualHold(this.store, previous, action, head);
|
|
336
|
+
if (hold) throw new PrControlError(hold);
|
|
337
|
+
if (action !== "pr-review") {
|
|
338
|
+
if (previous.epoch !== job.epoch || previous.head !== head || !head) throw new PrControlError("활성 등록의 최종 검토 SHA와 다릅니다. 새로 검토하세요.");
|
|
339
|
+
const approval = this.store.getMeta(`pr-control-review:${input.id}`);
|
|
340
|
+
if (!approval || approval !== this.approvalAt(input, argument))
|
|
341
|
+
throw new PrControlError("명령 접수 시점에 같은 스레드로 전달된 동일 검토 결과가 없습니다. 결과를 확인한 뒤 새 명령을 보내세요.");
|
|
342
|
+
const answer = this.answer(previous);
|
|
343
|
+
if (!answer)
|
|
344
|
+
throw new PrControlError("확인된 검토 결과 또는 수정 제안의 해시가 일치하지 않습니다.");
|
|
345
|
+
const evidence = JSON.parse(this.store.getMeta(materialKey(previous)) ?? "null");
|
|
346
|
+
const reviewed = previous;
|
|
347
|
+
const beforeWrite = () => {
|
|
348
|
+
verify(); this.assertActive(reviewed);
|
|
349
|
+
if (this.effect(reviewed) || approval !== this.approvalAt(input, argument))
|
|
350
|
+
throw new PrControlError("원래 검토·레인·쓰기 상태가 변경되어 요청하지 않았습니다.");
|
|
351
|
+
this.store.setMeta(effectKey(reviewed), JSON.stringify({ source: input.id, action, state: "unknown" } satisfies Effect));
|
|
352
|
+
};
|
|
353
|
+
let result: Awaited<ReturnType<typeof mergeIntakePull | typeof applyIntakeFix>>;
|
|
354
|
+
switch (action) {
|
|
355
|
+
case "pr-fix": {
|
|
356
|
+
const fix = parseIntakeFix(answer);
|
|
357
|
+
if (!fix || intakeFixDigest(job.repository, number, head, fix) !== hash)
|
|
358
|
+
throw new PrControlError("소유자가 지정한 해시가 해당 SHA의 수정 제안과 일치하지 않습니다.");
|
|
359
|
+
result = await this.api.applyIntakeFix(job.repository, number, head, fix, options.signal, confirmed => {
|
|
360
|
+
if (digest(confirmed) !== evidence?.digest) throw new PrControlError("수정 직전 검토 자료가 바뀌었습니다.");
|
|
361
|
+
beforeWrite();
|
|
362
|
+
}, previous);
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
case "pr-merge": {
|
|
366
|
+
if (!approved(answer)) throw new PrControlError("이 SHA에 대한 레인 검토의 병합 승인이 없습니다.");
|
|
367
|
+
const material = await this.api.readIntakeMaterial(job.repository, number, head, options.signal, previous);
|
|
368
|
+
if (digest(material) !== evidence?.digest) throw new PrControlError("검토 이후 PR 기준 브랜치 또는 내용이 바뀌었습니다. 같은 스레드에서 다시 검토하세요.");
|
|
369
|
+
result = await this.api.mergeIntakePull(job.repository, number, head, options.signal, beforeWrite,
|
|
370
|
+
{ ...previous, ...readIntakeMaterialTarget(material) });
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (result.status === "merged" || result.status === "applied") {
|
|
375
|
+
this.store.setMeta(effectKey(previous), JSON.stringify({ source: input.id, action, state: "confirmed", sha: result.sha } satisfies Effect));
|
|
376
|
+
return result.status === "merged" ? `GitHub 병합 확인: ${result.sha}` : `GitHub 수정 커밋 확인: ${result.sha}. /cron pr-review ${jobId} ${number} ${result.sha}`;
|
|
377
|
+
}
|
|
378
|
+
if (result.status === "blocked" && this.effect(previous)?.source === input.id)
|
|
379
|
+
this.store.setMeta(effectKey(previous), "null"); // Definitive refusal, not an ambiguous request.
|
|
380
|
+
return `GitHub ${result.status}: ${result.reason}. /cron pr-status ${jobId} ${number}`;
|
|
381
|
+
}
|
|
382
|
+
const old = this.store.input(previous.inputId);
|
|
383
|
+
if (old?.state === "pending" || old?.state === "submitted" || old?.state === "uncertain")
|
|
384
|
+
throw new PrControlError(`이전 검토 ${old.id}: ${old.state}. 기존 요청을 먼저 확인하세요.`);
|
|
385
|
+
}
|
|
386
|
+
if (!head) throw new PrControlError("전체 검토 SHA가 필요합니다.");
|
|
387
|
+
const laneId = previous?.laneId ?? options.newLaneId;
|
|
388
|
+
const round: ReviewRound = { job: jobId, number, repository: job.repository, laneId, opener: previous?.opener ?? input.id,
|
|
389
|
+
repositoryId: candidate.repositoryId, ownerId: candidate.ownerId,
|
|
390
|
+
head, source: input.id, epoch: job.epoch, inputId: `handoff:${input.id}:${previous ? laneId : "lane"}` };
|
|
391
|
+
this.store.setMeta(scopeKey(jobId, number), JSON.stringify(round));
|
|
392
|
+
this.store.setMeta(pointer(laneId), scopeKey(jobId, number));
|
|
393
|
+
this.store.setMeta(`topic-owner:${input.id}`, laneId);
|
|
394
|
+
await options.place(round, !previous);
|
|
395
|
+
return `PR #${number} 검토를 접수했습니다. 결과 확인: /cron pr-status ${jobId} ${number}`;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Type, type Static } from "@sinclair/typebox/type";
|
|
3
|
+
import { PrReadError } from "./pr-github-schema";
|
|
4
|
+
import type { openIntakeGitHubSession } from "./pr-intake-github";
|
|
5
|
+
|
|
6
|
+
type Session = Awaited<ReturnType<typeof openIntakeGitHubSession>>;
|
|
7
|
+
const sha = Type.String({ pattern: "^[0-9a-f]{40}$" });
|
|
8
|
+
const entry = Type.Object({ mode: Type.String(), type: Type.String(), sha, path: Type.String() });
|
|
9
|
+
const commit = Type.Object({ sha, tree: Type.Object({ sha }) });
|
|
10
|
+
const tree = Type.Object({ sha, truncated: Type.Literal(false), tree: Type.Array(entry) });
|
|
11
|
+
const blob = Type.Object({
|
|
12
|
+
sha, size: Type.Integer({ minimum: 0 }), encoding: Type.Literal("base64"), content: Type.String(),
|
|
13
|
+
});
|
|
14
|
+
type Entry = Static<typeof entry>;
|
|
15
|
+
export type RegularBlob = { readonly sha: string; readonly mode: "100644" | "100755" };
|
|
16
|
+
|
|
17
|
+
/** Only commit/tree IDs (never contributor paths) are passed to GitHub Git Data API endpoints. */
|
|
18
|
+
export async function openIntakeTree(session: Session, head: string) {
|
|
19
|
+
const [root] = await session.get(`${session.root}/git/commits/${head}`, Type.Tuple([commit]));
|
|
20
|
+
if (root.sha !== head) throw new PrReadError("response");
|
|
21
|
+
const cache = new Map<string, Promise<ReadonlyMap<string, Entry>>>();
|
|
22
|
+
const readTree = async (oid: string): Promise<ReadonlyMap<string, Entry>> => {
|
|
23
|
+
const [result] = await session.get(`${session.root}/git/trees/${oid}`, Type.Tuple([tree]));
|
|
24
|
+
const entries = new Map(result.tree.map(item => [item.path, item]));
|
|
25
|
+
if (result.sha !== oid || entries.size !== result.tree.length) throw new PrReadError("response");
|
|
26
|
+
return entries;
|
|
27
|
+
};
|
|
28
|
+
return async (path: string): Promise<RegularBlob | null> => {
|
|
29
|
+
const parts = path.split("/");
|
|
30
|
+
if (parts.length > 12 || parts.some(part => !part || part === "." || part === ".." || /[\x00-\x1f\x7f]/.test(part)))
|
|
31
|
+
throw new PrReadError("response");
|
|
32
|
+
let oid = root.tree.sha;
|
|
33
|
+
for (const [index, part] of parts.entries()) {
|
|
34
|
+
let contents = cache.get(oid);
|
|
35
|
+
if (!contents) {
|
|
36
|
+
contents = readTree(oid);
|
|
37
|
+
cache.set(oid, contents);
|
|
38
|
+
}
|
|
39
|
+
const item = (await contents).get(part);
|
|
40
|
+
if (!item) return null;
|
|
41
|
+
if (index === parts.length - 1) {
|
|
42
|
+
if (item.type !== "blob" || (item.mode !== "100644" && item.mode !== "100755"))
|
|
43
|
+
throw new PrReadError("response");
|
|
44
|
+
return { sha: item.sha, mode: item.mode };
|
|
45
|
+
}
|
|
46
|
+
if (item.type !== "tree" || item.mode !== "040000") throw new PrReadError("response");
|
|
47
|
+
oid = item.sha;
|
|
48
|
+
}
|
|
49
|
+
throw new PrReadError("response");
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function readIntakeBlob(session: Session, oid: string, maxBytes: number): Promise<string> {
|
|
54
|
+
const [result] = await session.get(`${session.root}/git/blobs/${oid}`, Type.Tuple([blob]));
|
|
55
|
+
if (result.sha !== oid || result.size > maxBytes) throw new PrReadError("response");
|
|
56
|
+
const encoded = result.content.replace(/\n/g, "");
|
|
57
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
58
|
+
if (bytes.length !== result.size || bytes.toString("base64") !== encoded
|
|
59
|
+
|| createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex") !== oid)
|
|
60
|
+
throw new PrReadError("response");
|
|
61
|
+
try {
|
|
62
|
+
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
63
|
+
if (text.includes("\0")) throw new PrReadError("response");
|
|
64
|
+
return text;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error instanceof TypeError) throw new PrReadError("response");
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { routeKey, type InputRecord, type StorePort } from "./contracts";
|
|
2
|
+
|
|
3
|
+
// Controller receipts have no platform message/interaction and are never owner
|
|
4
|
+
// inputs. Only the restricted lane's exact native result has a delivery route.
|
|
5
|
+
export const intakeWorkPrefix = "pr-intake-work:";
|
|
6
|
+
export const intakeWorkId = (job: string, number: number, revision: string, head: string) => `${intakeWorkPrefix}${job}:${number}:${revision}:${head}`;
|
|
7
|
+
export const intakeThreadKey = (job: string, number: number) => `pr-intake-thread:${job}:${number}`;
|
|
8
|
+
export const intakeStatusKey = (job: string, number: number) => `pr-intake-status:${job}:${number}`;
|
|
9
|
+
export function prThreadTitle(repository: string, number: number): string {
|
|
10
|
+
const suffix = ` #${number}`;
|
|
11
|
+
return repository.slice(0, 100 - suffix.length) + suffix; // Discord thread title limit; GitHub slugs are ASCII.
|
|
12
|
+
}
|
|
13
|
+
export function unattendedSource(store: StorePort, input: InputRecord): string | null {
|
|
14
|
+
const id = store.getMeta(`handoff-source:${input.id}`);
|
|
15
|
+
return id?.startsWith(intakeWorkPrefix) ? id : null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function hasIntakeReplyRoute(store: StorePort, input: InputRecord, id: string): boolean {
|
|
19
|
+
const source = store.input(id);
|
|
20
|
+
const lane = input.target && input.target !== "main" ? store.lane(input.target) : null;
|
|
21
|
+
const pointer = lane && store.getMeta(`pr-review-lane:${lane.id}`);
|
|
22
|
+
const raw = pointer && store.getMeta(pointer);
|
|
23
|
+
if (!raw || !lane || !source || source.messageId !== null || source.interactionId !== undefined
|
|
24
|
+
|| (source.state !== "pending" && source.state !== "done") || store.getMeta(`user-source:${id}`) !== null) return false;
|
|
25
|
+
const round = JSON.parse(raw);
|
|
26
|
+
return round.inputId === input.id && round.source === id && round.laneId === lane.id && !!round.automation
|
|
27
|
+
&& source.route.threadId === round.automation.anchor && routeKey(lane.route) === routeKey(source.route)
|
|
28
|
+
&& routeKey(input.route) === routeKey(lane.route);
|
|
29
|
+
}
|