omp-superagent 0.1.17 → 0.1.19

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 (82) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +205 -59
  4. package/docs/OPERATIONS.md +173 -47
  5. package/docs/design/execution.md +119 -37
  6. package/docs/design/messaging.md +160 -45
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/docs/releases/0.1.19.md +10 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +6 -5
  19. package/skills/head/references/model-selection.md +8 -22
  20. package/skills/head/references/routing.md +36 -17
  21. package/skills/lane/SKILL.md +24 -76
  22. package/skills/lane/references/workflow.md +7 -94
  23. package/src/cli.ts +36 -16
  24. package/src/config/config.ts +21 -2
  25. package/src/contracts.ts +66 -7
  26. package/src/cron/cron-jobs.ts +135 -92
  27. package/src/cron/cron-pr-intake.ts +18 -11
  28. package/src/extension.ts +25 -10
  29. package/src/gateway/gateway-client.ts +3 -1
  30. package/src/host-extension.ts +76 -8
  31. package/src/lane/lane-report.ts +1 -1
  32. package/src/lane/lane-rows.ts +2 -1
  33. package/src/lane/workflow.ts +12 -6
  34. package/src/lane-extension.ts +4 -21
  35. package/src/managed-super-probe.ts +21 -15
  36. package/src/messaging/messenger-command-catalog.json +1 -1
  37. package/src/messaging/messenger-commands.ts +8 -3
  38. package/src/messaging/result-attachment.ts +77 -19
  39. package/src/messaging/slack-context.ts +50 -0
  40. package/src/messaging/written-directives.ts +56 -0
  41. package/src/omp/exit-record.ts +27 -0
  42. package/src/omp/host-protocol.ts +20 -0
  43. package/src/omp/host.ts +73 -20
  44. package/src/omp/installed-omp.ts +15 -12
  45. package/src/omp/managed-super.ts +135 -65
  46. package/src/omp/superkit-skills.ts +15 -2
  47. package/src/pr/pr-intake-order.ts +62 -0
  48. package/src/pr/pr-intake-review.ts +49 -31
  49. package/src/pr/pr-intake-work.ts +3 -2
  50. package/src/routing/message-order.ts +22 -1
  51. package/src/routing/topic-request.ts +48 -4
  52. package/src/runtime/controller.ts +968 -338
  53. package/src/runtime/deferred-routing.ts +12 -4
  54. package/src/runtime/dm-timeline.ts +3 -3
  55. package/src/runtime/inbound-attachments.ts +70 -0
  56. package/src/runtime/local-host-fence.ts +85 -0
  57. package/src/runtime/model-journal.ts +14 -9
  58. package/src/runtime/native-frames.ts +5 -1
  59. package/src/runtime/result-attachments.ts +151 -24
  60. package/src/runtime/worker-result-download.ts +36 -0
  61. package/src/storage/deferred-routing.ts +25 -4
  62. package/src/storage/store.ts +445 -75
  63. package/src/worker/worker-checkout.ts +89 -9
  64. package/src/worker/worker-destination.ts +8 -7
  65. package/src/worker/worker-doctor.ts +29 -9
  66. package/src/worker/worker-enrollment.ts +44 -12
  67. package/src/worker/worker-git-startup.ts +157 -0
  68. package/src/worker/worker-host.ts +16 -26
  69. package/src/worker/worker-ledger.ts +42 -18
  70. package/src/worker/worker-placement-intent.ts +13 -0
  71. package/src/worker/worker-placement.ts +204 -28
  72. package/src/worker/worker-profile.ts +18 -65
  73. package/src/worker/worker-project-startup.ts +106 -0
  74. package/src/worker/worker-registration.ts +85 -30
  75. package/src/worker/worker-repository.ts +55 -6
  76. package/src/worker/worker-request.ts +13 -6
  77. package/src/worker/worker-result-attachments.ts +185 -0
  78. package/src/worker/worker-result-wire.ts +12 -0
  79. package/src/worker/worker-service.ts +51 -23
  80. package/src/worker/worker-trust.ts +19 -4
  81. package/src/worker/worker-wire.ts +47 -14
  82. package/upstream/super.json +2 -3
@@ -1,8 +1,8 @@
1
1
  import { lstatSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
 
4
- // Canonical skill IDs match the commands. Legacy IDs remain wire tags and
5
- // aliases (the plain SUPER command's legacy command name is "ulw").
4
+ // Canonical skill IDs match the commands. Older revisions used the legacy IDs
5
+ // as aliases and as pointer tags, including during the canonical skill rollout.
6
6
  export const superkitWorkflows = [
7
7
  ["super-plan", "ulw-plan"],
8
8
  ["super-run", "ulw-execute"],
@@ -20,3 +20,16 @@ export function hasCanonicalSuperkitSkills(packagePath: string): boolean {
20
20
  return canonicalSuperkitSkills.some(id =>
21
21
  lstatSync(join(packagePath, "skills", id, "SKILL.md"), { throwIfNoEntry: false }) !== undefined);
22
22
  }
23
+
24
+ export function matchesSuperkitPointer(content: unknown, [command, legacyId]: typeof superkitWorkflows[number], target: string): boolean {
25
+ if (typeof content !== "string") return false;
26
+ for (const id of [command, legacyId]) {
27
+ const open = `<omp-${id}-pointer>`;
28
+ const close = `</omp-${id}-pointer>`;
29
+ if (!content.startsWith(open) || !content.endsWith(close)) continue;
30
+ // The wrapper and canonical skill path can both contain the command.
31
+ const body = content.slice(open.length, -close.length);
32
+ return body.includes(target) && body.split(target).some(part => part.includes(command));
33
+ }
34
+ return false;
35
+ }
@@ -0,0 +1,62 @@
1
+ import type { Inbound, OutputRecord, Route, StorePort } from "../contracts";
2
+ import { matchesWrittenCommand } from "../messaging/messenger-commands";
3
+ import { compareMessageIds, slackOutputTimestamp } from "../routing/message-order";
4
+
5
+ export interface PrPhysicalEvent {
6
+ readonly platform: "discord" | "slack";
7
+ readonly accountId: string;
8
+ readonly authorityId: string;
9
+ readonly timestamp: string;
10
+ }
11
+
12
+ export function isPrMessageId(platform: Route["platform"], id: unknown): id is string {
13
+ if (typeof id !== "string") return false;
14
+ if (platform === "slack") return /^\d{1,20}\.\d{6}$/.test(id);
15
+ return platform === "discord" && /^[1-9]\d{0,19}$/.test(id) && BigInt(id) <= (1n << 64n) - 1n;
16
+ }
17
+
18
+ function isPrPhysicalEvent(value: unknown): value is PrPhysicalEvent {
19
+ return value !== null && typeof value === "object" && "platform" in value && "timestamp" in value
20
+ && (value.platform === "slack" || value.platform === "discord") && isPrMessageId(value.platform, value.timestamp)
21
+ && "accountId" in value && typeof value.accountId === "string"
22
+ && "authorityId" in value && typeof value.authorityId === "string";
23
+ }
24
+
25
+ export function prPhysicalEvent(input: Inbound): PrPhysicalEvent | null {
26
+ const { route: { platform, accountId, authorityId, channelId }, messageId, interactionId } = input;
27
+ if ((platform !== "discord" && platform !== "slack") || input.pickerSelection || input.invocationId !== undefined
28
+ || !matchesWrittenCommand(input)) return null;
29
+ const timestamp = messageId ?? interactionId;
30
+ if (!isPrMessageId(platform, timestamp)) return null;
31
+ if (platform === "slack") {
32
+ if (interactionId !== undefined || messageId === null || input.unresolvedReply
33
+ || input.id !== `slack:${accountId}:${channelId}:${messageId}:original`) return null;
34
+ } else if (messageId === null ? input.id !== `discord:${accountId}:interaction:${timestamp}`
35
+ : interactionId !== undefined || input.id.startsWith(`discord:${accountId}:${messageId}:edit:`)) return null;
36
+ return { platform, accountId, authorityId, timestamp };
37
+ }
38
+
39
+ export function samePrClock(left: PrPhysicalEvent, right: PrPhysicalEvent): boolean {
40
+ return left.platform === right.platform && left.accountId === right.accountId && left.authorityId === right.authorityId;
41
+ }
42
+
43
+ export function afterPrMessage(platform: Route["platform"], order: unknown, boundary: unknown): boolean {
44
+ return isPrMessageId(platform, order) && isPrMessageId(platform, boundary)
45
+ && compareMessageIds(platform, order, boundary) === 1;
46
+ }
47
+
48
+ /** Slack approvals need the final immutable post timestamp. A Slack file ID carries no send order. */
49
+ export function prSentOrder(store: StorePort, output: OutputRecord): string | null {
50
+ const { platform } = output.route;
51
+ if (platform === "slack") return slackOutputTimestamp(store, output);
52
+ return output.state === "sent" && isPrMessageId(platform, output.remoteId) ? output.remoteId : null;
53
+ }
54
+
55
+ export function readPrStopOrder(receipt: object, source: PrPhysicalEvent | null): PrPhysicalEvent | null {
56
+ if (source === null) return null;
57
+ if ("prOrder" in receipt)
58
+ return isPrPhysicalEvent(receipt.prOrder) && samePrClock(receipt.prOrder, source) ? receipt.prOrder : null;
59
+ if ("prDiscordOrder" in receipt) return source.platform === "discord" && isPrMessageId("discord", receipt.prDiscordOrder)
60
+ ? { ...source, timestamp: receipt.prDiscordOrder } : null;
61
+ return source;
62
+ }
@@ -1,9 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { physicalRoute, routeKey, type Inbound, type InputRecord, type Lane, type Route, type StorePort } from "../contracts";
3
- import { compareMessageIds } from "../routing/message-order";
4
3
  import type { CronJobs, CronPrJob } from "../cron/cron-jobs";
5
4
  import type { CronPrCandidate, CronPrIntake } from "../cron/cron-pr-intake";
6
- import { hasIntakeReplyRoute, intakeThreadKey, intakeStatusKey, intakeWorkId, intakeWorkPrefix } from "./pr-intake-work";
5
+ import { hasIntakeReplyRoute, intakeThreadKey, intakeStatusKey, intakeWorkId, intakeWorkPrefix, prCronCommand } from "./pr-intake-work";
6
+ import { afterPrMessage, isPrMessageId, prPhysicalEvent, prSentOrder } from "./pr-intake-order";
7
7
  import { hasExactJsonPropertyCount } from "./pr-github-schema";
8
8
  import { inspectIntakeMerge, mergeIntakePull } from "./pr-intake-github";
9
9
  import { applyIntakeFix, intakeFixDigest, parseIntakeFix, reconcileIntakeFix } from "./pr-intake-fix";
@@ -102,6 +102,7 @@ export class PrReviews {
102
102
  || routeKey(parent) !== routeKey(active.source.route) || source.route.threadId !== offer.remoteId
103
103
  || (source.state !== "pending" && source.state !== "done")
104
104
  || !source.id.startsWith(intakeWorkPrefix) || source.messageId !== null || source.interactionId !== undefined
105
+ || source.invocationId !== undefined
105
106
  || this.store.getMeta(`user-source:${source.id}`) !== null)
106
107
  throw new PrControlError("등록한 자동 단계 또는 원래 PR·스레드 영수증을 확인하지 못했습니다.");
107
108
  } else if (this.cron.requireActivePrJob(source, r.job, parent).epoch !== r.epoch)
@@ -124,7 +125,7 @@ export class PrReviews {
124
125
  }
125
126
  const lane = this.store.headLanePlacement(r.opener);
126
127
  if (!lane || lane === "unverified" || lane.id !== r.laneId || !lane.route.threadId || lane.remote)
127
- throw new PrControlError("스레드 생성·레인 배정·시작 메시지 중 확인되지 않은 단계가 있습니다. 원래 명령과 Discord 전송 기록을 대조하세요. 스레드를 다시 만들지 않습니다.");
128
+ throw new PrControlError("스레드 생성·레인 배정·시작 메시지 중 확인되지 않은 단계가 있습니다. 원래 명령과 메신저 전송 기록을 대조하세요. 스레드를 다시 만들지 않습니다.");
128
129
  return lane;
129
130
  }
130
131
 
@@ -150,19 +151,20 @@ export class PrReviews {
150
151
 
151
152
  async advance(r: ReviewRound, observedHead: string | null, policy: NonNullable<ReturnType<CronJobs["prPolicy"]>>,
152
153
  signal: AbortSignal, verifyRound: () => void): Promise<{ text: string; nextHead: string | null }> {
154
+ const command = prCronCommand(this.store.input(r.source)?.route.platform ?? "discord");
153
155
  const manual = this.effect(r);
154
- if (manual) return { text: `별도의 소유자 명령 ${manual.action}: ${manual.state}. /cron pr-status ${r.job} ${r.number}`, nextHead: null };
156
+ if (manual) return { text: `별도의 소유자 명령 ${manual.action}: ${manual.state}. ${command} pr-status ${r.job} ${r.number}`, nextHead: null };
155
157
  const input = this.store.input(r.inputId);
156
158
  if (!input || input.state === "pending" || input.state === "submitted" || input.state === "uncertain")
157
159
  return { text: `PR #${r.number} ${r.head}: 검토 ${input?.state ?? "미확인"}.`, nextHead: null };
158
160
  if (input.state === "cancelled" && observedHead === r.head) {
159
161
  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 };
162
+ return { text: `${why} 원인을 해결한 뒤 이 스레드에서 ${command} pr-review ${r.job} ${r.number} ${r.head}`, nextHead: null };
161
163
  }
162
164
  const answer = this.answer(r);
163
165
  const material = this.store.getMeta(materialKey(r));
164
166
  if (input.state === "done" && !answer)
165
- return { text: "원래 검토 답변의 Discord 전달이 확인되지 않아 새 검토·쓰기를 보류했습니다.", nextHead: null };
167
+ return { text: "원래 검토 답변의 전달이 확인되지 않아 새 검토·쓰기를 보류했습니다.", nextHead: null };
166
168
  const rank = { review: 1, fix: 2, merge: 3 } as const;
167
169
  const verify = (stage: PrIntakeMode) => {
168
170
  verifyRound();
@@ -195,7 +197,9 @@ export class PrReviews {
195
197
  approvalAt(command: Inbound, argument: string): string | null {
196
198
  const { route } = command;
197
199
  const match = args.exec(argument);
198
- if (!match || (match[1] !== "pr-fix" && match[1] !== "pr-merge") || !match[2] || !route.threadId) return null;
200
+ const event = prPhysicalEvent(command);
201
+ if (!event || command.attachments.length || !match
202
+ || (match[1] !== "pr-fix" && match[1] !== "pr-merge") || !match[2] || !route.threadId) return null;
199
203
  const r = this.saved(match[2], Number(match[3]));
200
204
  if (!r || r.head !== match[4]) return null;
201
205
  let lane: Lane;
@@ -205,33 +209,34 @@ export class PrReviews {
205
209
  if (!answer) return null;
206
210
  const input = this.store.input(r.inputId);
207
211
  const output = this.store.output(`${r.inputId}:answer`);
212
+ const sentOrder = output && prSentOrder(this.store, output);
208
213
  // A Gateway catch-up may admit an earlier physical owner message only
209
214
  // 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]));
215
+ if (!sentOrder || !afterPrMessage(event.platform, event.timestamp, sentOrder)) return null;
216
+ return digest(JSON.stringify([r.inputId, r.epoch, input?.requestId, input?.generation, sentOrder, answer]));
213
217
  }
214
218
 
215
- private next(r: ReviewRound): string {
219
+ private next(r: ReviewRound, command: string): string {
216
220
  const text = this.answer(r);
217
221
  const cmd = `${r.job} ${r.number} ${r.head}`;
218
222
  const state = this.store.input(r.inputId)?.state ?? "not admitted";
219
223
  if (!text) return `${r.head}: ${state}. 검토 답변의 전송이 확인되기 전에는 병합하거나 수정할 수 없습니다.`;
220
224
  if (approved(text)) return prIntakeManualHold(this.store, r, "pr-merge", r.head)
221
- ?? `검토한 SHA: ${r.head}. 현재 CI·보호 규칙을 다시 확인한 뒤 병합하려면 이 스레드에서 /cron pr-merge ${cmd}`;
225
+ ?? `검토한 SHA: ${r.head}. 현재 CI·보호 규칙을 다시 확인한 뒤 병합하려면 이 스레드에서 ${command} pr-merge ${cmd}`;
222
226
  const fix = parseIntakeFix(text);
223
227
  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> 로 다시 검토하세요.`;
228
+ ?? `수정 제안: ${fix.path}. 위 답변의 정확한 변경을 확인한 뒤 이 스레드에서 ${command} pr-fix ${cmd} ${intakeFixDigest(r.repository, r.number, r.head, fix)}`;
229
+ return `병합 승인 없음. 수정 후 이 스레드에서 ${command} pr-review ${r.job} ${r.number} <새 HEAD SHA> 로 다시 검토하세요.`;
226
230
  }
227
231
 
228
232
  async control(input: InputRecord, argument: string, options: {
229
233
  readonly signal: AbortSignal; readonly verify: () => void;
230
234
  readonly newLaneId: string; readonly place: (round: ReviewRound, first: boolean) => Promise<void>;
231
235
  }): Promise<string> {
236
+ const command = prCronCommand(input.route.platform);
232
237
  const match = args.exec(argument);
233
238
  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 (첨부 없이 새 소유자 명령)");
239
+ throw new PrControlError(`형식: ${command} pr-status JOB NUMBER | pr-review/pr-merge JOB NUMBER SHA | pr-fix JOB NUMBER SHA DIGEST (첨부 없이 새 소유자 명령)`);
235
240
  const [, verb, jobId, n, head, hash] = match;
236
241
  const action = verb as Action;
237
242
  const number = Number(n);
@@ -241,6 +246,8 @@ export class PrReviews {
241
246
  const job = this.cron.requireActivePrJob(input, jobId, parent);
242
247
  if (this.store.getMeta(`pr-control-epoch:${input.id}`) !== job.epoch)
243
248
  throw new PrControlError("명령 접수 이후 등록이 변경되었습니다. 현재 등록을 확인한 뒤 새 명령을 보내세요.");
249
+ if (input.route.platform === "slack" && !this.cron.followsPrEpoch(input, job))
250
+ throw new PrControlError(`현재 등록 이후에 보낸 Slack 명령임을 확인할 수 없습니다. 새 ${command} 명령을 보내세요.`);
244
251
  const candidate = this.intake.candidate(job, number);
245
252
  if (!candidate) throw new PrControlError("이 등록에서 발견한 PR이 아닙니다.");
246
253
  let previous = this.saved(jobId, number);
@@ -248,16 +255,23 @@ export class PrReviews {
248
255
  if (action === "pr-status" && automaticStatus && !input.route.threadId)
249
256
  return automaticStatus;
250
257
  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}`;
258
+ const threadKey = intakeThreadKey(jobId, number);
259
+ const anchor = this.store.getMeta(threadKey);
260
+ const slackAlert = input.route.platform === "slack" && input.route.threadId !== null;
261
+ const offer = !previous && (anchor || slackAlert) ? this.store.output(candidate.outputId) : null;
262
+ const sentRoot = offer?.state === "sent" && offer.sourceId === job.sourceId
263
+ && routeKey(parent) === routeKey(offer.route) && isPrMessageId(parent.platform, offer.remoteId) ? offer.remoteId : null;
264
+ const declined = sentRoot !== null && anchor === `rejected:${sentRoot}`;
255
265
  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);
266
+ anchored = action === "pr-review" && input.route.threadId === anchor && sentRoot === anchor
267
+ && !this.store.laneForRoute(input.route);
258
268
  if (!anchored)
259
269
  throw new PrControlError("자동 스레드 생성 영수증이 있습니다. 원래 알림의 스레드를 확인하세요. 두 번째 스레드는 만들지 않습니다.");
260
270
  }
271
+ const claimSlackRoot = !previous && anchor === null && slackAlert && sentRoot === input.route.threadId
272
+ && action === "pr-review" && input.messageId !== null && afterPrMessage("slack", input.messageId, sentRoot)
273
+ && !this.store.laneForRoute(input.route);
274
+ if (claimSlackRoot) anchored = true;
261
275
  const verify = () => {
262
276
  options.verify();
263
277
  if (this.store.input(input.id)?.state !== "pending" || this.cron.requireActivePrJob(input, jobId, parent).epoch !== job.epoch)
@@ -271,7 +285,7 @@ export class PrReviews {
271
285
  && opener?.state === "cancelled" && opener.route.threadId === null
272
286
  && this.store.getMeta(`handoff-route:${previous.opener}`) === null
273
287
  && !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
288
+ // Discord and Slack use the starter message ID as the thread ID. A fresh
275
289
  // owner command inside that exact thread can finish a lost create receipt
276
290
  // without repeating createThread or adopting a thread by name.
277
291
  const destination = previous && this.store.getMeta(`handoff-route:${previous.opener}`);
@@ -286,21 +300,24 @@ export class PrReviews {
286
300
  previous = null;
287
301
  }
288
302
  if (!previous) {
289
- if (input.route.threadId && !anchored || action !== "pr-review" || !head) throw new PrControlError("원래 등록한 부모 채널에서 /cron pr-review JOB NUMBER SHA 를 보내세요.");
303
+ if (input.route.threadId && !anchored || action !== "pr-review" || !head)
304
+ throw new PrControlError(`원래 등록한 부모 채널에서 ${command} pr-review JOB NUMBER SHA 를 보내세요.`);
290
305
  if (head !== candidate.head) throw new PrControlError("최초 검토는 원래 제안에 표시된 SHA를 지정해야 합니다. 이후 변경은 전용 스레드에서 검토하세요.");
291
306
  } else {
292
307
  if (!input.route.threadId) {
293
308
  if (previous.opener === input.id && !this.store.headLanePlacement(input.id)) {
294
309
  throw new PrControlError("이전 배정이 중단되었습니다. 원래 명령·스레드의 실제 상태를 확인하세요. 자동으로 반복하지 않습니다.");
295
310
  }
296
- return `이 PR에는 이미 전용 레인이 있습니다: <#${this.placed(previous).route.threadId}>. 그 스레드에서 /cron pr-status ${jobId} ${number}`;
311
+ const root = this.placed(previous).route.threadId;
312
+ const thread = input.route.platform === "slack" ? `Slack 스레드 (${root})` : `<#${root}>`;
313
+ return `이 PR에는 이미 전용 레인이 있습니다: ${thread}. 그 스레드에서 ${command} pr-status ${jobId} ${number}`;
297
314
  }
298
315
  const lane = this.placed(previous);
299
316
  if (routeKey(lane.route) !== routeKey(input.route)) throw new PrControlError("이 PR의 원래 스레드가 아닙니다.");
300
317
  if (lane.workState !== "open" && action !== "pr-status") throw new PrControlError("원래 PR 레인이 중단되었습니다. 먼저 해당 레인의 상태를 확인하세요.");
301
318
  const effect = this.effect(previous);
302
319
  if (effect?.state === "unknown") {
303
- if (action !== "pr-status") throw new PrControlError(`GitHub 요청 ${effect.source} 결과 미확인. /cron pr-status ${jobId} ${number} 로 읽기 전용 확인하세요. 반복 실행하지 않습니다.`);
320
+ if (action !== "pr-status") throw new PrControlError(`GitHub 요청 ${effect.source} 결과 미확인. ${command} pr-status ${jobId} ${number} 로 읽기 전용 확인하세요. 반복 실행하지 않습니다.`);
304
321
  const fix = parseIntakeFix(this.answer(previous) ?? "");
305
322
  const target = JSON.parse(this.store.getMeta(materialKey(previous)) ?? "null");
306
323
  const result = effect.action === "pr-merge" && typeof target?.baseRef === "string" && typeof target.baseSha === "string"
@@ -315,7 +332,7 @@ export class PrReviews {
315
332
  }
316
333
  if (effect?.state === "confirmed") {
317
334
  if (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를 다시 검토하세요.` : "종료되었습니다."}`;
335
+ return `GitHub 확인: ${effect.action} ${effect.sha}. ${effect.action === "pr-fix" ? `이 스레드에서 ${command} pr-review ${jobId} ${number} ${effect.sha} 로 새 HEAD를 다시 검토하세요.` : "종료되었습니다."}`;
319
336
  }
320
337
  if (action === "pr-status") {
321
338
  if (previous.automation && this.needsReconciliation(previous)) {
@@ -329,8 +346,8 @@ export class PrReviews {
329
346
  return result.message;
330
347
  }
331
348
  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> 로 다시 검토하세요.`;
349
+ ? [automaticStatus, this.next(previous, command)].filter(Boolean).join("\n")
350
+ : `이전 등록의 검토입니다. 이 스레드에서 ${command} pr-review ${jobId} ${number} <현재 HEAD SHA> 로 다시 검토하세요.`;
334
351
  }
335
352
  const hold = prIntakeManualHold(this.store, previous, action, head);
336
353
  if (hold) throw new PrControlError(hold);
@@ -373,11 +390,11 @@ export class PrReviews {
373
390
  }
374
391
  if (result.status === "merged" || result.status === "applied") {
375
392
  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}`;
393
+ return result.status === "merged" ? `GitHub 병합 확인: ${result.sha}` : `GitHub 수정 커밋 확인: ${result.sha}. ${command} pr-review ${jobId} ${number} ${result.sha}`;
377
394
  }
378
395
  if (result.status === "blocked" && this.effect(previous)?.source === input.id)
379
396
  this.store.setMeta(effectKey(previous), "null"); // Definitive refusal, not an ambiguous request.
380
- return `GitHub ${result.status}: ${result.reason}. /cron pr-status ${jobId} ${number}`;
397
+ return `GitHub ${result.status}: ${result.reason}. ${command} pr-status ${jobId} ${number}`;
381
398
  }
382
399
  const old = this.store.input(previous.inputId);
383
400
  if (old?.state === "pending" || old?.state === "submitted" || old?.state === "uncertain")
@@ -388,10 +405,11 @@ export class PrReviews {
388
405
  const round: ReviewRound = { job: jobId, number, repository: job.repository, laneId, opener: previous?.opener ?? input.id,
389
406
  repositoryId: candidate.repositoryId, ownerId: candidate.ownerId,
390
407
  head, source: input.id, epoch: job.epoch, inputId: `handoff:${input.id}:${previous ? laneId : "lane"}` };
408
+ if (claimSlackRoot && sentRoot !== null) this.store.setMeta(threadKey, sentRoot);
391
409
  this.store.setMeta(scopeKey(jobId, number), JSON.stringify(round));
392
410
  this.store.setMeta(pointer(laneId), scopeKey(jobId, number));
393
411
  this.store.setMeta(`topic-owner:${input.id}`, laneId);
394
412
  await options.place(round, !previous);
395
- return `PR #${number} 검토를 접수했습니다. 결과 확인: /cron pr-status ${jobId} ${number}`;
413
+ return `PR #${number} 검토를 접수했습니다. 결과 확인: ${command} pr-status ${jobId} ${number}`;
396
414
  }
397
415
  }
@@ -1,4 +1,4 @@
1
- import { routeKey, type InputRecord, type StorePort } from "../contracts";
1
+ import { routeKey, type InputRecord, type Route, type StorePort } from "../contracts";
2
2
 
3
3
  // Controller receipts have no platform message/interaction and are never owner
4
4
  // inputs. Only the restricted lane's exact native result has a delivery route.
@@ -6,6 +6,7 @@ export const intakeWorkPrefix = "pr-intake-work:";
6
6
  export const intakeWorkId = (job: string, number: number, revision: string, head: string) => `${intakeWorkPrefix}${job}:${number}:${revision}:${head}`;
7
7
  export const intakeThreadKey = (job: string, number: number) => `pr-intake-thread:${job}:${number}`;
8
8
  export const intakeStatusKey = (job: string, number: number) => `pr-intake-status:${job}:${number}`;
9
+ export const prCronCommand = (platform: Route["platform"]) => platform === "slack" ? "!cron" : "/cron";
9
10
  export function prThreadTitle(repository: string, number: number): string {
10
11
  const suffix = ` #${number}`;
11
12
  return repository.slice(0, 100 - suffix.length) + suffix; // Discord thread title limit; GitHub slugs are ASCII.
@@ -20,7 +21,7 @@ export function hasIntakeReplyRoute(store: StorePort, input: InputRecord, id: st
20
21
  const lane = input.target && input.target !== "main" ? store.lane(input.target) : null;
21
22
  const pointer = lane && store.getMeta(`pr-review-lane:${lane.id}`);
22
23
  const raw = pointer && store.getMeta(pointer);
23
- if (!raw || !lane || !source || source.messageId !== null || source.interactionId !== undefined
24
+ if (!raw || !lane || !source || source.messageId !== null || source.interactionId !== undefined || source.invocationId !== undefined
24
25
  || (source.state !== "pending" && source.state !== "done") || store.getMeta(`user-source:${id}`) !== null) return false;
25
26
  const round = JSON.parse(raw);
26
27
  return round.inputId === input.id && round.source === id && round.laneId === lane.id && !!round.automation
@@ -1,4 +1,25 @@
1
- import type { Platform } from "../contracts";
1
+ import { routeKey, type Inbound, type OutputRecord, type Platform, type StorePort } from "../contracts";
2
+
3
+ /** Last verified physical message of a Slack post; a file or an edit is not a new post. */
4
+ export function slackOutputTimestamp(store: Pick<StorePort, "getMeta">, output: OutputRecord): string | null {
5
+ const { platform, accountId, channelId } = output.route;
6
+ const timestamp = /^\d{1,20}\.\d{6}$/u;
7
+ const first = output.remoteId;
8
+ if (platform !== "slack" || output.state !== "sent" || output.editOf || !first || !timestamp.test(first)) return null;
9
+ const last = store.getMeta(`slack:output-last:${output.id}`);
10
+ if (last === null) return first;
11
+ const part = `slack:output-part:${JSON.stringify([accountId, channelId, last])}`;
12
+ return timestamp.test(last) && compareMessageIds("slack", last, first) === 1 && store.getMeta(part) === output.id ? last : null;
13
+ }
14
+
15
+ /** The actual post of this source's workspace question, never a different route or kind of receipt. */
16
+ export function slackWorkspaceQuestionTimestamp(store: Pick<StorePort, "getMeta" | "output">, source: Pick<Inbound, "id" | "route">): string | null {
17
+ if (source.route.platform !== "slack") return null;
18
+ const post = store.output(`${source.id}:workspace`);
19
+ if (!post || post.sourceId !== source.id || routeKey(post.route) !== routeKey(source.route)
20
+ || post.resultAttachment || post.status || post.picker || post.replyTo) return null;
21
+ return slackOutputTimestamp(store, post);
22
+ }
2
23
 
3
24
  /** Platform message order only; event/edit IDs and local arrival times are not clocks. */
4
25
  export function compareMessageIds(platform: Platform, left: string, right: string): -1 | 0 | 1 | null {
@@ -1,9 +1,23 @@
1
1
  import { realpathSync, statSync } from "node:fs";
2
2
  import { basename, isAbsolute } from "node:path";
3
3
  import type { Lane } from "../contracts";
4
+ import { decodeSlackMrkdwn } from "../messaging/messenger-commands";
4
5
 
5
6
  export const TOPIC_CHOICE_WAIT_MS = 5 * 60_000;
6
7
 
8
+ /** Slack has no reply reference to an individual message inside a thread. */
9
+ function slackTopicChoice(text: string): { readonly source: string; readonly answer: string } | null {
10
+ const match = /^!choose[ \t]+(\d{1,20}\.\d{6})[ \t]+(\S[^\r\n\u2028\u2029]*)$/u.exec(text.trim());
11
+ return match ? { source: match[1], answer: decodeSlackMrkdwn(match[2]) } : null;
12
+ }
13
+
14
+ /** Interpret only a physical Slack workspace header; preserve task bytes. */
15
+ export function slackWorkspacePlacement(text: string, routingText: string | null | undefined): string {
16
+ const written = routingText !== undefined && routingText !== null && /^cwd:/iu.test(routingText) ? routingText : text;
17
+ // Match the same leading whitespace that topicRequest trims.
18
+ return written.replace(/^\s*cwd:[^\n]*/iu, decodeSlackMrkdwn);
19
+ }
20
+
7
21
  /** Only owner text, never a quote, attachment path, or channel description. */
8
22
  export function topicRequest(text: string) {
9
23
  const request = text.replace(/^\s*\/new(?:\s+|$)/, "");
@@ -14,6 +28,22 @@ export function topicRequest(text: string) {
14
28
  return { text: request.trimStart().slice(header[0].length), cwd: quoted?.[2] ?? path };
15
29
  }
16
30
 
31
+ /** The only answer forms that an original Slack message can supply to a workspace question. */
32
+ export function slackWorkspaceAnswer(
33
+ text: string, routingText: string | null | undefined, verified: unknown,
34
+ ): { text: string; cwd: string | null; source: string | null } | null {
35
+ if (verified !== true) return null;
36
+ if (/^!choose(?:\s|$)/u.test(text.trim())) {
37
+ const explicit = slackTopicChoice(text);
38
+ return explicit ? { text: explicit.answer, cwd: null, source: explicit.source } : null;
39
+ }
40
+ if (/^\s*\/new(?:\s|$)/u.test(text)) return null;
41
+ const request = topicRequest(slackWorkspacePlacement(text, routingText));
42
+ if (request.cwd !== null) return request.text.trim() ? null : { cwd: request.cwd, text: "", source: null };
43
+ const answer = (routingText ?? decodeSlackMrkdwn(text)).trim();
44
+ return answer && !/[\r\n\u2028\u2029]/u.test(answer) ? { cwd: null, text: answer, source: null } : null;
45
+ }
46
+
17
47
  /** Parse only the original Discord owner request body. An empty result asks for a task. */
18
48
  export function discordThreadSplit(text: string): string | null {
19
49
  const line = text.trim();
@@ -48,7 +78,8 @@ export function editsTopicPlacement(before: string, after: string): boolean {
48
78
  export function existingWorkspace(path: string): string | null {
49
79
  if (!isAbsolute(path)) return null;
50
80
  try {
51
- const canonical = realpathSync(path);
81
+ // Resolve symlinks before '..', just as chdir and the worker's Git process do.
82
+ const canonical = realpathSync.native(path);
52
83
  return statSync(canonical).isDirectory() ? canonical : null;
53
84
  } catch (error) {
54
85
  if (!(error instanceof Error)) throw error;
@@ -56,6 +87,17 @@ export function existingWorkspace(path: string): string | null {
56
87
  }
57
88
  }
58
89
 
90
+ /** A Slack history question accepts a number, a unique workspace name or an existing absolute path. */
91
+ export function matchingSlackHistoryChoice<T extends { readonly cwd: string }>(
92
+ answer: string, cwdHeader: string | null, choices: readonly T[],
93
+ ): T | undefined {
94
+ if (cwdHeader === null && /^[1-9]\d*$/u.test(answer)) return choices[Number(answer) - 1];
95
+ const cwd = existingWorkspace(cwdHeader ?? answer);
96
+ const matches = choices.filter(ref => cwd !== null ? ref.cwd === cwd
97
+ : cwdHeader === null && basename(ref.cwd).toLowerCase() === answer.toLowerCase());
98
+ return matches.length === 1 ? matches[0] : undefined;
99
+ }
100
+
59
101
  /** Match names of placed workspaces, not substrings of paths, filenames or longer repo names. */
60
102
  export function namedWorkspaces(text: string, lanes: readonly Lane[], nameOnly = false): Set<string> {
61
103
  const matches = new Set<string>();
@@ -74,11 +116,12 @@ export function namedWorkspaces(text: string, lanes: readonly Lane[], nameOnly =
74
116
  }
75
117
 
76
118
  /** Choose a single existing directory; conflicting evidence or explicit exclusions need clarification. */
77
- export function inferredWorkspace(text: string, lanes: readonly Lane[], replied: string | null, threadWorkspace: string | null): string | null {
119
+ export function inferredWorkspace(text: string, lanes: readonly Lane[], replied: string | null, threadWorkspace: string | null) {
78
120
  if (/\b(?:not|avoid|except|instead of|rather than|other than)\b|n['’]t\b|말고|대신|제외|빼고|아니라|아닌|(?:쓰|사용하)지\s*마/iu.test(text)) return null;
79
121
  const candidates = namedWorkspaces(text, lanes);
80
122
  const lineEnd = text.indexOf("\n");
81
- const path = lineEnd > 0 ? existingWorkspace(text.slice(0, lineEnd).trim()) : null;
123
+ const requested = lineEnd > 0 ? text.slice(0, lineEnd).trim() : null;
124
+ const path = requested === null ? null : existingWorkspace(requested);
82
125
  if (path) candidates.add(path);
83
126
  if (replied) candidates.add(replied);
84
127
  if (!candidates.size && threadWorkspace) candidates.add(threadWorkspace);
@@ -86,5 +129,6 @@ export function inferredWorkspace(text: string, lanes: readonly Lane[], replied:
86
129
  for (const lane of lanes) candidates.add(lane.cwd);
87
130
  }
88
131
  const [selected] = candidates;
89
- return candidates.size === 1 && selected && existingWorkspace(selected) === selected ? selected : null;
132
+ return candidates.size === 1 && selected && existingWorkspace(selected) === selected
133
+ ? { cwd: selected, requested: selected === path ? requested ?? selected : selected } : null;
90
134
  }