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
@@ -32,19 +32,63 @@ import type { ApprovalResolution } from "../contracts";
32
32
  import { captureDecision, resolveDecision } from "../lane/decisions";
33
33
  import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
34
34
  import { laneData, readLaneRows, toLane, type LaneRow } from "../lane/lane-rows";
35
- import { compareMessageIds } from "../routing/message-order";
35
+ import { compareMessageIds, slackOutputTimestamp, slackWorkspaceQuestionTimestamp } from "../routing/message-order";
36
36
  import { storedWorkflowName, workflowChoice } from "../lane/workflow";
37
37
  import { laneWaitKey, type LaneReport } from "../lane/lane-report";
38
38
  import { laneWatchReplySource } from "../lane/lane-watch";
39
39
  import { discordWorkThreadOwnerKey, recordedDiscordWorkThreadSource } from "../messaging/discord-work-thread";
40
40
  import { isResultAttachmentSnapshot } from "../messaging/result-attachment";
41
- import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
41
+ import { existingWorkspace, matchingSlackHistoryChoice, slackWorkspaceAnswer, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
42
42
  import type { CronUpdate } from "../cron/cron-jobs";
43
43
  import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "../pr/pr-intake-work";
44
44
  import { isPrReviewLane, type ReviewRound } from "../pr/pr-intake-review";
45
45
  import { DeferredRoutingQueue, type DeferredChoiceRow } from "./deferred-routing";
46
46
 
47
47
  const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
48
+ const SLACK_JOINED_RETRY = "slack:joined-retry:";
49
+ const SLACK_JOINED_REJECTED_AT = "gateway:slack-joined-rejected-at:";
50
+ const SLACK_JOINED_RETRY_LIMIT = 2;
51
+ const SLACK_JOINED_FENCES = `WITH fences AS (
52
+ SELECT fence.physical_route, min(fence.sequence) AS sequence
53
+ FROM metadata AS retry JOIN outputs AS fence ON fence.id = substr(retry.key, ${SLACK_JOINED_RETRY.length + 1})
54
+ WHERE retry.key GLOB '${SLACK_JOINED_RETRY}*' AND fence.state = 'pending' AND json_extract(retry.value, '$.at') > ?
55
+ GROUP BY fence.physical_route
56
+ )`;
57
+ interface SlackJoinedRetry {
58
+ readonly count: number;
59
+ readonly at?: number;
60
+ readonly priorAttemptIds?: readonly string[];
61
+ }
62
+ interface GatewaySendAttempt {
63
+ readonly id: string;
64
+ readonly arguments: string;
65
+ readonly result: string | null;
66
+ }
67
+
68
+ function gatewaySendSuccess(result: unknown): string | null {
69
+ return result && typeof result === "object" && "value" in result && typeof result.value === "string"
70
+ && isDeepStrictEqual(result, { ok: true, value: result.value }) ? result.value : null;
71
+ }
72
+
73
+ function parseGatewaySendResult(receipt: string): unknown {
74
+ // Preserve the Rust u64 token before rounding can merge valid and invalid delays.
75
+ return JSON.parse(receipt, (key, value: unknown, context?: { source?: string }) => {
76
+ const token = context?.source;
77
+ return key === "retryAfterMs" && token && /^(?:0|[1-9]\d{0,19})$/u.test(token) ? BigInt(token) : value;
78
+ });
79
+ }
80
+
81
+ function gatewaySendRejection(result: unknown): { readonly retryAfterMs?: number } | null {
82
+ if (!result || typeof result !== "object" || !("error" in result) || typeof result.error !== "string") return null;
83
+ const rejection = { ok: false, certainty: "rejected", error: result.error };
84
+ if (!("retryAfterMs" in result)) return isDeepStrictEqual(result, rejection) ? {} : null;
85
+ const retryAfterMs = result.retryAfterMs;
86
+ if (typeof retryAfterMs !== "bigint" || retryAfterMs > 18_446_744_073_709_551_615n
87
+ || !isDeepStrictEqual(result, { ...rejection, retryAfterMs })) return null;
88
+ // Gateway emits a u64. A delay outside the scheduler's safe range does
89
+ // not turn definitive non-delivery into an uncertain remote effect.
90
+ return retryAfterMs <= BigInt(Number.MAX_SAFE_INTEGER) ? { retryAfterMs: Number(retryAfterMs) } : {};
91
+ }
48
92
  const retiredScopeId = (column: "id" | "source_id" | "retired.id" | "newer.id") =>
49
93
  `(${column} GLOB 'scope-review:*' OR ${column} GLOB 'handoff:scope-review:*')`;
50
94
 
@@ -145,6 +189,7 @@ const inboundData = (input: Inbound): Inbound => ({
145
189
  id: input.id, route: input.route, messageId: input.messageId, text: input.text,
146
190
  ...(input.discordOriginalText === undefined ? {} : { discordOriginalText: input.discordOriginalText }),
147
191
  ...(input.routingText === undefined ? {} : { routingText: input.routingText }),
192
+ ...(input.slackVerifiedRoutingBody === true ? { slackVerifiedRoutingBody: true } : {}),
148
193
  ...(input.telegramProtectedCommand === undefined ? {} : { telegramProtectedCommand: input.telegramProtectedCommand }),
149
194
  ...(input.telegramOriginalText === undefined ? {} : { telegramOriginalText: input.telegramOriginalText }),
150
195
  ...(input.interactionId === undefined ? {} : { interactionId: input.interactionId }),
@@ -158,7 +203,8 @@ const inboundData = (input: Inbound): Inbound => ({
158
203
  function inboundIdentity(input: Inbound) {
159
204
  // Derived routing text and independently edited references do not change the
160
205
  // event identity. Keep the first snapshot, including on pre-upgrade replay.
161
- const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText, ...data } = inboundData(input);
206
+ const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText,
207
+ slackVerifiedRoutingBody: _slackVerifiedRoutingBody, ...data } = inboundData(input);
162
208
  return {
163
209
  ...data,
164
210
  // Slack supplies no command timestamp. A transport redelivery has a fresh
@@ -364,7 +410,7 @@ export class Store implements StorePort {
364
410
  const selection = input.pickerSelection;
365
411
  if (selection ? input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
366
412
  || input.id !== `picker:${selection.outputId}` || target !== "main"
367
- || selection.target !== undefined && (input.route.platform !== "discord" || selection.confirmed !== undefined
413
+ || selection.target !== undefined && (input.route.platform !== "discord" && input.route.platform !== "slack" || selection.confirmed !== undefined
368
414
  || (selection.target !== "head" && selection.target !== "lane"))
369
415
  : input.interactionId !== undefined && (input.route.platform !== "discord" || typeof input.interactionId !== "string" || !/^[1-9]\d{0,19}$/.test(input.interactionId))
370
416
  || (input.invocationId !== undefined && !slackInvocation)
@@ -378,7 +424,7 @@ export class Store implements StorePort {
378
424
  receivePrWork(input: Inbound, target: string | null, r: ReviewRound): boolean {
379
425
  const parent = { ...input.route, threadId: null };
380
426
  const offer = this.output(`cron-pr:offer:${r.repository}:${r.number}`);
381
- if (!r.automation || input.route.platform !== "discord" || !input.route.guildId || input.route.topicId !== undefined
427
+ if (!r.automation || (input.route.platform !== "discord" && input.route.platform !== "slack") || !input.route.guildId || input.route.topicId !== undefined
382
428
  || input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
383
429
  || input.pickerSelection || input.attachments.length || input.discordOriginalText !== undefined || input.reply
384
430
  || this.getMeta(`user-source:${input.id}`) !== null || r.automation.anchor !== input.route.threadId
@@ -554,48 +600,71 @@ export class Store implements StorePort {
554
600
 
555
601
  hasPendingTopicChoice(input: InputRecord, deadline: number): boolean {
556
602
  const { platform, accountId, authorityId, guildId, channelId, threadId } = input.route;
557
- if (platform !== "discord" || guildId === null || threadId === null) return false;
603
+ if (threadId === null || platform !== "slack" && (platform !== "discord" || guildId === null)) return false;
558
604
  // An input already ACKed to Gateway but still awaiting deferred topic routing
559
605
  // has no head receipt yet either; it fences the choice like a pending ledger row.
560
606
  const deferred = this.deferredRouting.choices(input, deadline);
561
607
  // Gateway creates the shared ingress ledger; standalone Store use has none.
562
608
  const ledger = this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get() !== null;
563
609
  const questionId = `${input.id}:workspace`;
610
+ const slackQuestionTs = slackWorkspaceQuestionTimestamp(this, input);
564
611
  const choices: readonly { readonly cwd: string }[] = JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]");
565
612
  // The Gateway pending index skips delivered history, including terminal rejections.
566
613
  // Unresolved rows stay pending. The durable insert, not its wall-clock timestamp,
567
614
  // fences a timely-authored choice even when transport-delayed.
568
- const rows = ledger ? this.db.query<DeferredChoiceRow, [number, number, string, string, string, string, string, string, string]>(`
615
+ const rows = ledger ? this.db.query<DeferredChoiceRow, [number, number, string, string, string, string, string | null, string, string]>(`
569
616
  SELECT json_extract(data, '$.input.id') AS id,
570
617
  json_extract(data, '$.input.text') AS text,
618
+ json_extract(data, '$.input.routingText') AS routingText,
619
+ json_type(data, '$.input.slackVerifiedRoutingBody') IS 'true' AS verifiedSlackBody,
571
620
  json_extract(data, '$.input.messageId') AS messageId,
572
621
  json_extract(data, '$.input.reply.messageId') AS replyId,
573
- json_extract(data, '$.input.receivedAt') AS authoredAt
622
+ json_extract(data, '$.input.receivedAt') AS authoredAt,
623
+ coalesce(json_extract(data, '$.input.unresolvedReply'), 0)
624
+ OR json_type(data, '$.input.attachments') IS NOT 'array'
625
+ OR json_array_length(data, '$.input.attachments') > 0 AS attached
574
626
  FROM gateway_events INDEXED BY gateway_events_pending WHERE delivered_at IS NULL
575
627
  AND json_extract(data, '$.kind') = 'message'
576
628
  AND json_type(data, '$.input.pickerSelection') IS NULL
577
629
  AND (json_type(data, '$.input.messageId') = 'text'
578
630
  OR json_type(data, '$.input.interactionId') = 'text')
579
- AND json_type(data, '$.input.receivedAt') = 'integer'
631
+ AND (json_type(data, '$.input.receivedAt') = 'integer'
632
+ OR json_extract(data, '$.input.route.platform') = 'slack' AND json_type(data, '$.input.receivedAt') = 'real')
580
633
  AND json_extract(data, '$.input.receivedAt') BETWEEN ? AND ?
581
634
  AND json_extract(data, '$.input.id') <> ?
582
635
  AND json_extract(data, '$.input.route.platform') = ?
583
636
  AND json_extract(data, '$.input.route.accountId') = ?
584
637
  AND json_extract(data, '$.input.route.authorityId') = ?
585
- AND json_extract(data, '$.input.route.guildId') = ?
638
+ AND json_extract(data, '$.input.route.guildId') IS ?
586
639
  AND json_extract(data, '$.input.route.channelId') = ?
587
640
  AND json_extract(data, '$.input.route.threadId') = ?
588
641
  `) : null;
589
642
  const pending = rows?.iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId) ?? [];
590
643
  for (const candidates of [deferred, pending]) {
591
644
  for (const row of candidates) {
592
- if (row.messageId !== null && row.id.startsWith(`discord:${accountId}:${row.messageId}:edit:`)) continue;
645
+ const scope = platform === "slack" ? `${accountId}:${channelId}` : accountId;
646
+ if (row.messageId !== null && row.id.startsWith(`${platform}:${scope}:${row.messageId}:edit:`)) continue;
593
647
  const questionReply = row.replyId !== null && this.sentOutputForMessage(input.route, row.replyId)?.id === questionId;
594
648
  const scopedReply = questionReply || row.replyId !== null && row.replyId === input.messageId;
595
- if (!questionReply && row.authoredAt < deadline - TOPIC_CHOICE_WAIT_MS) continue;
596
649
  const text = row.text.trim();
597
- if (text === "/stop") return true;
650
+ const locallyTimely = questionReply || row.authoredAt >= deadline - TOPIC_CHOICE_WAIT_MS;
651
+ if (text === "/stop") {
652
+ if (locallyTimely) return true;
653
+ continue;
654
+ }
598
655
  if (row.messageId === null || row.replyId !== null && !scopedReply || /^\/new(?:\s|$)/.test(text)) continue;
656
+ if (platform === "slack") {
657
+ // Slack may publish the exact question before HEAD commits its receipt.
658
+ // All manual answers use message order, not the local start of the window.
659
+ if (!slackQuestionTs || row.replyId !== null || row.attached || !/^\d{1,20}\.\d{6}$/u.test(row.messageId)
660
+ || compareMessageIds("slack", row.messageId, slackQuestionTs) !== 1) continue;
661
+ const answer = slackWorkspaceAnswer(row.text, row.routingText, row.verifiedSlackBody === 1);
662
+ if (!answer || answer.source !== null && (answer.source !== input.messageId
663
+ || this.firstAdmittedMessage(input.route, answer.source)?.id !== input.id)) continue;
664
+ if (matchingSlackHistoryChoice(answer.text, answer.cwd, choices)) return true;
665
+ continue;
666
+ }
667
+ if (!locallyTimely) continue;
599
668
  if (/^[1-9]\d*$/.test(text)) return true;
600
669
  const request = topicRequest(text);
601
670
  if (request.cwd === null ? !scopedReply : request.text.trim()) continue;
@@ -616,6 +685,7 @@ export class Store implements StorePort {
616
685
  if (!Number.isSafeInteger(deadline) || Date.now() < deadline
617
686
  || current?.state !== "pending" || current.target !== null || routeKey(current.route) !== routeKey(input.route)
618
687
  || this.getMeta(`topic-choice-deadline:${input.id}`) !== String(deadline)
688
+ || JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]").length === 0
619
689
  || this.getMeta(`topic-previous:${input.id}`) !== null || this.getMeta(automatic) !== null
620
690
  || this.hasPendingTopicChoice(current, deadline)) return false;
621
691
  this.setMeta(automatic, pin);
@@ -769,13 +839,30 @@ export class Store implements StorePort {
769
839
  .get(messageId, this.getMeta(`discord:output-part:${messageId}`), route.accountId, route.authorityId, route.guildId, route.channelId) !== null;
770
840
  }
771
841
 
842
+ hasSlackHistoryChoice(route: Route, number: number, authoredAt: number, excludeSourceId?: string): boolean {
843
+ if (route.platform !== "slack" || route.threadId === null) return false;
844
+ // A lone late digit is ambiguous just after expiry. Once a later question
845
+ // is open, only overlapping answer windows can make its selection ambiguous.
846
+ const lateGrace = excludeSourceId === undefined ? TOPIC_CHOICE_WAIT_MS : 0;
847
+ return this.db.query(`SELECT 1 FROM outputs
848
+ JOIN metadata AS options ON options.key = 'topic-history:' || outputs.source_id
849
+ JOIN metadata AS deadline ON deadline.key = 'topic-choice-deadline:' || outputs.source_id
850
+ WHERE outputs.physical_route = ? AND outputs.state = 'sent' AND outputs.id = outputs.source_id || ':workspace'
851
+ AND json_array_length(options.value) >= ? AND CAST(deadline.value AS INTEGER) - ? <= ?
852
+ AND ? <= CAST(deadline.value AS INTEGER) + ?
853
+ AND outputs.source_id IS NOT ?
854
+ LIMIT 1`).get(physicalRouteKey(route), number, TOPIC_CHOICE_WAIT_MS, authoredAt, authoredAt, lateGrace, excludeSourceId ?? null) !== null;
855
+ }
856
+
772
857
  sentOutputForMessage(route: Route, messageId: string): OutputRecord | null {
773
858
  const scoped = this.outputReceiptsForMessage(route, messageId).filter(output => output.state === "sent");
774
859
  return scoped.length === 1 ? scoped[0] ?? null : null;
775
860
  }
776
861
 
777
862
  private outputReceiptsForMessage(route: Route, messageId: string): OutputRecord[] {
778
- const part = route.platform === "discord" ? this.getMeta(`discord:output-part:${messageId}`) : null;
863
+ const part = route.platform === "discord" ? this.getMeta(`discord:output-part:${messageId}`)
864
+ : route.platform === "slack" ? this.getMeta(`slack:output-part:${JSON.stringify([route.accountId, route.channelId, messageId])}`)
865
+ : null;
779
866
  // The Gateway can know a completed multipart send before this controller
780
867
  // durably records its confirmation. Such a part identifies, but does not prove, placement.
781
868
  const rows = this.db.query<OutputRow, [string, string | null]>(
@@ -943,7 +1030,7 @@ export class Store implements StorePort {
943
1030
  this.setMeta(`steering-topic-reply:${owner.id}`, JSON.stringify(topic.route));
944
1031
  }
945
1032
  }
946
- if (submitted && lane?.route.platform === "discord" && lane.route.guildId && lane.route.threadId) {
1033
+ if (submitted && lane?.route.threadId && (lane.route.platform === "slack" || lane.route.platform === "discord" && lane.route.guildId)) {
947
1034
  if (ownerId === null || ownerId === id) this.setMeta(`lane-latest-run:${lane.id}`, id);
948
1035
  }
949
1036
  return submitted;
@@ -1003,7 +1090,7 @@ export class Store implements StorePort {
1003
1090
  }
1004
1091
 
1005
1092
  private laneReportSources(receiptId: string, input: InputRecord, source: InputRecord): Readonly<Record<string, string>> {
1006
- const approvalSource = this.getMeta(`handoff-reply:${input.id}`) !== null ? source : this.reportApprovalSource(input.id);
1093
+ const approvalSource = this.parentThreadReply(input, source) ? source : this.reportApprovalSource(input.id);
1007
1094
  return {
1008
1095
  [`activity-source:${receiptId}`]: source.id,
1009
1096
  // Redirect the mediated report, not native approvals raised during review.
@@ -1030,7 +1117,7 @@ export class Store implements StorePort {
1030
1117
  }
1031
1118
 
1032
1119
  /**
1033
- * When opted in on Discord (`editInPlace`), nonterminal progress uses one
1120
+ * When opted in on Discord or Slack (`editInPlace`), nonterminal progress uses one
1034
1121
  * `⏳` status message edited in place. Each update stays its own immutable
1035
1122
  * output; `claimOutput` decides whether it edits that message. By default (or
1036
1123
  * on other platforms), every update posts as an ordinary new message.
@@ -1040,9 +1127,12 @@ export class Store implements StorePort {
1040
1127
  stream: string,
1041
1128
  editInPlace = false,
1042
1129
  ): boolean {
1043
- if (!editInPlace || output.route.platform !== "discord") return this.queueOutput(output);
1044
- this.setMeta(`status-stream:${output.id}`, stream);
1130
+ if (!editInPlace || output.route.platform !== "discord" && output.route.platform !== "slack") return this.queueOutput(output);
1045
1131
  const text = /^(?:`{3,}|~{3,})/.test(output.text.trimStart()) ? `⏳\n${output.text}` : `⏳ ${output.text}`;
1132
+ // The Slack status marker is a single 3,000 UTF-16 unit section. Let the
1133
+ // ordinary Slack output path split or upload longer updates instead.
1134
+ if (output.route.platform === "slack" && text.length > 3_000) return this.queueOutput(output);
1135
+ this.setMeta(`status-stream:${output.id}`, stream);
1046
1136
  return this.queueOutput({ ...output, text, status: true });
1047
1137
  }
1048
1138
 
@@ -1279,10 +1369,11 @@ export class Store implements StorePort {
1279
1369
  this.queueOutput({ ...output, sourceId: id, route: input.route });
1280
1370
  }
1281
1371
  } else if (this.queueOutput({ ...output, sourceId: id, route: input.route })
1282
- && settlement?.discordHeadFollowups?.length && state === "done" && input.state === "submitted"
1283
- && input.target === "main" && input.route.platform === "discord" && output.id === `${id}:answer`
1372
+ && settlement?.headFollowups?.length && state === "done" && input.state === "submitted"
1373
+ && input.target === "main" && (input.route.platform === "discord" || input.route.platform === "slack")
1374
+ && output.id === `${id}:answer`
1284
1375
  && !output.picker && output.text.trim() && this.ownerSource(id)?.id === id) {
1285
- this.setMeta(`discord-head-followups:${output.id}`, JSON.stringify(settlement.discordHeadFollowups));
1376
+ this.setMeta(`${input.route.platform}-head-followups:${output.id}`, JSON.stringify(settlement.headFollowups));
1286
1377
  }
1287
1378
  }
1288
1379
  this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
@@ -1409,21 +1500,33 @@ export class Store implements StorePort {
1409
1500
  if (scoped.sourceId !== source.id) throw new Error(`Invalid scoped Discord reply source: ${input.id}`);
1410
1501
  return input.route;
1411
1502
  }
1503
+ const parentReply = this.parentThreadReply(input, source);
1504
+ if (parentReply) return parentReply;
1505
+ const pinned = this.getMeta(`steering-topic-reply:${input.id}`);
1506
+ return pinned ? JSON.parse(pinned) : this.deliveryRoute(source);
1507
+ }
1508
+
1509
+ parentThreadReply(input: InputRecord, source: InputRecord): Route | null {
1412
1510
  const handoffReply = this.getMeta(`handoff-reply:${input.id}`);
1511
+ const kickoffId = `${source.id}:kickoff`;
1512
+ // Native thread creation has its own delivery binding; do not reinterpret
1513
+ // its approval routing as existing-thread placement.
1514
+ const opening = input.id === `handoff:${source.id}:lane` && this.getMeta(`kickoff-output:${input.id}`) === kickoffId
1515
+ && this.getMeta(`handoff-native:${source.id}`) !== "true";
1516
+ if (handoffReply === null && !opening) return null;
1517
+ const { route } = input;
1518
+ const fromExactParent = input.target && source.target === "main" && !source.pickerSelection
1519
+ && this.getMeta(`handoff-source:${input.id}`) === source.id && this.getMeta(`user-source:${source.id}`) === "true"
1520
+ && (route.platform === "discord" && route.guildId || route.platform === "slack") && route.threadId && route.topicId === undefined
1521
+ && routeKey({ ...route, threadId: null }) === routeKey(source.route) && this.laneForRoute(route)?.id === input.target;
1413
1522
  if (handoffReply !== null) {
1414
- const { route } = input;
1415
- if (!input.target || input.id !== `handoff:${source.id}:${input.target}`
1416
- || this.getMeta(`handoff-source:${input.id}`) !== source.id
1417
- || source.target !== "main" || source.pickerSelection || this.getMeta(`user-source:${source.id}`) !== "true"
1418
- || route.platform !== "discord" || !route.guildId || !route.threadId || route.topicId !== undefined
1419
- || routeKey(route) !== handoffReply || routeKey({ ...route, threadId: null }) !== routeKey(source.route)
1420
- || this.laneForRoute(route)?.id !== input.target) {
1523
+ if (!fromExactParent || input.id !== `handoff:${source.id}:${input.target}` || routeKey(route) !== handoffReply)
1421
1524
  throw new Error(`Invalid existing-thread delivery binding: ${input.id}`);
1422
- }
1423
1525
  return route;
1424
1526
  }
1425
- const pinned = this.getMeta(`steering-topic-reply:${input.id}`);
1426
- return pinned ? JSON.parse(pinned) : this.deliveryRoute(source);
1527
+ if (!fromExactParent) return null;
1528
+ const kickoff = this.output(kickoffId);
1529
+ return kickoff?.state === "sent" && kickoff.sourceId === input.id && routeKey(kickoff.route) === routeKey(route) ? route : null;
1427
1530
  }
1428
1531
 
1429
1532
  private deliveryRoute(source: InputRecord, expectedLane?: string | null): Route {
@@ -1442,8 +1545,8 @@ export class Store implements StorePort {
1442
1545
 
1443
1546
  queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
1444
1547
  if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) return false;
1445
- if (output.status && (output.route.platform !== "discord" || output.picker || output.resultAttachment)) {
1446
- throw new Error(`Status delivery requires a plain Discord message: ${output.id}`);
1548
+ if (output.status && (output.route.platform !== "discord" && output.route.platform !== "slack" || output.picker || output.resultAttachment)) {
1549
+ throw new Error(`Status delivery requires a plain Discord or Slack message: ${output.id}`);
1447
1550
  }
1448
1551
  return this.db.transaction(() => {
1449
1552
  const existing = this.output(output.id);
@@ -1455,6 +1558,7 @@ export class Store implements StorePort {
1455
1558
  || output.replyTo !== undefined && (!existing.replyTo
1456
1559
  || existing.replyTo.messageId !== output.replyTo.messageId
1457
1560
  || existing.replyTo.requireExisting !== output.replyTo.requireExisting
1561
+ || existing.replyTo.joinedAnswerId !== output.replyTo.joinedAnswerId
1458
1562
  || physicalRouteKey(existing.replyTo.route) !== physicalRouteKey(output.replyTo.route))) {
1459
1563
  throw new Error(`Output identity conflict: ${output.id}`);
1460
1564
  }
@@ -1489,10 +1593,14 @@ export class Store implements StorePort {
1489
1593
  }
1490
1594
  }
1491
1595
  const replyOrigin = original ?? laneWatchReplySource(this, source, output.id);
1492
- const replyTo = replyOrigin?.route.platform === "discord" && replyOrigin.messageId
1596
+ const joinedAnswerId = output.replyTo?.joinedAnswerId;
1597
+ const slackLink = replyOrigin?.route.platform === "slack" && output.route.platform === "slack"
1598
+ && joinedAnswerId !== undefined && output.replyTo?.requireExisting === true && !output.text && !output.status && !output.picker && !attachment;
1599
+ const replyTo = (replyOrigin?.route.platform === "discord" && joinedAnswerId === undefined || slackLink) && replyOrigin?.messageId
1493
1600
  && physicalRouteKey(replyOrigin.route) === physicalRouteKey(output.route)
1494
1601
  ? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId,
1495
- ...(output.replyTo?.requireExisting ? { requireExisting: true } : {}) } : undefined;
1602
+ ...(output.replyTo?.requireExisting ? { requireExisting: true } : {}),
1603
+ ...(slackLink ? { joinedAnswerId } : {}) } : undefined;
1496
1604
  if (output.replyTo !== undefined && (!replyTo || output.replyTo.messageId !== replyTo.messageId
1497
1605
  || physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
1498
1606
  throw new Error(`Output reply differs from its source: ${output.id}`);
@@ -1545,12 +1653,18 @@ export class Store implements StorePort {
1545
1653
  }
1546
1654
 
1547
1655
  outputs(physicalRoute?: string): OutputRecord[] {
1548
- if (physicalRoute !== undefined) {
1549
- return (this.db.query("SELECT * FROM outputs WHERE state = 'pending' AND physical_route = ? ORDER BY sequence")
1550
- .all(physicalRoute) as OutputRow[]).map(toOutput);
1551
- }
1552
- return (this.db.query("SELECT * FROM outputs WHERE state = 'pending' ORDER BY sequence")
1553
- .all() as OutputRow[]).map(toOutput);
1656
+ const route = physicalRoute === undefined ? "" : "AND outputs.physical_route = ?";
1657
+ return this.db.query<OutputRow, string[]>(`SELECT * FROM outputs
1658
+ WHERE state = 'pending' ${route} ORDER BY sequence`)
1659
+ .all(...(physicalRoute === undefined ? [] : [physicalRoute])).map(toOutput);
1660
+ }
1661
+
1662
+ deliverableOutputs(physicalRoute?: string): OutputRecord[] {
1663
+ const route = physicalRoute === undefined ? "" : "AND outputs.physical_route = ?";
1664
+ return this.db.query<OutputRow, [number, ...string[]]>(`${SLACK_JOINED_FENCES}
1665
+ SELECT outputs.* FROM outputs LEFT JOIN fences USING (physical_route)
1666
+ WHERE outputs.state = 'pending' AND (fences.sequence IS NULL OR outputs.sequence < fences.sequence) ${route}
1667
+ ORDER BY outputs.sequence`).all(Date.now(), ...(physicalRoute === undefined ? [] : [physicalRoute])).map(toOutput);
1554
1668
  }
1555
1669
 
1556
1670
  hasUnresolvedHeadDelivery(): boolean {
@@ -1642,6 +1756,9 @@ export class Store implements StorePort {
1642
1756
  }
1643
1757
  const output = this.output(id);
1644
1758
  if (output?.state !== "pending") return false;
1759
+ if (output.route.platform === "slack" && this.db.query(`${SLACK_JOINED_FENCES}
1760
+ SELECT 1 FROM outputs JOIN fences USING (physical_route)
1761
+ WHERE outputs.id = ? AND outputs.sequence >= fences.sequence`).get(Date.now(), id)) return false;
1645
1762
  if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) {
1646
1763
  // Only the existing immutable answer can be sent. Do not consult live
1647
1764
  // lane/HEAD ownership or mutate its historical reply/edit destination.
@@ -1662,11 +1779,46 @@ export class Store implements StorePort {
1662
1779
  this.db.query("UPDATE outputs SET edit_of = ? WHERE id = ?")
1663
1780
  .run(JSON.stringify({ route: physicalRoute(output.route), messageId: anchor.remoteId }), id);
1664
1781
  }
1782
+ if (this.isSlackJoinedNotice(output)) {
1783
+ const retry = this.slackJoinedRetry(id);
1784
+ const prior = this.hasGatewayEffects() ? this.gatewaySendAttempts(id, SLACK_JOINED_RETRY_LIMIT + 1) : [];
1785
+ // While claimed, this fixes the pre-existing effects. A previous
1786
+ // retry's receipt cannot stand in for a new claim that never reached IPC.
1787
+ this.setMeta(`${SLACK_JOINED_RETRY}${id}`, JSON.stringify({
1788
+ ...retry, priorAttemptIds: prior.map(attempt => attempt.id),
1789
+ }));
1790
+ }
1665
1791
  return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'")
1666
1792
  .run(id).changes === 1;
1667
1793
  }).immediate();
1668
1794
  }
1669
1795
 
1796
+ private isSlackJoinedNotice(output: OutputRecord): boolean {
1797
+ return output.remoteId === null && output.route.platform === "slack"
1798
+ && Boolean(output.replyTo?.joinedAnswerId) && output.replyTo?.requireExisting === true && !output.text
1799
+ && !output.resultAttachment && !output.status && !output.picker && !output.editOf;
1800
+ }
1801
+
1802
+ private slackJoinedRetry(id: string): SlackJoinedRetry {
1803
+ const retry = this.getMeta(`${SLACK_JOINED_RETRY}${id}`);
1804
+ return retry === null ? { count: 0 } : JSON.parse(retry);
1805
+ }
1806
+
1807
+ deferSlackJoinedOutput(id: string, delayMs: number): boolean {
1808
+ return this.db.transaction(() => {
1809
+ const output = this.output(id);
1810
+ if (output?.state !== "sending" || !this.isSlackJoinedNotice(output)) return false;
1811
+ return this.recordSlackJoinedRetry(id, this.slackJoinedRetry(id).count, Date.now(), delayMs);
1812
+ }).immediate();
1813
+ }
1814
+
1815
+ private recordSlackJoinedRetry(id: string, count: number, completedAt: number, delayMs: number): boolean {
1816
+ const at = completedAt + Math.max(1000, delayMs);
1817
+ if (count >= SLACK_JOINED_RETRY_LIMIT || !Number.isSafeInteger(delayMs) || delayMs < 0 || !Number.isSafeInteger(at)) return false;
1818
+ this.setMeta(`${SLACK_JOINED_RETRY}${id}`, JSON.stringify({ at, count: count + 1 }));
1819
+ return this.db.query("UPDATE outputs SET state = 'pending', error = NULL WHERE id = ? AND state = 'sending'").run(id).changes === 1;
1820
+ }
1821
+
1670
1822
  finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void {
1671
1823
  this.db.transaction(() => {
1672
1824
  const output = this.output(id);
@@ -1691,8 +1843,10 @@ export class Store implements StorePort {
1691
1843
  }
1692
1844
  this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
1693
1845
  .run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
1694
- if (state === "sent" && remoteId && output.route.platform === "discord") {
1695
- this.queueDiscordHeadFollowupLinks(output, remoteId);
1846
+ if (state !== "pending" && output.route.platform === "slack" && output.replyTo?.joinedAnswerId)
1847
+ this.db.query("DELETE FROM metadata WHERE key = ?").run(`${SLACK_JOINED_RETRY}${id}`);
1848
+ if (state === "sent" && remoteId && (output.route.platform === "discord" || output.route.platform === "slack")) {
1849
+ this.queueHeadFollowupLinks(output, remoteId);
1696
1850
  }
1697
1851
  const stream = this.getMeta(`status-stream:${id}`);
1698
1852
  if (stream) {
@@ -1706,17 +1860,30 @@ export class Store implements StorePort {
1706
1860
  this.db.query("DELETE FROM metadata WHERE key = ?").run(anchorKey);
1707
1861
  }
1708
1862
  }
1709
- // Start the owner's response window with the durable question receipt,
1710
- // never with input admission or an unconfirmed send attempt.
1711
- if (state === "sent" && id === `${output.sourceId}:workspace`
1712
- && this.getMeta(`topic-history:${output.sourceId}`) !== null && !this.getMeta(`topic-creator:${output.sourceId}`)) {
1713
- this.setMeta(`topic-choice-deadline:${output.sourceId}`, String(Date.now() + TOPIC_CHOICE_WAIT_MS));
1714
- }
1863
+ if (state === "sent") this.startTopicChoiceDeadline({ ...output, state, remoteId: remoteId ?? output.remoteId });
1715
1864
  }).immediate();
1716
1865
  }
1717
1866
 
1718
- private queueDiscordHeadFollowupLinks(output: OutputRecord, remoteId: string): void {
1719
- const key = `discord-head-followups:${output.id}`;
1867
+ private startTopicChoiceDeadline(output: OutputRecord): void {
1868
+ const key = `topic-choice-deadline:${output.sourceId}`;
1869
+ if (output.id !== `${output.sourceId}:workspace` || this.getMeta(`topic-creator:${output.sourceId}`)
1870
+ || JSON.parse(this.getMeta(`topic-history:${output.sourceId}`) ?? "[]").length === 0 || this.getMeta(key) !== null) return;
1871
+ let confirmedAt = Date.now();
1872
+ if (output.route.platform === "slack") {
1873
+ const source = this.input(output.sourceId);
1874
+ const post = source && this.slackPlainPostTimestamp(output, source);
1875
+ if (!post) return;
1876
+ // The clock is the last verified physical post, not IPC return or
1877
+ // recovery time. Round up to whole milliseconds for the saved deadline.
1878
+ confirmedAt = Number((BigInt(post.replace(".", "")) + 999n) / 1000n);
1879
+ }
1880
+ const deadline = confirmedAt + TOPIC_CHOICE_WAIT_MS;
1881
+ if (Number.isSafeInteger(deadline)) this.setMeta(key, String(deadline));
1882
+ }
1883
+
1884
+ private queueHeadFollowupLinks(output: OutputRecord, remoteId: string): void {
1885
+ const { platform } = output.route;
1886
+ const key = `${platform}-head-followups:${output.id}`;
1720
1887
  const saved = this.getMeta(key);
1721
1888
  if (!saved) return;
1722
1889
  const owner = this.input(output.sourceId);
@@ -1724,21 +1891,30 @@ export class Store implements StorePort {
1724
1891
  const guild = output.route.guildId;
1725
1892
  const channel = output.route.threadId ?? output.route.channelId;
1726
1893
  const snowflake = /^\d{1,20}$/u;
1894
+ const slack = platform === "slack";
1895
+ const messageId = slack ? /^\d{1,20}\.\d{6}$/u : snowflake;
1727
1896
  if (owner?.target !== "main" || owner.state !== "done"
1728
- || (owner.messageId === null ? !owner.interactionId || target !== undefined : target?.messageId !== owner.messageId)
1729
- || !snowflake.test(channel) || guild !== null && !snowflake.test(guild) || !snowflake.test(remoteId)) return;
1730
- const url = `https://discord.com/channels/${guild ?? "@me"}/${channel}/${remoteId}`;
1897
+ || (owner.messageId === null ? !(slack ? owner.invocationId : owner.interactionId) || target !== undefined
1898
+ : !slack && target?.messageId !== owner.messageId)
1899
+ || !slack && (!snowflake.test(channel) || guild !== null && !snowflake.test(guild))) return;
1900
+ if (!messageId.test(remoteId)) {
1901
+ // A file receipt confirms publication, not an exact Slack message.
1902
+ if (slack && remoteId.startsWith("file:")) this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
1903
+ return;
1904
+ }
1905
+ const url = slack ? null : `https://discord.com/channels/${guild ?? "@me"}/${channel}/${remoteId}`;
1731
1906
  const physical = new Set(owner.messageId === null ? [] : [owner.messageId]);
1732
1907
  for (const id of JSON.parse(saved) as string[]) {
1733
1908
  const source = this.input(id);
1734
1909
  if (source?.target !== "main" || source.state !== "done" || source.generation !== owner.generation
1735
- || !source.messageId || !snowflake.test(source.messageId) || physical.has(source.messageId)
1910
+ || !source.messageId || !messageId.test(source.messageId) || physical.has(source.messageId)
1736
1911
  || routeKey(source.route) !== routeKey(output.route) || this.ownerSource(id)?.id !== id
1737
1912
  || this.getMeta(`steering-owner:${id}`) !== owner.id) continue;
1738
1913
  physical.add(source.messageId);
1739
1914
  this.queueOutput({ id: `${output.id}:joined:${id}`, sourceId: id, route: source.route,
1740
- replyTo: { route: physicalRoute(source.route), messageId: source.messageId, requireExisting: true },
1741
- text: `이 후속 메시지와 함께 처리한 [HEAD 통합 답변](<${url}>)` });
1915
+ replyTo: { route: physicalRoute(source.route), messageId: source.messageId, requireExisting: true,
1916
+ ...(slack ? { joinedAnswerId: remoteId } : {}) },
1917
+ text: url ? `이 후속 메시지와 함께 처리한 [HEAD 통합 답변](<${url}>)` : "" });
1742
1918
  }
1743
1919
  // Commit the canonical send receipt and its dependent notices together.
1744
1920
  this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
@@ -1831,7 +2007,7 @@ export class Store implements StorePort {
1831
2007
 
1832
2008
  private sentLaneModelPicker(source: InputRecord) {
1833
2009
  const selection = source.pickerSelection;
1834
- if (source.route.platform !== "discord" || selection?.target !== "lane" || selection.confirmed !== undefined
2010
+ if ((source.route.platform !== "discord" && source.route.platform !== "slack") || selection?.target !== "lane" || selection.confirmed !== undefined
1835
2011
  || source.id !== `picker:${selection.outputId}`) return null;
1836
2012
  const card = this.output(selection.outputId);
1837
2013
  const picker = card?.picker;
@@ -2110,9 +2286,13 @@ export class Store implements StorePort {
2110
2286
 
2111
2287
  recoverDeliveries(): void {
2112
2288
  this.db.transaction(() => {
2289
+ const gateway = this.hasGatewayEffects();
2290
+ // Distinguish a complete receipt already durable at startup from one
2291
+ // arriving after the old send has been quarantined. Never clear a prior hold.
2292
+ if (gateway) this.recoverSlackDeliveries();
2113
2293
  this.db.query("UPDATE outputs SET state = 'uncertain', error = ? WHERE state = 'sending'")
2114
2294
  .run("Delivery interrupted before a durable receipt; reconcile before retrying.");
2115
- if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get()) return;
2295
+ if (!gateway) return;
2116
2296
  const retired = this.db.query<OutputRow, []>(`SELECT * FROM outputs WHERE state = 'uncertain' AND remote_id IS NULL
2117
2297
  AND (${retiredScopeId("id")} OR ${retiredScopeId("source_id")})`).all();
2118
2298
  const attempts = this.db.query<{ output: string; rejected: number }, [string]>(`SELECT
@@ -2137,6 +2317,155 @@ export class Store implements StorePort {
2137
2317
  }).immediate();
2138
2318
  }
2139
2319
 
2320
+ private hasGatewayEffects(): boolean {
2321
+ return this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get() !== null;
2322
+ }
2323
+
2324
+ private gatewaySendAttempts(id: string, limit: number): GatewaySendAttempt[] {
2325
+ return this.db.query<GatewaySendAttempt, [string, number]>(`SELECT id, arguments,
2326
+ CASE WHEN state = 'complete' AND json_valid(result) THEN result END AS result
2327
+ FROM gateway_effects WHERE operation = 'send'
2328
+ AND (CASE WHEN json_valid(arguments) THEN json_extract(arguments, '$[0].id') END) = ? LIMIT ?`).all(id, limit);
2329
+ }
2330
+
2331
+ reconcileSlackOutput(id: string): boolean {
2332
+ return this.db.transaction(() => {
2333
+ const output = this.output(id);
2334
+ return output?.state === "sending" && output.route.platform === "slack"
2335
+ && this.hasGatewayEffects() && this.reconcileSlackPlainPost(output);
2336
+ }).immediate();
2337
+ }
2338
+
2339
+ reconcileSlackJoinedOutput(id: string): boolean {
2340
+ return this.db.transaction(() => {
2341
+ const output = this.output(id);
2342
+ return output?.state === "sending" && this.isSlackJoinedNotice(output)
2343
+ && this.hasGatewayEffects() && this.reconcileSlackJoinedReceipt(output);
2344
+ }).immediate();
2345
+ }
2346
+
2347
+ private recoverSlackDeliveries(): void {
2348
+ const sending = this.db.query<OutputRow, []>(`SELECT * FROM outputs
2349
+ WHERE state = 'sending' AND remote_id IS NULL AND json_extract(route, '$.platform') = 'slack'
2350
+ AND (id IN (source_id || ':workspace', source_id || ':restart-ack')
2351
+ OR EXISTS (SELECT 1 FROM metadata WHERE key = 'kickoff-output:' || outputs.source_id AND value = outputs.id)
2352
+ OR json_type(reply_to, '$.joinedAnswerId') = 'text')
2353
+ ORDER BY sequence`).all();
2354
+ for (const row of sending) {
2355
+ const output = toOutput(row);
2356
+ if (output.id !== `${output.sourceId}:workspace` && this.isSlackJoinedNotice(output)) this.reconcileSlackJoinedReceipt(output);
2357
+ else this.reconcileSlackPlainPost(output);
2358
+ }
2359
+ }
2360
+
2361
+ private reconcileSlackPlainPost(output: OutputRecord): boolean {
2362
+ const source = this.input(output.sourceId);
2363
+ if (output.remoteId !== null || !source || !this.isSlackPlainPost(output, source) || !this.isScopedSlackPlainPost(output, source)) return false;
2364
+ const attempts = this.gatewaySendAttempts(output.id, 2);
2365
+ const receipt = attempts.length === 1 ? attempts[0] : undefined;
2366
+ if (!receipt?.result || !isDeepStrictEqual(JSON.parse(receipt.arguments), [output])) return false;
2367
+ const result = parseGatewaySendResult(receipt.result);
2368
+ // A definitive non-post is terminal for these outputs, even if the
2369
+ // provider asked for a delay. Only a joined link has a retry contract.
2370
+ if (gatewaySendRejection(result)) {
2371
+ this.finishOutput(output.id, "failed", undefined, "Messenger rejected delivery");
2372
+ return true;
2373
+ }
2374
+ const remoteId = gatewaySendSuccess(result);
2375
+ if (remoteId === null || !this.slackPlainPostTimestamp({ ...output, state: "sent", remoteId }, source)) return false;
2376
+ this.finishOutput(output.id, "sent", remoteId);
2377
+ return true;
2378
+ }
2379
+
2380
+ private isScopedSlackPlainPost(output: OutputRecord, source: InputRecord): boolean {
2381
+ if (output.id === `${source.id}:workspace`) {
2382
+ return source.state === "pending" && source.target === null && this.getMeta(`user-source:${source.id}`) === "true";
2383
+ }
2384
+ if (output.id !== `${source.id}:restart-ack`) {
2385
+ return source.state === "pending" && this.getMeta(`kickoff-output:${source.id}`) === output.id
2386
+ && this.db.query(`SELECT 1 FROM lane_sources JOIN lanes ON lanes.id = lane_sources.lane_id
2387
+ WHERE source_id = ? AND lane_id = ? AND lanes.route_key = ?`).get(source.id, source.target, routeKey(source.route)) !== null;
2388
+ }
2389
+ if (source.state !== "done" || source.target !== "main" || source.pickerSelection
2390
+ || this.getMeta(`user-source:${source.id}`) !== "true" || this.getMeta(`handoff-source:${source.id}`) !== null) return false;
2391
+ // This proof only confirms the original acknowledgement. The restart
2392
+ // coordinator still owns checkpoint, native ownership and handoff checks.
2393
+ const saved = this.db.query<{ value: string }, [string]>(`SELECT value FROM metadata
2394
+ WHERE key = 'head:restart-fence' AND json_valid(value)
2395
+ AND value = (SELECT value FROM metadata WHERE key = ?)`).get(`head:restart:${source.id}`);
2396
+ if (!saved) return false;
2397
+ const fence: unknown = JSON.parse(saved.value);
2398
+ return !!fence && typeof fence === "object"
2399
+ && "state" in fence && fence.state === "acknowledging"
2400
+ && "inputId" in fence && fence.inputId === source.id
2401
+ && "ackOutputId" in fence && fence.ackOutputId === output.id
2402
+ && "requestId" in fence && typeof fence.requestId === "string" && !!fence.requestId
2403
+ && "ownerPid" in fence && typeof fence.ownerPid === "number" && Number.isSafeInteger(fence.ownerPid) && fence.ownerPid > 0
2404
+ && "sessionId" in fence && typeof fence.sessionId === "string" && !!fence.sessionId
2405
+ && "sessionFile" in fence && typeof fence.sessionFile === "string" && !!fence.sessionFile
2406
+ && (("stopBoundary" in fence ? fence.stopBoundary : null) ?? null) === this.getMeta("gateway:operator-stop");
2407
+ }
2408
+
2409
+ private isSlackPlainPost(output: OutputRecord, source: InputRecord): boolean {
2410
+ return routeKey(source.route) === routeKey(output.route) && Boolean(output.text.trim())
2411
+ && !output.replyTo && !output.editOf && !output.picker && !output.resultAttachment && !output.status;
2412
+ }
2413
+
2414
+ private slackPlainPostTimestamp(output: OutputRecord, source: InputRecord): string | null {
2415
+ if (!this.isSlackPlainPost(output, source)) return null;
2416
+ const post = slackOutputTimestamp(this, output);
2417
+ const first = output.remoteId;
2418
+ // Opening handoffs copy the owner's message ID but change the route. Only
2419
+ // the recorded origin can tell whether that ID belongs to this Slack clock.
2420
+ const originId = this.getMeta(`handoff-source:${source.id}`);
2421
+ const origin = originId === null ? source : this.input(originId);
2422
+ if (!origin) return null;
2423
+ const sameSlackChannel = origin.route.platform === "slack" && origin.route.accountId === output.route.accountId
2424
+ && origin.route.channelId === output.route.channelId;
2425
+ if (!post || !first || compareMessageIds("slack", first, "0.000000") !== 1
2426
+ || sameSlackChannel && origin.messageId !== null && compareMessageIds("slack", first, origin.messageId) !== 1
2427
+ || source.route.threadId !== null && compareMessageIds("slack", first, source.route.threadId) !== 1) return null;
2428
+ return post;
2429
+ }
2430
+
2431
+ private reconcileSlackJoinedReceipt(output: OutputRecord): boolean {
2432
+ const { at, count, priorAttemptIds } = this.slackJoinedRetry(output.id);
2433
+ if (!priorAttemptIds || priorAttemptIds.length !== count || count > SLACK_JOINED_RETRY_LIMIT) return false;
2434
+ const attempts = this.gatewaySendAttempts(output.id, count + 2);
2435
+ if (attempts.length !== count + 1) return false;
2436
+ const current = attempts.find(attempt => !priorAttemptIds.includes(attempt.id));
2437
+ if (!current?.result || priorAttemptIds.some(id => !attempts.some(attempt => attempt.id === id))) return false;
2438
+ for (const attempt of attempts) {
2439
+ if (!attempt.result || !isDeepStrictEqual(JSON.parse(attempt.arguments), [output])) return false;
2440
+ if (attempt !== current && gatewaySendRejection(parseGatewaySendResult(attempt.result))?.retryAfterMs === undefined) return false;
2441
+ }
2442
+
2443
+ const result = parseGatewaySendResult(current.result);
2444
+ const remoteId = gatewaySendSuccess(result);
2445
+ if (remoteId !== null) {
2446
+ const reply = output.replyTo;
2447
+ const root = output.route.threadId;
2448
+ if (!reply?.joinedAnswerId || !/^\d{1,20}\.\d{6}$/u.test(remoteId)
2449
+ || compareMessageIds("slack", remoteId, "0.000000") !== 1
2450
+ || compareMessageIds("slack", remoteId, reply.messageId) !== 1
2451
+ || compareMessageIds("slack", remoteId, reply.joinedAnswerId) !== 1
2452
+ || root !== null && compareMessageIds("slack", remoteId, root) !== 1) return false;
2453
+ this.finishOutput(output.id, "sent", remoteId);
2454
+ return true;
2455
+ }
2456
+
2457
+ const rejection = gatewaySendRejection(result);
2458
+ if (!rejection) return false;
2459
+ if (rejection.retryAfterMs !== undefined && count < SLACK_JOINED_RETRY_LIMIT) {
2460
+ const completed = this.getMeta(`${SLACK_JOINED_REJECTED_AT}${current.id}`);
2461
+ const completedAt = completed !== null && /^\d+$/u.test(completed) ? Number(completed) : NaN;
2462
+ if (!Number.isSafeInteger(completedAt) || completedAt < (at ?? 0)) return false;
2463
+ if (this.recordSlackJoinedRetry(output.id, count, completedAt, rejection.retryAfterMs)) return true;
2464
+ }
2465
+ this.finishOutput(output.id, "failed", undefined, "Gateway recorded definitive non-delivery");
2466
+ return true;
2467
+ }
2468
+
2140
2469
  getMeta(key: string): string | null {
2141
2470
  return (this.db.query("SELECT value FROM metadata WHERE key = ?").get(key) as { value: string } | null)?.value ?? null;
2142
2471
  }