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
package/src/contracts.ts CHANGED
@@ -110,6 +110,31 @@ export type DiscordPurposeRequest = {
110
110
  );
111
111
  export interface DiscordPurposeNote { readonly route: Route; readonly purpose: string }
112
112
 
113
+ /** Current verified Slack conversation observations, never instructions, authority or routing policy. */
114
+ export interface SlackContext {
115
+ readonly kind: "workspace" | "dm";
116
+ readonly channel: {
117
+ readonly id: string;
118
+ readonly name?: string;
119
+ readonly topic?: string | null;
120
+ /** Native Slack channel purpose, observed but not editable here. */
121
+ readonly slackPurpose?: string | null;
122
+ /** Owner's local Superagent note, not Slack metadata. */
123
+ readonly purpose?: string;
124
+ };
125
+ readonly thread?: { readonly id: string; readonly parentId: string; readonly purpose?: string };
126
+ }
127
+
128
+ export interface SlackContextRequest {
129
+ readonly sourceId: string;
130
+ readonly route: Route;
131
+ }
132
+ export type SlackPurposeRequest = SlackContextRequest & (
133
+ | { readonly action: "list" | "clear" }
134
+ | { readonly action: "set"; readonly purpose: string }
135
+ );
136
+ export interface SlackPurposeNote { readonly route: Route; readonly purpose: string }
137
+
113
138
  export type PresenceAction = "start" | "status" | "stop";
114
139
  export interface MessengerPresenceRequest {
115
140
  readonly action: PresenceAction;
@@ -150,10 +175,14 @@ export interface Inbound {
150
175
  readonly discordOriginalText?: string;
151
176
  /** Adapter-verified routing-only view; an empty string excludes the entire message. */
152
177
  readonly routingText?: string;
178
+ /** The Slack adapter proved that this message's routing body is plain owner text. */
179
+ readonly slackVerifiedRoutingBody?: true;
153
180
  /** Telegram's authenticated formatting verdict; absent on pre-upgrade receipts. */
154
181
  readonly telegramProtectedCommand?: boolean;
155
182
  /** Original Telegram text or caption when an addressed bot suffix was removed. */
156
183
  readonly telegramOriginalText?: string;
184
+ /** UTF-16 end of the adapter-attested owner-written prefix (after Slack entity decoding). */
185
+ readonly ownerWrittenPrefix?: number;
157
186
  receivedAt: number;
158
187
  attachments: Attachment[];
159
188
  reply?: ReplyContext;
@@ -210,6 +239,17 @@ export interface LaneObservation {
210
239
  lastEvidence: (LaneEvidence & { at: number }) | null;
211
240
  waiting: { target: LaneWaitTarget; since: number } | null;
212
241
  }
242
+ /** Observed on the verified local stdio connection, never a remote process lookup. */
243
+ export interface LocalHostIdentity {
244
+ readonly pid: number;
245
+ readonly ownerPid: number;
246
+ readonly sessionId: string;
247
+ readonly sessionFile: string;
248
+ readonly dev: number;
249
+ readonly ino: number;
250
+ readonly ctimeMs: number;
251
+ }
252
+
213
253
  export interface Lane {
214
254
  id: string;
215
255
  title: string;
@@ -233,6 +273,7 @@ export interface Lane {
233
273
  socketPath: string;
234
274
  generation: number;
235
275
  pid: number | null;
276
+ localOwner?: LocalHostIdentity & { readonly journalHeld?: true };
236
277
  createdAt: number;
237
278
  lastActivityAt: number;
238
279
  result: string | null;
@@ -306,7 +347,7 @@ export interface OutputRecord {
306
347
  sourceId: string;
307
348
  route: Route;
308
349
  /** Durable original owner message, only in the same physical conversation. */
309
- replyTo?: MessageReference & { readonly requireExisting?: true };
350
+ replyTo?: MessageReference & { readonly requireExisting?: true; readonly joinedAnswerId?: string };
310
351
  /** Discord status message replaced in place; fixed when the output is claimed. */
311
352
  readonly editOf?: MessageReference;
312
353
  /** Initial Discord status message; overflow falls back to one attachment instead of multi-message split. */
@@ -320,8 +361,8 @@ export interface OutputRecord {
320
361
  }
321
362
 
322
363
  export type SettlementOutput = Pick<OutputRecord, "id" | "text" | "picker"> & {
323
- /** Physically distinct Discord HEAD steers proved to precede this shared answer. */
324
- readonly discordHeadFollowups?: readonly string[];
364
+ /** Physically distinct HEAD steers proved to precede this shared answer. */
365
+ readonly headFollowups?: readonly string[];
325
366
  /** Controller-only lane failure routing, never derived from output text. */
326
367
  readonly laneFailure?: "quota" | "recover";
327
368
  };
@@ -427,6 +468,8 @@ export interface StorePort {
427
468
  laneReplyRoute(input: InputRecord, source: InputRecord): Route;
428
469
  /** Exact original owner and authorized delivery route for a topic-owned lane input. */
429
470
  topicDelivery(id: string): { readonly source: InputRecord; readonly route: Route; readonly outputSourceId: string } | null;
471
+ /** Original file recipient or its exact confirmed child for a remote admission; text routing does not grant file consent. */
472
+ resultAttachmentDelivery(id: string): ReturnType<StorePort["topicDelivery"]>;
430
473
  /** Whether an unowned dialog could belong to a durable topic admission on this native generation. */
431
474
  hasTopicAdmission(target: string, generation: number): boolean;
432
475
  /** A timely owner choice or stop on the original route is durably admitted by Gateway and still awaiting its head receipt. */
@@ -468,6 +511,7 @@ export interface StorePort {
468
511
  | { readonly kind: "sources"; readonly sources: readonly InputRecord[] }
469
512
  | { readonly kind: "unverified" | "unknown" };
470
513
  isDiscordWorkspaceQuestion(route: Route, messageId: string): boolean;
514
+ hasSlackHistoryChoice(route: Route, number: number, authoredAt: number, excludeSourceId?: string): boolean;
471
515
  sentOutputForMessage(route: Route, messageId: string): OutputRecord | null;
472
516
  /** Actual authorized message IDs in durable admission order; not invocation or edit IDs. */
473
517
  admittedMessageIds(route: Route): Iterable<string>;
@@ -496,20 +540,29 @@ export interface StorePort {
496
540
  output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
497
541
  recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean;
498
542
  output(id: string): OutputRecord | null;
543
+ /** Every pending output, including work held by a route's retry fence. */
499
544
  outputs(physicalRoute?: string): OutputRecord[];
545
+ /** Pending outputs before any future Slack joined retry on their physical route. */
546
+ deliverableOutputs(physicalRoute?: string): OutputRecord[];
500
547
  claimOutput(id: string, editInPlace?: boolean): boolean;
548
+ /** Retry only a Slack joined notice known not to have been posted. */
549
+ deferSlackJoinedOutput(id: string, delayMs: number): boolean;
550
+ /** Settle a scoped in-flight Slack workspace question, kickoff, or restart ACK from its exact Gateway receipt. */
551
+ reconcileSlackOutput(id: string): boolean;
552
+ /** Settle an in-flight Slack joined notice from its exact durable Gateway receipt. */
553
+ reconcileSlackJoinedOutput(id: string): boolean;
501
554
  finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void;
502
- createLane(lane: Lane & { model: LaneModel; modelReason: string }, sourceId: string): Lane;
555
+ createLane(lane: Lane & { model: LaneModel }, sourceId: string): Lane;
503
556
  lane(id: string): Lane | null;
504
557
  laneForRoute(route: Route): Lane | null;
505
558
  lanes(): Lane[];
506
559
  updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
507
- "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
560
+ "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result" | "localOwner"
508
561
  >>): boolean;
509
- retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath">): boolean;
562
+ retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath" | "localOwner">, orphan?: LocalHostIdentity): boolean;
510
563
  nextGeneration(id: string, pickerRestoreSourceId?: string): Lane;
511
564
  adoptLaneModel(id: string, generation: number, model: LaneModel, reason: string): boolean;
512
- changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: string,
565
+ changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: Lane["modelReason"],
513
566
  preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata?: Readonly<Record<string, string>>, operatorSourceId?: string): boolean;
514
567
  recordLaneFallback(id: string, configured: LaneModel, previous: string | null, receipt: LaneFallbackReceipt,
515
568
  notice: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean;
@@ -576,6 +629,10 @@ export interface ThreadInfo {
576
629
  readonly route: Route;
577
630
  readonly title: string;
578
631
  readonly archived: boolean | null;
632
+ /** Slack only: true when the verified root belongs to this app's bot. */
633
+ readonly botStarter?: boolean;
634
+ /** Slack only: the root is the bot's managed work title, not a user or PR notice. */
635
+ readonly editableTitle?: boolean;
579
636
  readonly requiresTag: boolean;
580
637
  readonly availableTags: readonly { readonly id: string; readonly name: string; readonly moderated: boolean }[];
581
638
  readonly appliedTags: readonly string[];
@@ -632,6 +689,8 @@ export interface Messenger {
632
689
  updateThread?(route: Route, update: ThreadUpdate): Promise<ThreadInfo>;
633
690
  inspectDiscordContext?(route: Route): Promise<DiscordContext>;
634
691
  discordPurpose?(request: DiscordPurposeRequest): Promise<readonly DiscordPurposeNote[]>;
692
+ inspectSlackContext?(request: SlackContextRequest): Promise<SlackContext>;
693
+ slackPurpose?(request: SlackPurposeRequest): Promise<readonly SlackPurposeNote[]>;
635
694
  messengerPresence?(request: MessengerPresenceRequest): Promise<DiscordPresenceStatus>;
636
695
  /** null means adapter-owned recovery. An ordered read uses the Gateway's saved gap cutoff. */
637
696
  fetchAfter(route: Route, messageId: string, historySequence?: number): Promise<Inbound[] | null>;
@@ -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 }) };