omp-superagent 0.1.16 → 0.1.18

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 (47) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +119 -33
  4. package/docs/OPERATIONS.md +83 -23
  5. package/docs/design/execution.md +66 -17
  6. package/docs/design/messaging.md +134 -47
  7. package/docs/releases/0.1.17.md +10 -0
  8. package/docs/releases/0.1.18.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 +2 -2
  19. package/skills/head/references/routing.md +17 -6
  20. package/src/config/config.ts +15 -0
  21. package/src/contracts.ts +49 -4
  22. package/src/cron/cron-jobs.ts +135 -92
  23. package/src/cron/cron-pr-intake.ts +18 -11
  24. package/src/extension.ts +15 -5
  25. package/src/gateway/gateway-client.ts +3 -1
  26. package/src/lane/workflow.ts +12 -6
  27. package/src/managed-super-probe.ts +21 -15
  28. package/src/messaging/messenger-command-catalog.json +1 -1
  29. package/src/messaging/messenger-commands.ts +8 -3
  30. package/src/messaging/slack-context.ts +50 -0
  31. package/src/omp/superkit-skills.ts +15 -2
  32. package/src/pr/pr-intake-order.ts +62 -0
  33. package/src/pr/pr-intake-review.ts +49 -31
  34. package/src/pr/pr-intake-work.ts +3 -2
  35. package/src/routing/message-order.ts +22 -1
  36. package/src/routing/topic-request.ts +41 -0
  37. package/src/runtime/controller.ts +515 -191
  38. package/src/runtime/deferred-routing.ts +12 -4
  39. package/src/runtime/dm-timeline.ts +3 -3
  40. package/src/storage/deferred-routing.ts +25 -4
  41. package/src/storage/store.ts +389 -60
  42. package/src/worker/worker-checkout.ts +38 -4
  43. package/src/worker/worker-host.ts +114 -24
  44. package/src/worker/worker-ledger.ts +28 -9
  45. package/src/worker/worker-repository.ts +13 -0
  46. package/src/worker/worker-service.ts +74 -17
  47. package/src/worker/worker-wire.ts +3 -1
@@ -4,9 +4,10 @@ import { authorizeRoute, type Config } from "../config/config";
4
4
  import { routeKey, type Inbound, type InputRecord, type Route, type StorePort } from "../contracts";
5
5
  import { describePrIntake, normalizeIntakeRepository } from "./cron-pr-intake";
6
6
  import { describeCronSchedule, nextCronTime, parseCronSchedule, type CronSchedule } from "./cron-schedule";
7
- import { compareMessageIds } from "../routing/message-order";
8
- import { matchesWrittenCommand } from "../messaging/messenger-commands";
7
+ import { messengerCommandText } from "../messaging/messenger-commands";
9
8
  import { parsePrModeControl, prModeArgument, prModeEffects, type PrIntakeMode } from "../pr/pr-intake-mode";
9
+ import { afterPrMessage, prPhysicalEvent, prSentOrder, readPrStopOrder, samePrClock, type PrPhysicalEvent } from "../pr/pr-intake-order";
10
+ import { prCronCommand } from "../pr/pr-intake-work";
10
11
 
11
12
  const jobsKey = "cron:jobs";
12
13
  export const CRON_RUN_PREFIX = "cron-run:";
@@ -14,7 +15,7 @@ const shellDisabled = "Direct shell cron jobs are disabled. Use /cron add with a
14
15
  const manualPrEffects = "manual: discovery only; use the explicit owner commands for review, fix, or merge when the native checks allow";
15
16
  const approvalFallback = "Work above the selected mode still needs an explicit owner command and must pass the native checks.";
16
17
  const stalePrOrder = "This PR intake command predates a newer control. No PR intake settings were changed.";
17
- const unverifiedPrOrder = "PR intake control order could not be verified. Send /cron show JOB_ID and reply to its confirmed status with a new explicit command.";
18
+ const slackPrOriginal = "Slack PR controls require an original written message. Send !cron in the allowed channel or the specified thread; a slash invocation has no message timestamp.";
18
19
  const usage = [
19
20
  '/cron add "every 2h" Check the build', '/cron add "in 30m" Remind me',
20
21
  '/cron add "TZ=Asia/Seoul 0 9 * * 1-5" Summarize CI',
@@ -91,6 +92,10 @@ function reject(text: string): CronUpdate {
91
92
  return { text, state: "cancelled" };
92
93
  }
93
94
 
95
+ function unverifiedPrOrder(platform: Route["platform"]): CronUpdate {
96
+ return reject(`PR intake control order could not be verified. Send ${prCronCommand(platform)} show JOB_ID and reply to its confirmed status with a new explicit command.`);
97
+ }
98
+
94
99
  function jobMetadata(state: CronState, changed: CronJob, remove = false) {
95
100
  const next = state.jobs.filter(job => job.id !== changed.id);
96
101
  if (!remove) next.push(changed);
@@ -107,16 +112,8 @@ function prOrderKey(jobId: string): string { return `cron-pr:order:${jobId}`; }
107
112
 
108
113
  function prStatusKey(sourceId: string): string { return `cron-pr:status:${sourceId}`; }
109
114
 
110
- function isDiscordSnowflake(id: unknown): id is string {
111
- return typeof id === "string" && /^[1-9]\d{0,19}$/.test(id) && BigInt(id) <= (1n << 64n) - 1n;
112
- }
113
-
114
- function afterDiscordOrder(order: string, boundary: string | null): boolean {
115
- return isDiscordSnowflake(boundary) && compareMessageIds("discord", order, boundary) === 1;
116
- }
117
-
118
115
  function originalCronArgument(input: InputRecord): string | undefined {
119
- return /^\/cron\s+([\s\S]+)$/u.exec(input.text.trim())?.[1];
116
+ return /^\/cron\s+([\s\S]+)$/u.exec(messengerCommandText(input).trim())?.[1];
120
117
  }
121
118
 
122
119
  function prModeReceipt(job: CronPrJob, mode: PrIntakeMode): string {
@@ -184,36 +181,35 @@ export class CronJobs {
184
181
  && this.store.firstAdmittedMessage(input.route, input.messageId)?.id === input.id;
185
182
  }
186
183
 
187
- private discordOrder(input: InputRecord): string | null {
188
- if (input.route.platform !== "discord" || input.pickerSelection || input.invocationId !== undefined
189
- || this.store.getMeta(`user-source:${input.id}`) !== "true") return null;
190
- const id = input.messageId ?? input.interactionId;
191
- if (!isDiscordSnowflake(id)) return null;
192
- if (input.messageId === null) return input.id === `discord:${input.route.accountId}:interaction:${id}` ? id : null;
193
- return input.interactionId === undefined && this.originalMessage(input) ? id : null;
184
+ private sourceOrder(input: InputRecord): PrPhysicalEvent | null {
185
+ return this.store.getMeta(`user-source:${input.id}`) === "true" && this.originalMessage(input)
186
+ ? prPhysicalEvent(input) : null;
194
187
  }
195
188
 
196
189
  /** Keep the newest physical stop even if catch-up admits an older stop later. */
197
- prStopOrder(previousBoundary: string | null, newStop: InputRecord): string | null {
198
- const order = authorizeRoute(this.config, newStop.route) ? this.discordOrder(newStop) : null;
190
+ prStopOrder(previousBoundary: string | null, newStop: InputRecord): PrPhysicalEvent | null {
191
+ const order = authorizeRoute(this.config, newStop.route) ? this.sourceOrder(newStop) : null;
199
192
  if (order === null || previousBoundary === null) return order;
200
193
  const previous = this.stopOrder(previousBoundary);
201
- if (previous === null) return null; // An incomparable stop always requires causal recovery.
202
- return afterDiscordOrder(order, previous) ? order : previous;
194
+ if (previous === null || !samePrClock(order, previous)) return null;
195
+ return afterPrMessage(order.platform, order.timestamp, previous.timestamp) ? order : previous;
203
196
  }
204
197
 
205
- private stopOrder(boundary: string): string | null {
198
+ private stopOrder(boundary: string): PrPhysicalEvent | null {
206
199
  let receipt: unknown;
207
200
  try { receipt = JSON.parse(boundary); }
208
201
  catch (error) {
209
202
  if (error instanceof SyntaxError) return null;
210
203
  throw error;
211
204
  }
212
- if (!receipt || typeof receipt !== "object") return null;
213
- if ("prDiscordOrder" in receipt) return isDiscordSnowflake(receipt.prDiscordOrder) ? receipt.prDiscordOrder : null;
214
- if (!("inputId" in receipt) || typeof receipt.inputId !== "string") return null;
205
+ if (!receipt || typeof receipt !== "object" || !("inputId" in receipt) || typeof receipt.inputId !== "string") return null;
215
206
  const input = this.store.input(receipt.inputId);
216
- return input && authorizeRoute(this.config, input.route) ? this.discordOrder(input) : null;
207
+ return readPrStopOrder(receipt, input && authorizeRoute(this.config, input.route) ? this.sourceOrder(input) : null);
208
+ }
209
+
210
+ private stopMessage(boundary: string | null, order: PrPhysicalEvent): string | null {
211
+ const stop = boundary === null ? null : this.stopOrder(boundary);
212
+ return stop && samePrClock(stop, order) ? stop.timestamp : null;
217
213
  }
218
214
 
219
215
  private originalPrSource(input: InputRecord): boolean {
@@ -222,14 +218,10 @@ export class CronJobs {
222
218
  // A voice confirmation can have projected draft text in `text`. It is
223
219
  // not a physical owner instruction to open a lane or publish to GitHub.
224
220
  return stored !== null && (stored.state === "pending" || stored.state === "done")
225
- && matchesWrittenCommand(stored)
226
221
  && routeKey(stored.route) === routeKey(route) && stored.messageId === input.messageId
227
- && stored.interactionId === input.interactionId && !stored.pickerSelection
228
- && (stored.messageId === null ? stored.interactionId !== undefined
229
- : !stored.id.startsWith(`discord:${route.accountId}:${stored.messageId}:edit:`))
230
- && route.platform === "discord" && route.guildId !== null && route.topicId === undefined
231
- && this.store.getMeta(`user-source:${input.id}`) === "true"
232
- && authorizeRoute(this.config, route) && this.originalMessage(stored);
222
+ && stored.interactionId === input.interactionId && stored.invocationId === input.invocationId
223
+ && route.guildId !== null && route.topicId === undefined
224
+ && authorizeRoute(this.config, route) && this.sourceOrder(stored) !== null;
233
225
  }
234
226
 
235
227
  /** Metadata survives pause, removal and restarts; these receipts must never reach a model. */
@@ -248,9 +240,10 @@ export class CronJobs {
248
240
  return source ? { job, source } : null;
249
241
  }
250
242
 
251
- private prControlSource(inputId: string): InputRecord | null {
243
+ private prControlSource(inputId: string, allowSlackStatusReply = false): InputRecord | null {
252
244
  const source = this.store.input(inputId);
253
- return source?.target === "main" && source.route.threadId === null && source.attachments.length === 0
245
+ return source?.target === "main" && (source.route.threadId === null || allowSlackStatusReply && source.route.platform === "slack")
246
+ && source.attachments.length === 0
254
247
  && this.store.getMeta(`handoff-source:${inputId}`) === null
255
248
  && this.store.getMeta(`activity-source:${inputId}`) === null
256
249
  && this.originalPrSource(source) ? source : null;
@@ -260,11 +253,12 @@ export class CronJobs {
260
253
  const selection = job.prMode;
261
254
  if (!selection || typeof selection.sourceId !== "string"
262
255
  || this.store.getMeta(prModeKey(selection.sourceId)) !== prModeReceipt(job, selection.mode)) return null;
263
- const action = this.prControlSource(selection.sourceId);
264
- if (action?.state !== "done" || routeKey(action.route) !== routeKey(parent)) return null;
265
- const argument = prModeArgument(action.text);
256
+ const action = this.prControlSource(selection.sourceId, true);
257
+ if (action?.state !== "done" || routeKey({ ...action.route, threadId: null }) !== routeKey(parent)) return null;
258
+ if (action.route.threadId !== null && this.prStatusReply(action)?.[0] !== job.id) return null;
259
+ const argument = prModeArgument(messengerCommandText(action));
266
260
  if (!argument) {
267
- return selection.mode === "review" && originalPrAdd(action.text)?.repository === job.repository ? selection : null;
261
+ return selection.mode === "review" && originalPrAdd(messengerCommandText(action))?.repository === job.repository ? selection : null;
268
262
  }
269
263
  const command = parsePrModeControl(argument);
270
264
  return command && command.mode === selection.mode
@@ -279,13 +273,13 @@ export class CronJobs {
279
273
  // physical send order: old controllers settled controls in arrival order.
280
274
  const enrolled = job.epoch === job.sourceId ? this.prControlSource(job.sourceId) : null;
281
275
  const order = enrolled?.state === "done" && routeKey(enrolled.route) === routeKey(parent)
282
- && originalPrAdd(enrolled.text)?.repository === job.repository ? this.discordOrder(enrolled) : null;
276
+ && originalPrAdd(messengerCommandText(enrolled))?.repository === job.repository ? this.sourceOrder(enrolled)?.timestamp ?? null : null;
283
277
  const mode = this.savedPrMode(job, parent);
284
- const selection = mode && this.prControlSource(mode.sourceId);
278
+ const selection = mode && this.prControlSource(mode.sourceId, true);
285
279
  return {
286
280
  membership: job.removed ? null : order,
287
281
  control: job.removed || job.paused ? null : order,
288
- mode: selection ? this.discordOrder(selection) : null,
282
+ mode: selection ? this.sourceOrder(selection)?.timestamp ?? null : null,
289
283
  };
290
284
  }
291
285
 
@@ -294,13 +288,21 @@ export class CronJobs {
294
288
  this.store.getMeta(prOrderKey(job.id))]);
295
289
  }
296
290
 
297
- private repliesToPrStatus(input: InputRecord, job: CronPrJob, order: string): boolean {
298
- const replied = input.reply?.messageId;
299
- if (input.messageId === null || !isDiscordSnowflake(replied) || !afterDiscordOrder(order, replied)) return false;
300
- const output = this.store.sentOutputForMessage(input.route, replied);
301
- return output !== null && output.remoteId === replied && routeKey(output.route) === routeKey(input.route)
302
- && output.id === `${output.sourceId}:head-control`
303
- && this.store.getMeta(prStatusKey(output.sourceId)) === this.prStatusReceipt(job, this.store.getMeta("head:stop-boundary"));
291
+ private prStatusReply(input: InputRecord): readonly unknown[] | null {
292
+ const { platform } = input.route;
293
+ const replied = platform === "slack" ? input.route.threadId : input.reply?.messageId;
294
+ if (!replied || input.messageId === null) return null;
295
+ const parent = { ...input.route, threadId: null };
296
+ const output = this.store.sentOutputForMessage(parent, replied);
297
+ if (!output || output.remoteId !== replied || routeKey(output.route) !== routeKey(parent)
298
+ || output.id !== `${output.sourceId}:head-control` || !afterPrMessage(platform, input.messageId, prSentOrder(this.store, output))) return null;
299
+ const saved: unknown = JSON.parse(this.store.getMeta(prStatusKey(output.sourceId)) ?? "null");
300
+ return Array.isArray(saved) ? saved : null;
301
+ }
302
+
303
+ private repliesToPrStatus(input: InputRecord, job: CronPrJob): boolean {
304
+ const receipt = this.prStatusReply(input);
305
+ return receipt !== null && JSON.stringify(receipt) === this.prStatusReceipt(job, this.store.getMeta("head:stop-boundary"));
304
306
  }
305
307
 
306
308
  /** Read at admission and before each unattended effect; an older revision never regains authority. */
@@ -319,11 +321,23 @@ export class CronJobs {
319
321
  const active = this.activePrEnrollment(jobId);
320
322
  if (scope.threadId !== null || !parentMatches || !this.originalPrSource(input) || !active
321
323
  || routeKey(active.source.route) !== routeKey(scope)) {
322
- throw new CronPrScopeError("No active PR intake job with that ID in the authorized Discord parent.");
324
+ throw new CronPrScopeError(input.route.platform === "slack" && input.messageId === null
325
+ ? slackPrOriginal : "No active PR intake job with that ID in the authorized parent channel.");
323
326
  }
324
327
  return active.job;
325
328
  }
326
329
 
330
+ followsPrEpoch(input: InputRecord, job: CronPrJob): boolean {
331
+ // The settled add or effective resume opened this epoch. Later controls
332
+ // (including a resume of an already active job) can advance control order.
333
+ const source = this.prControlSource(job.epoch, true);
334
+ if (source?.state !== "done"
335
+ || routeKey({ ...source.route, threadId: null }) !== routeKey({ ...input.route, threadId: null })) return false;
336
+ const event = prPhysicalEvent(input);
337
+ const boundary = prPhysicalEvent(source);
338
+ return event !== null && boundary !== null && afterPrMessage(event.platform, event.timestamp, boundary.timestamp);
339
+ }
340
+
327
341
  pendingPrRun(input: InputRecord): PrEnrollment | null {
328
342
  if (!this.isPrIntakeRun(input) || this.store.getMeta(`user-source:${input.id}`) === "true") return null;
329
343
  const [jobId] = input.id.slice(CRON_RUN_PREFIX.length).split(":", 1);
@@ -332,7 +346,7 @@ export class CronJobs {
332
346
  return active && live?.state === "pending" && live.target === "main" && active.job.lastRunId === live.id
333
347
  && this.store.getMeta(prRunKey(live.id)) === prRunIdentity(active.job)
334
348
  && routeKey(live.route) === routeKey(active.source.route) && live.messageId === active.source.messageId
335
- && live.interactionId === active.source.interactionId ? active : null;
349
+ && live.interactionId === active.source.interactionId && live.invocationId === active.source.invocationId ? active : null;
336
350
  }
337
351
 
338
352
  create(input: InputRecord, request: CronCreate, now: number) {
@@ -383,12 +397,13 @@ export class CronJobs {
383
397
  }
384
398
 
385
399
  private addPrJob(input: InputRecord, tail: string, now: number): CronUpdate {
386
- const source = this.prControlSource(input.id);
400
+ const source = this.prControlSource(input.id, true);
387
401
  if (!source || routeKey(source.route) !== routeKey(input.route)) {
388
- return reject("PR intake requires a new authenticated owner command in a Discord guild parent channel.");
402
+ return reject(input.route.platform === "slack" && input.messageId === null
403
+ ? slackPrOriginal : "PR intake requires a new authenticated owner command in the registered parent channel.");
389
404
  }
390
405
  const request = prAddRequest(tail);
391
- const written = originalPrAdd(source.text);
406
+ const written = originalPrAdd(messengerCommandText(source));
392
407
  const schedule = request && parseCronSchedule(request.schedule, now);
393
408
  if (!request || !written || written.repository !== request.repository || written.schedule !== request.schedule
394
409
  || !schedule || schedule.kind === "once") {
@@ -404,20 +419,25 @@ export class CronJobs {
404
419
  return prior.fingerprint === fingerprint && enrollment?.id === prior.jobId ? { text: this.status(enrollment) }
405
420
  : reject("This owner request already registered a different cron job.");
406
421
  }
407
- const order = this.discordOrder(source);
408
- if (source.state !== "pending" || !order) return reject("PR intake requires an original Discord message or application command with a verifiable snowflake.");
422
+ const event = prPhysicalEvent(source);
423
+ if (source.state !== "pending" || !event) return reject("PR intake requires an original command with a verifiable send order.");
424
+ const { platform, timestamp: order } = event;
409
425
  const boundary = this.store.getMeta("head:stop-boundary");
410
- const stop = boundary === null ? null : this.stopOrder(boundary);
411
- if (stop !== null && !afterDiscordOrder(order, stop)) return reject(stalePrOrder);
426
+ const stop = this.stopMessage(boundary, event);
427
+ if (stop !== null && !afterPrMessage(platform, order, stop)) return reject(stalePrOrder);
428
+ const parent = { ...source.route, threadId: null };
412
429
  if (enrollment?.kind === "pr-intake") {
413
430
  const enrolledBy = this.source(enrollment);
414
- if (!enrolledBy || routeKey(enrolledBy.route) !== routeKey(source.route)) {
415
- return reject("This repository is already reserved by its original Discord parent.");
431
+ if (!enrolledBy || routeKey(enrolledBy.route) !== routeKey(parent)) {
432
+ return reject("This repository is already reserved by its original parent channel.");
416
433
  }
417
434
  if (!enrollment.removed) return reject(`This repository is already enrolled as ${enrollment.id}.`);
418
435
  const latest = this.prOrder(enrollment, enrolledBy.route).control;
419
- if (latest !== null && !afterDiscordOrder(order, latest)) return reject(stalePrOrder);
420
- if (latest === null && !this.repliesToPrStatus(source, enrollment, order)) return reject(unverifiedPrOrder);
436
+ if (latest !== null && !afterPrMessage(platform, order, latest)) return reject(stalePrOrder);
437
+ if ((latest === null || source.route.threadId !== null) && !this.repliesToPrStatus(source, enrollment))
438
+ return unverifiedPrOrder(platform);
439
+ } else if (source.route.threadId !== null) {
440
+ return reject("Enroll a new PR intake job in the allowed parent channel, not inside a thread.");
421
441
  }
422
442
  // A removed enrollment is a tombstone: its original route, job identity and
423
443
  // prior per-PR receipts must not be reassigned by a fresh /cron pr-add.
@@ -429,36 +449,41 @@ export class CronJobs {
429
449
  };
430
450
  const next = { ...state, registrations: { ...state.registrations, [sourceKey]: { jobId: job.id, fingerprint } } };
431
451
  const orderReceipt: PrOrder = { membership: order, control: order, mode: order };
452
+ const command = prCronCommand(platform);
432
453
  const held = boundary !== null && job.stopBoundary !== boundary
433
- ? `\nTo reopen this job after the HEAD stop, send /cron show ${job.id} and reply to its confirmed status with /cron resume ${job.id}.`
454
+ ? `\nTo reopen this job after the HEAD stop, send ${command} show ${job.id} and reply to its confirmed status with ${command} resume ${job.id}.`
434
455
  : "";
435
456
  return { text: `${enrollment ? "Re-enrolled" : "Enrolled"} PR intake. ${this.status(job, "review")}${held}`,
436
457
  metadata: { ...jobMetadata(next, job), [prModeKey(input.id)]: prModeReceipt(job, "review"), [prOrderKey(job.id)]: JSON.stringify(orderReceipt) } };
437
458
  }
438
459
 
439
460
  private setPrMode(input: InputRecord, argument: string): CronUpdate {
440
- const source = this.prControlSource(input.id);
461
+ const source = this.prControlSource(input.id, true);
441
462
  if (source?.state !== "pending" || routeKey(source.route) !== routeKey(input.route)) {
442
- return reject("Changing PR intake mode requires a new authenticated owner command in its Discord guild parent channel.");
463
+ return reject(input.route.platform === "slack" && input.messageId === null
464
+ ? slackPrOriginal : "Changing PR intake mode requires a new authenticated owner command in its parent channel.");
443
465
  }
444
466
  const command = parsePrModeControl(argument);
445
- const original = prModeArgument(source.text);
467
+ const original = prModeArgument(messengerCommandText(source));
446
468
  const written = original && parsePrModeControl(original);
447
469
  if (!command || !written || command.mode !== written.mode || command.target !== written.target) {
448
470
  return reject("Use a direct /cron pr-mode JOB_OR_OWNER/REPO review|fix|merge command.");
449
471
  }
450
- const order = this.discordOrder(source);
451
- if (!order) return reject("PR intake mode requires an original Discord message or application command with a verifiable snowflake.");
472
+ const event = prPhysicalEvent(source);
473
+ if (!event) return reject("PR intake mode requires an original command with a verifiable send order.");
474
+ const { platform, timestamp: order } = event;
452
475
  const state = this.state();
453
- const parent = routeKey(source.route);
476
+ const parentRoute = { ...source.route, threadId: null };
477
+ const parent = routeKey(parentRoute);
478
+ if (source.route.threadId !== null && command.target === null) return unverifiedPrOrder(platform);
454
479
  // All membership changes survive on their row, including removed jobs.
455
480
  // Taking the maximum through strict comparisons prevents catch-up inputs
456
481
  // from resolving against a different set than was known at their send.
457
482
  if (command.target === null && state.jobs.some(job => {
458
483
  if (job.kind !== "pr-intake") return false;
459
484
  const enrollment = this.store.input(job.sourceId);
460
- return !enrollment || routeKey(enrollment.route) === parent && !afterDiscordOrder(order, this.prOrder(job, source.route).membership);
461
- })) return reject("This targetless PR intake command cannot be ordered after the Discord parent's enrollment changes. Send a new command naming its job ID or OWNER/REPO.");
485
+ return !enrollment || routeKey(enrollment.route) === parent && !afterPrMessage(platform, order, this.prOrder(job, parentRoute).membership);
486
+ })) return reject("This targetless PR intake command cannot be ordered after the parent channel's enrollment changes. Send a new command naming its job ID or OWNER/REPO.");
462
487
  const matches = state.jobs.filter(job => {
463
488
  if (job.kind !== "pr-intake" || job.removed
464
489
  || command.target !== null && command.target !== job.id && command.target !== job.repository) return false;
@@ -467,17 +492,17 @@ export class CronJobs {
467
492
  });
468
493
  const [job] = matches;
469
494
  if (job?.kind !== "pr-intake" || matches.length !== 1) {
470
- return reject("No unique enrolled PR intake job matches this Discord parent. Specify its job ID or OWNER/REPO.");
495
+ return reject("No unique PR intake job in this parent channel. Specify its job ID or OWNER/REPO.");
471
496
  }
472
- const latest = this.prOrder(job, source.route);
497
+ const latest = this.prOrder(job, parentRoute);
473
498
  const boundary = this.store.getMeta("head:stop-boundary");
474
- const stop = boundary !== job.stopBoundary && boundary !== null ? this.stopOrder(boundary) : null;
475
- if ([latest.control, latest.mode, stop].some(previous => previous !== null && !afterDiscordOrder(order, previous))) {
499
+ const stop = boundary !== job.stopBoundary ? this.stopMessage(boundary, event) : null;
500
+ if ([latest.control, latest.mode, stop].some(previous => previous !== null && !afterPrMessage(platform, order, previous))) {
476
501
  return reject(stalePrOrder);
477
502
  }
478
503
  const needsProof = latest.control === null || job.prMode !== undefined && latest.mode === null
479
504
  || boundary !== job.stopBoundary && stop === null;
480
- if (needsProof && !this.repliesToPrStatus(source, job, order)) return reject(unverifiedPrOrder);
505
+ if ((needsProof || source.route.threadId !== null) && !this.repliesToPrStatus(source, job)) return unverifiedPrOrder(platform);
481
506
  const next = { ...job, prMode: { mode: command.mode, sourceId: source.id } };
482
507
  const orderReceipt: PrOrder = { membership: latest.membership ?? (needsProof ? order : null),
483
508
  control: latest.control ?? order, mode: order };
@@ -490,9 +515,14 @@ export class CronJobs {
490
515
  const [, action = "", tail = ""] = /^(\S+)(?:\s+([\s\S]*))?$/.exec(argument) ?? [];
491
516
  if (!action || action === "help" && !tail) return { text: usage };
492
517
  const state = this.state();
518
+ const slackRecovery = input.route.platform === "slack" && input.route.threadId !== null
519
+ && ["pause", "resume", "remove", "delete"].includes(action);
520
+ const parent = routeKey({ ...input.route, threadId: null });
493
521
  const scoped = state.jobs.flatMap(job => {
494
522
  const source = this.source(job);
495
- return source && routeKey(source.route) === routeKey(input.route) ? [{ job, source }] : [];
523
+ return source && (routeKey(source.route) === routeKey(input.route)
524
+ || slackRecovery && job.kind === "pr-intake" && routeKey(source.route) === parent && this.repliesToPrStatus(input, job))
525
+ ? [{ job, source }] : [];
496
526
  });
497
527
  if (action === "list" && !tail) {
498
528
  const current = scoped.filter(({ job }) => job.kind !== "pr-intake" || !job.removed);
@@ -507,15 +537,17 @@ export class CronJobs {
507
537
  if (details && (number === null || !Number.isSafeInteger(number))) return reject(usage);
508
538
  const summary = `${this.status(job)}\n\n${describePrIntake(this.store, job, number)}`;
509
539
  const source = this.prControlSource(input.id);
510
- if (number !== null || source?.state !== "pending" || !this.discordOrder(source)
540
+ const event = source && prPhysicalEvent(source);
541
+ if (number !== null || source?.state !== "pending" || !event
511
542
  || routeKey(source.route) !== routeKey(found.source.route)
512
543
  || originalCronArgument(source)?.split(/\s+/u).join(" ") !== `show ${job.id}`) return { text: summary };
513
544
  const boundary = this.store.getMeta("head:stop-boundary");
514
545
  const latest = this.prOrder(job, source.route);
515
- const stopUnordered = boundary !== null && job.stopBoundary !== boundary && this.stopOrder(boundary) === null;
546
+ const stopUnordered = boundary !== null && job.stopBoundary !== boundary && this.stopMessage(boundary, event) === null;
516
547
  if (!stopUnordered && latest.control !== null && (!job.prMode || latest.mode !== null)) return { text: summary };
517
- const next = job.removed ? "the explicit /cron pr-add command for this repository"
518
- : `/cron resume ${job.id} to reopen it, or another explicit control naming this job`;
548
+ const command = prCronCommand(event.platform);
549
+ const next = job.removed ? `the explicit ${command} pr-add command for this repository`
550
+ : `${command} resume ${job.id} to reopen it, or another explicit control naming this job`;
519
551
  return { text: `To prove this is a new control, reply directly to this status with ${next}.\n\n${summary}`,
520
552
  metadata: { [prStatusKey(source.id)]: this.prStatusReceipt(job, boundary) } };
521
553
  }
@@ -549,24 +581,35 @@ export class CronJobs {
549
581
  if (!found) return reject("No cron job with that ID in this conversation.");
550
582
  const { job, source } = found;
551
583
  if (job.kind === "pr-intake" && (job.removed || !this.originalPrSource(input))) {
552
- return reject("No enrolled PR intake job with that ID in this Discord parent.");
584
+ return reject(input.route.platform === "slack" && input.messageId === null
585
+ ? slackPrOriginal : "No enrolled PR intake job with that ID in this parent channel.");
586
+ }
587
+ if (job.kind === "pr-intake" && action === "run" && input.route.platform === "slack") {
588
+ const runSource = this.prControlSource(input.id);
589
+ if (runSource?.state !== "pending" || originalCronArgument(runSource)?.split(/\s+/u).join(" ") !== `run ${job.id}`)
590
+ return reject("Running PR intake requires the exact original command in its parent channel.");
591
+ const event = prPhysicalEvent(runSource);
592
+ const latest = this.prOrder(job, source.route);
593
+ if (!event || !afterPrMessage("slack", event.timestamp, latest.control)
594
+ || latest.mode !== null && !afterPrMessage("slack", event.timestamp, latest.mode)) return reject(stalePrOrder);
553
595
  }
554
596
  let orderMetadata: Readonly<Record<string, string>> = {};
555
597
  if (job.kind === "pr-intake" && action !== "run" && action !== "show") {
556
- const prControl = this.prControlSource(input.id);
557
- const order = prControl && this.discordOrder(prControl);
558
- if (!order || prControl?.state !== "pending"
598
+ const prControl = this.prControlSource(input.id, slackRecovery);
599
+ const event = prControl && prPhysicalEvent(prControl);
600
+ if (prControl?.state !== "pending" || !event
559
601
  || originalCronArgument(prControl)?.split(/\s+/u).join(" ") !== `${action} ${job.id}`) {
560
- return reject("PR intake changes require the exact original Discord command with a verifiable snowflake.");
602
+ return reject("PR intake changes require the exact original command with a verifiable send order.");
561
603
  }
604
+ const { platform, timestamp: order } = event;
562
605
  const latest = this.prOrder(job, source.route);
563
606
  const heldByStop = action === "resume" && job.stopBoundary !== boundary;
564
- const stop = heldByStop && boundary !== null ? this.stopOrder(boundary) : null;
565
- if ([latest.control, stop].some(previous => previous !== null && !afterDiscordOrder(order, previous))) {
607
+ const stop = heldByStop ? this.stopMessage(boundary, event) : null;
608
+ if ([latest.control, stop].some(previous => previous !== null && !afterPrMessage(platform, order, previous))) {
566
609
  return reject(stalePrOrder);
567
610
  }
568
- if ((latest.control === null || heldByStop && stop === null) && !this.repliesToPrStatus(prControl, job, order)) {
569
- return reject(unverifiedPrOrder);
611
+ if ((latest.control === null || heldByStop && stop === null) && !this.repliesToPrStatus(prControl, job)) {
612
+ return unverifiedPrOrder(platform);
570
613
  }
571
614
  const membership = action === "remove" || action === "delete" ? order : latest.membership ?? order;
572
615
  orderMetadata = { [prOrderKey(job.id)]: JSON.stringify({ ...latest, control: order, membership }) };
@@ -1,10 +1,10 @@
1
1
  import { Type, type Static } from "@sinclair/typebox/type";
2
2
  import { Value } from "@sinclair/typebox/value";
3
- import { routeKey, type InputRecord, type OutputRecord, type StorePort } from "../contracts";
3
+ import { routeKey, type InputRecord, type OutputRecord, type Route, type StorePort } from "../contracts";
4
4
  import type { CronJobs, CronPrJob } from "./cron-jobs";
5
5
  import { parsePrRef } from "../pr/pr-github";
6
6
  import { PrReadError } from "../pr/pr-github-schema";
7
- import { intakeStatusKey } from "../pr/pr-intake-work";
7
+ import { intakeStatusKey, prCronCommand } from "../pr/pr-intake-work";
8
8
 
9
9
  const offerPrefix = "cron-pr:offer:";
10
10
  const githubId = Type.Readonly(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }));
@@ -75,17 +75,24 @@ function sameIdentity(left: RepositoryIdentity, right: RepositoryIdentity): bool
75
75
  return left.repositoryId === right.repositoryId && left.ownerId === right.ownerId;
76
76
  }
77
77
 
78
- function action(candidate: CronPrCandidate): string {
79
- return `/cron pr-review ${candidate.jobId} ${candidate.number} ${candidate.head}`;
78
+ function action(candidate: CronPrCandidate, command: string): string {
79
+ return `${command} pr-review ${candidate.jobId} ${candidate.number} ${candidate.head}`;
80
80
  }
81
81
 
82
- function offerText(repository: string, candidate: CronPrCandidate): string {
83
- if (candidate.policyRevision) return `${repository}#${candidate.number} — 새 외부 PR (${candidate.head}). 등록한 단계에 따라 이 메시지에 전용 검토 스레드를 엽니다. 상태: /cron show ${candidate.jobId} ${candidate.number}\n수동 검토:\n${action(candidate)}`;
82
+ function offerText(repository: string, candidate: CronPrCandidate, platform: Route["platform"]): string {
83
+ const command = prCronCommand(platform);
84
+ if (platform === "slack") {
85
+ return `${repository}#${candidate.number} — 새 외부 PR (${candidate.head}). `
86
+ + (candidate.policyRevision ? "등록한 단계에 따라 이 메시지의 스레드에서 검토합니다. " : "")
87
+ + `상태: ${command} show ${candidate.jobId} ${candidate.number}\n이 메시지의 스레드에서 수동 검토:\n${action(candidate, command)}`;
88
+ }
89
+ if (candidate.policyRevision) return `${repository}#${candidate.number} — 새 외부 PR (${candidate.head}). 등록한 단계에 따라 이 메시지에 전용 검토 스레드를 엽니다. 상태: /cron show ${candidate.jobId} ${candidate.number}\n수동 검토:\n${action(candidate, command)}`;
84
90
  return `New external pull request: ${repository}#${candidate.number}. `
85
- + `The following owner command starts a read-only review; it does not merge or change the pull request.\n\n${action(candidate)}`;
91
+ + `The following owner command starts a read-only review; it does not merge or change the pull request.\n\n${action(candidate, command)}`;
86
92
  }
87
93
 
88
94
  export function describePrIntake(store: StorePort, job: CronPrJob, number: number | null): string {
95
+ const command = prCronCommand(store.input(job.sourceId)?.route.platform ?? "discord");
89
96
  const newest = ledger(store, job.repository)?.candidates.filter(candidate => candidate.jobId === job.id).reverse() ?? [];
90
97
  const summary = job.lastRunId ? store.getMeta(outcomeKey(job.lastRunId)) : null;
91
98
  const selected = number === null ? newest.slice(0, 10) : newest.filter(candidate => candidate.number === number);
@@ -96,12 +103,12 @@ export function describePrIntake(store: StorePort, job: CronPrJob, number: numbe
96
103
  : candidate.epoch === job.epoch && open
97
104
  ? "deferred; up to one offer per scan" : "deferred offer suppressed; manual review only";
98
105
  const progress = store.getMeta(intakeStatusKey(job.id, candidate.number));
99
- return `${action(candidate)} (${status})${progress ? ` — ${progress}` : ""}`;
106
+ return `${action(candidate, command)} (${status})${progress ? ` — ${progress}` : ""}`;
100
107
  });
101
108
  return [
102
109
  summary,
103
110
  lines.length ? `Recorded PR offers:\n${lines.join("\n")}` : "No matching PR offers recorded.",
104
- number === null && newest.length > selected.length ? `Showing the latest ${selected.length} of ${newest.length}; use /cron show ${job.id} PR_NUMBER for an older offer.` : null,
111
+ number === null && newest.length > selected.length ? `Showing the latest ${selected.length} of ${newest.length}; use ${command} show ${job.id} PR_NUMBER for an older offer.` : null,
105
112
  ].filter(Boolean).join("\n");
106
113
  }
107
114
 
@@ -139,7 +146,7 @@ export class CronPrIntake {
139
146
  const active = this.jobs.activePrEnrollment(candidate.jobId);
140
147
  return active !== null && active.job.repository === repository && candidate.epoch === active.job.epoch
141
148
  && output.sourceId === active.source.id && routeKey(output.route) === routeKey(active.source.route)
142
- && output.text === offerText(repository, candidate);
149
+ && output.text === offerText(repository, candidate, active.source.route.platform);
143
150
  }
144
151
 
145
152
  async consume(input: InputRecord, signal: AbortSignal): Promise<IntakeScan | undefined> {
@@ -223,7 +230,7 @@ export class CronPrIntake {
223
230
  try {
224
231
  this.store.queueOutput({
225
232
  id: chosen.outputId, sourceId: current.source.id, route: current.source.route,
226
- text: offerText(current.job.repository, chosen),
233
+ text: offerText(current.job.repository, chosen, current.source.route.platform),
227
234
  });
228
235
  } catch (error) {
229
236
  this.finish(input.id, "The PR offer was claimed but outbox creation was interrupted; inspect the recorded status.", "cancelled");
package/src/extension.ts CHANGED
@@ -20,6 +20,7 @@ import type { PrWatchCommand } from "./pr/pr-watch";
20
20
  import type { LaneWatchCommand } from "./lane/lane-watch";
21
21
  import { registerDecisionAsk } from "./lane/decision-tool";
22
22
  import { registerResultAttach, RESULT_ATTACH_TOOL } from "./messaging/result-attachment";
23
+ import { registerSlackContext } from "./messaging/slack-context";
23
24
  import { HEAD_ROTATION_GUARD, HEAD_ROTATION_PROBE, HEAD_SLEEP_PROBE_READY, type HeadSleepProbeReadyEvent,
24
25
  type RotationGuardEvent, type RotationProbeEvent } from "./runtime/head-rotation";
25
26
  import { readHeadQuota } from "./runtime/head-quota";
@@ -70,6 +71,7 @@ const managerTools: Record<string, true> = {
70
71
  thread_inspect: true, lane_thread_update: true,
71
72
  messenger_presence: true,
72
73
  discord_context: true, discord_purpose_list: true, discord_purpose_set: true, discord_purpose_clear: true,
74
+ slack_context: true, slack_purpose_list: true, slack_purpose_set: true, slack_purpose_clear: true,
73
75
  pr_watch: true, pr_watch_list: true,
74
76
  decision_list: true, decision_inspect: true, decision_withdraw: true,
75
77
  [RESULT_ATTACH_TOOL]: true,
@@ -195,6 +197,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
195
197
  if (ctx.agent.kind === "main" && runtime?.laneRecoveryActive() && Object.hasOwn(managerTools, event.toolName)) {
196
198
  switch (event.toolName) {
197
199
  case "lane_models": case "lane_inspect": case "thread_inspect": case "discord_context": case "discord_purpose_list":
200
+ case "slack_context": case "slack_purpose_list":
198
201
  case "decision_list": case "decision_inspect": case "pr_watch_list":
199
202
  // The runtime validates their exact report source, target and current authority.
200
203
  case "lane_message": case "lane_set_model":
@@ -381,7 +384,13 @@ export default function superagentExtension(pi: ExtensionAPI): void {
381
384
  appliedTags: Type.Optional(threadTagsSchema),
382
385
  destination: Type.Optional(laneRouteSchema),
383
386
  }),
384
- async execute(_id, params, _signal, _onUpdate, ctx) { return result(await requireRuntime(ctx).startLane(params)); },
387
+ async execute(_id, params, _signal, _onUpdate, ctx) {
388
+ const controller = requireRuntime(ctx);
389
+ const lane = await controller.startLane(params);
390
+ const kickoff = controller.store.output(`${params.sourceId}:kickoff`);
391
+ return result(kickoff && kickoff.state !== "sent"
392
+ ? { ...lane, kickoff: { outputId: kickoff.id, state: kickoff.state } } : lane);
393
+ },
385
394
  });
386
395
  pi.registerTool({
387
396
  name: "pr_watch_list", label: "Inspect tracked pull requests", approval: "read",
@@ -416,8 +425,8 @@ export default function superagentExtension(pi: ExtensionAPI): void {
416
425
  },
417
426
  });
418
427
  pi.registerTool({
419
- name: "thread_inspect", label: "Inspect Discord forum or thread", approval: "read",
420
- description: "Read the original user source's Discord guild channel/thread, an explicitly selected managed lane's thread, or an eligible alternate guild parent (destination with threadId:null and no topicId, instead of laneId). Returns available tag IDs, required-tag policy, applied tags, title and archive state. Use before selecting appliedTags for lane_start. This never creates a topic, changes lane state, or reads message history.",
428
+ name: "thread_inspect", label: "Inspect messenger thread", approval: "read",
429
+ description: "Read the original authorized Discord guild channel/thread or Slack thread, or an explicitly selected managed lane's thread. For Discord an eligible alternate guild parent may be selected instead via destination (threadId:null, no topicId). Discord returns tag policy, title and archive state; Slack verifies the exact root and whether the bot's managed starter label is editable. Slack has no native thread archive status or forum tags. This never creates a topic, changes lane state, or reads a conversation transcript.",
421
430
  parameters: Type.Object({
422
431
  sourceId: Type.String({ minLength: 1 }), laneId: Type.Optional(Type.String({ minLength: 1 })),
423
432
  destination: Type.Optional(laneRouteSchema),
@@ -427,8 +436,8 @@ export default function superagentExtension(pi: ExtensionAPI): void {
427
436
  },
428
437
  });
429
438
  pi.registerTool({
430
- name: "lane_thread_update", label: "Manage a lane's Discord thread", approval: "exec",
431
- description: "Explicitly rename, retag, archive or reopen a managed lane's Discord thread under an original user sourceId. Requires Discord ManageThreads. appliedTags replaces the full set using observed exact IDs; omit to preserve or [] to clear if allowed. Omitted fields stay unchanged. Archiving never closes/pauses a lane; reopening never resumes it. Source-bound receipts suppress repeated mutations; uncertain edits require inspection and a new explicit user request, never blind retry. A returned replay receipt is historical, not a fresh inspection.",
439
+ name: "lane_thread_update", label: "Manage a lane's messenger thread", approval: "exec",
440
+ description: "Explicitly change a managed lane's thread under an original user sourceId. On Slack, only title is supported and only when the bot created the managed starter message; do not edit the user's root, or simulate tags, archive or reopen. On Discord, ManageThreads permits title, tag and archive changes; appliedTags replaces the full set using observed IDs. Omitted fields stay unchanged. Archiving never pauses a lane; reopening never resumes it. A repeated source returns its historical receipt without reapplying edits. After an uncertain response, inspect and use a new explicit user request rather than retrying.",
432
441
  parameters: Type.Object({
433
442
  id: Type.String({ minLength: 1 }), sourceId: Type.String({ minLength: 1 }),
434
443
  changes: Type.Union([
@@ -479,6 +488,7 @@ export default function superagentExtension(pi: ExtensionAPI): void {
479
488
  return result(await requireRuntime(ctx).discordPurpose({ ...params, action: "clear" }));
480
489
  },
481
490
  });
491
+ registerSlackContext(pi, requireRuntime);
482
492
  pi.registerTool({
483
493
  name: "lane_set_model", label: "Change an idle lane model", approval: "exec",
484
494
  description: "Explicitly change one idle lane's model or full native preset snapshot without changing global OMP settings, the head, or other lanes. Requires a received authorized sourceId, exactly one model/preset and modelReason. Refuses active work, approvals/services/goals or unresolved submissions. Uses durable intent and native readback; do not blindly repeat an uncertain change.",
@@ -10,7 +10,7 @@ import {
10
10
  } from "./gateway-protocol";
11
11
  import type { GatewayReceipt, QueuedEvent } from "./gateway-wire";
12
12
  import type { GroupReply } from "../group/group-policy";
13
- import type { DiscordPresenceStatus, MessengerPresenceRequest } from "../contracts";
13
+ import type { DiscordPresenceStatus, MessengerPresenceRequest, SlackContext, SlackContextRequest, SlackPurposeNote, SlackPurposeRequest } from "../contracts";
14
14
 
15
15
  export interface GatewayHeadMessenger extends Messenger {
16
16
  assertRoute(route: Route, purpose?: "history" | "bound-work"): Promise<void>;
@@ -246,6 +246,8 @@ class GatewayMessenger implements GatewayHeadMessenger {
246
246
  return this.effect("messengerPresence", [request]);
247
247
  }
248
248
  discordPurpose(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]> { return this.effect("discordPurpose", [request]); }
249
+ inspectSlackContext(request: SlackContextRequest): Promise<SlackContext> { return this.effect("inspectSlackContext", [request]); }
250
+ slackPurpose(request: SlackPurposeRequest): Promise<readonly SlackPurposeNote[]> { return this.effect("slackPurpose", [request]); }
249
251
  fetchAfter(route: Route, messageId: string, historySequence?: number): Promise<Inbound[] | null> {
250
252
  return this.effect("fetchAfter", historySequence === undefined ? [route, messageId] : [route, messageId, historySequence]);
251
253
  }