omp-superagent 0.1.13 → 0.1.16

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 (78) hide show
  1. package/DESIGN.md +8 -5
  2. package/THIRD_PARTY_NOTICES.md +6 -0
  3. package/assets/architecture-dark.svg +4 -4
  4. package/assets/architecture.ko-dark.svg +4 -4
  5. package/assets/architecture.ko.svg +4 -4
  6. package/assets/architecture.mmd +5 -5
  7. package/assets/architecture.svg +4 -4
  8. package/config.example.json +1 -0
  9. package/docs/OPERATIONS.en.md +80 -23
  10. package/docs/OPERATIONS.md +73 -18
  11. package/docs/design/execution.md +180 -43
  12. package/docs/design/messaging.md +62 -10
  13. package/docs/releases/0.1.15.md +13 -0
  14. package/docs/releases/0.1.16.md +9 -0
  15. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  16. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  17. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  18. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  19. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  20. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  21. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  22. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  23. package/package.json +6 -3
  24. package/scripts/prepare-worker-memory.ts +37 -0
  25. package/skills/head/SKILL.md +29 -47
  26. package/skills/head/references/routing.md +35 -16
  27. package/skills/head/references/supervision.md +10 -14
  28. package/skills/lane/SKILL.md +14 -16
  29. package/skills/lane/references/workflow.md +14 -27
  30. package/src/cli.ts +56 -56
  31. package/src/config/config.ts +14 -0
  32. package/src/contracts.ts +38 -30
  33. package/src/cron/cron-jobs.ts +4 -3
  34. package/src/cron/cron-pr-intake.ts +1 -2
  35. package/src/extension.ts +69 -24
  36. package/src/gateway/gateway-client.ts +24 -15
  37. package/src/group/group-runner.ts +3 -2
  38. package/src/group-runner-extension.ts +7 -3
  39. package/src/host-extension.ts +109 -2
  40. package/src/host-sdk-helper.ts +6 -1
  41. package/src/lane/decision-tool.ts +2 -3
  42. package/src/lane/lane-report.ts +8 -30
  43. package/src/lane/lane-rows.ts +1 -1
  44. package/src/lane/workflow.ts +44 -3
  45. package/src/lane-extension.ts +5 -46
  46. package/src/messaging/discord-context.ts +8 -6
  47. package/src/messaging/discord-work-thread.ts +36 -0
  48. package/src/omp/host-protocol.ts +4 -3
  49. package/src/omp/host.ts +24 -7
  50. package/src/omp/managed-super.ts +43 -27
  51. package/src/omp/native-sessions.ts +12 -0
  52. package/src/omp/worker-memory-import.ts +410 -0
  53. package/src/omp/worker-memory-sdk.ts +8 -0
  54. package/src/operator/setup.ts +8 -13
  55. package/src/pr/pr-github-schema.ts +9 -0
  56. package/src/pr/pr-github.ts +6 -2
  57. package/src/pr/pr-intake-automation.ts +11 -8
  58. package/src/pr/pr-intake-fix.ts +2 -5
  59. package/src/pr/pr-intake-review.ts +7 -7
  60. package/src/routing/topic-history.ts +2 -2
  61. package/src/runtime/controller.ts +720 -468
  62. package/src/runtime/head-recovery.ts +7 -7
  63. package/src/runtime/head-superstack.ts +83 -0
  64. package/src/runtime/result-attachments.ts +3 -1
  65. package/src/runtime/worker-memory.ts +156 -0
  66. package/src/storage/deferred-routing.ts +1 -7
  67. package/src/storage/store.ts +465 -372
  68. package/src/worker/worker-host.ts +3 -2
  69. package/src/worker/worker-ledger.ts +20 -11
  70. package/src/worker/worker-memory-page.ts +83 -0
  71. package/src/worker/worker-memory-proofs.ts +260 -0
  72. package/src/worker/worker-memory-source.ts +305 -0
  73. package/src/worker/worker-memory-storage.ts +130 -0
  74. package/src/worker/worker-profile.ts +2 -0
  75. package/src/worker/worker-repository.ts +92 -7
  76. package/src/worker/worker-request.ts +1 -0
  77. package/src/worker/worker-service.ts +25 -8
  78. package/src/worker/worker-wire.ts +20 -6
@@ -198,10 +198,11 @@ export function headRecoveryEvidence(entries: unknown[], owner: Pick<HeadRecover
198
198
  const matches = (entry: Record<string, unknown>, type: string) => entry.type === "custom" && entry.customType === type
199
199
  && object(entry.data).sessionId === owner.sessionId && object(entry.data).sessionFile === owner.sessionFile;
200
200
  const receipts = slice.filter(entry => matches(entry, "rpc_prompt_result"));
201
- const receiptsForRequest = receipts.filter(entry => object(object(entry.data).frame).id === owner.requestId);
202
- if (receiptsForRequest.length !== 1 || receipts.length !== 1) return null;
203
- const receipt = receiptsForRequest[0]!;
204
- const frame = object(object(receipt.data).frame);
201
+ if (receipts.length !== 1) return null;
202
+ const [receipt] = receipts;
203
+ const receiptData = object(receipt.data);
204
+ const frame = object(receiptData.frame);
205
+ if (frame.id !== owner.requestId) return null;
205
206
  const starts = slice.filter(entry => matches(entry, "rpc_agent_start"));
206
207
  const latestStart = starts.at(-1);
207
208
  const latestStartIndex = latestStart ? slice.indexOf(latestStart) : -1;
@@ -215,12 +216,12 @@ export function headRecoveryEvidence(entries: unknown[], owner: Pick<HeadRecover
215
216
  const latestAssistant = assistants.at(-1);
216
217
  const latestRunStatus = object(latestAssistant?.message).stopReason;
217
218
  let outcome: "done" | "cancelled" | undefined;
218
- const receiptData = object(receipt.data);
219
219
  const startData = object(latestStart?.data);
220
+ const receiptIndex = slice.indexOf(receipt);
220
221
  const receiptAfterStart = typeof receiptData.runOrdinal === "number" && typeof startData.runOrdinal === "number"
221
222
  && receiptData.hostPid === startData.hostPid
222
223
  ? receiptData.runOrdinal >= startData.runOrdinal
223
- : slice.indexOf(receipt) > latestStartIndex;
224
+ : receiptIndex > latestStartIndex;
224
225
  if (frame.status === "aborted" && (!latestStart || receiptAfterStart)) outcome = "cancelled";
225
226
  if (frame.status === "completed") {
226
227
  if (frame.agentInvoked === false && !latestStart) outcome = "done";
@@ -229,7 +230,6 @@ export function headRecoveryEvidence(entries: unknown[], owner: Pick<HeadRecover
229
230
  }
230
231
  const error = object(frame.error);
231
232
  const failedAt = typeof receipt.timestamp === "string" ? Date.parse(receipt.timestamp) : NaN;
232
- const receiptIndex = slice.indexOf(receipt);
233
233
  const sameRun = typeof receiptData.hostPid === "number" && Number.isSafeInteger(receiptData.hostPid)
234
234
  && receiptData.hostPid > 0 && typeof receiptData.instanceKey === "string" && receiptData.instanceKey !== ""
235
235
  && typeof receiptData.runOrdinal === "number" && Number.isSafeInteger(receiptData.runOrdinal) && receiptData.runOrdinal > 0
@@ -0,0 +1,83 @@
1
+ import type { Inbound } from "../contracts";
2
+ import { matchesWrittenCommand, messengerCommandText } from "../messaging/messenger-commands";
3
+ import { record } from "./native-frames";
4
+
5
+ // Native command and branch journal contract from omp-superkit 12d19ec.
6
+ const selector = /^\s*(\/?superstack)(?=\s|$)/i;
7
+ export const headSuperstackTaskPrefix = "superstack\n\n";
8
+
9
+ type HeadSuperstackReceipt =
10
+ | { readonly kind: "enable" | "off" | "held" }
11
+ | { readonly kind: "task"; readonly start: number; readonly view: "written" | "telegram" };
12
+
13
+ // This runs only on original intake. For a task, pin an offset into one of
14
+ // the immutable source views rather than storing another copy of its text.
15
+ export function admitHeadSuperstack(input: Inbound, task: string): HeadSuperstackReceipt | undefined {
16
+ const match = selector.exec(task);
17
+ if (!match || !matchesWrittenCommand(input)) return;
18
+ const written = messengerCommandText(input);
19
+ if (!written.endsWith(task)) return;
20
+ const wrapperLength = written.length - task.length;
21
+ const start = wrapperLength + match[0].length;
22
+ const args = written.slice(start).trim();
23
+ const view = input.route.platform === "telegram" ? input.routingText : written;
24
+ const projected = view !== written;
25
+ if (projected) {
26
+ // An exposed second token on the same line cannot corroborate a masked
27
+ // first token. Telegram only attests the first written slash command.
28
+ const sameLine = /^[^\r\n]*/u.exec(written.slice(start))?.[0];
29
+ const attestedSlash = wrapperLength === 0 && match[1]?.startsWith("/") && input.telegramProtectedCommand === false;
30
+ if (view === undefined || !view.startsWith(written.slice(0, start)) || !/^(?:\s|$)/u.test(view.slice(start))
31
+ || (!attestedSlash && match[1] && sameLine?.includes(match[1]))) return { kind: "held" };
32
+ }
33
+ if (args === "" || args === "off")
34
+ return view?.slice(start).trim() === args ? { kind: args ? "off" : "enable" } : { kind: "held" };
35
+ if (!view?.slice(start).trim()) return { kind: "held" };
36
+ return { kind: "task", start, view: projected ? "telegram" : "written" };
37
+ }
38
+
39
+ export function recordedHeadSuperstack(value: string | null): HeadSuperstackReceipt | null {
40
+ if (value === null) return null;
41
+ const { kind, start, view } = record(JSON.parse(value));
42
+ if (kind === "task" && typeof start === "number" && Number.isSafeInteger(start) && start > 0
43
+ && (view === "written" || view === "telegram")) return { kind, start, view };
44
+ if (kind === "enable" || kind === "off") return { kind };
45
+ return { kind: "held" };
46
+ }
47
+
48
+ export function headSuperstackTaskText(input: Inbound, task: Extract<HeadSuperstackReceipt, { kind: "task" }>): string | undefined {
49
+ return (task.view === "telegram" ? input.routingText : messengerCommandText(input))?.slice(task.start).trim();
50
+ }
51
+
52
+ export function advertisesSuperstack(value: unknown): boolean {
53
+ const { commands } = record(value);
54
+ return Array.isArray(commands) && commands.map(record).some(command =>
55
+ command.name === "superstack" && command.source === "extension"
56
+ && command.description === "Enable branch-local skill routing for an optional task, or use off to disable it");
57
+ }
58
+
59
+ export function superstackBranchEnabled(value: unknown): boolean | undefined {
60
+ const { entries, leafId } = record(value);
61
+ if (!Array.isArray(entries) || (leafId !== null && typeof leafId !== "string")) return undefined;
62
+ const byId = new Map(entries.map(record).map(entry => [entry.id, entry]));
63
+ const visited = new Set<string>();
64
+ let id = leafId;
65
+ while (typeof id === "string" && !visited.has(id)) {
66
+ visited.add(id);
67
+ const entry = byId.get(id);
68
+ if (!entry) return undefined;
69
+ if (entry.type === "custom" && entry.customType === "omp-superstack:state")
70
+ return typeof entry.data === "boolean" ? entry.data : undefined;
71
+ if (entry.parentId !== null && typeof entry.parentId !== "string") return undefined;
72
+ id = entry.parentId;
73
+ }
74
+ return id === null ? false : undefined;
75
+ }
76
+
77
+ export function superstackControlOutcome(id: string, wanted: boolean, enabled: boolean | undefined) {
78
+ if (enabled === undefined) return { state: "uncertain",
79
+ text: `Superstack 설정을 확인하지 못했습니다. 명령을 다시 보내지 않았고 다음 HEAD 요청을 보류했습니다. 원래 세션을 확인하거나 /resolve ${id} 로 보류를 종료하세요.` } as const;
80
+ if (enabled !== wanted) return { state: "cancelled",
81
+ text: "HEAD 브랜치에 요청한 Superstack 설정이 적용되지 않았습니다. 모델 작업은 시작하지 않았습니다." } as const;
82
+ return { state: "done", text: `현재 HEAD 세션 브랜치의 Superstack 설정을 ${enabled ? "켰습니다" : "껐습니다"}. 모델 작업은 시작하지 않았습니다.` } as const;
83
+ }
@@ -5,6 +5,7 @@ import { getAgentDbPath } from "@oh-my-pi/pi-utils/dirs";
5
5
  import { authorizeRoute, type Config } from "../config/config";
6
6
  import type { InputRecord, Route, StorePort } from "../contracts";
7
7
  import { messengerCommandText, telegramCommandBlocked } from "../messaging/messenger-commands";
8
+ import { discordWorkThreadSource } from "../messaging/discord-work-thread";
8
9
  import { discardResultAttachment, isOriginalAttachmentMessage, pruneResultAttachments, readResultAttachmentIntent,
9
10
  readResultAttachmentStart, requestedResultPath, ResultAttachmentError, stageResultAttachment,
10
11
  type ResultAttachmentIntent, type ResultAttachmentPayload } from "../messaging/result-attachment";
@@ -56,7 +57,8 @@ export class ResultAttachments {
56
57
  if (route.authorityId !== this.config[route.platform]?.ownerId) {
57
58
  throw new ResultAttachmentError("Result attachments require the configured messenger owner");
58
59
  }
59
- if (!authorizeRoute(this.config, route)) throw new Error("Unauthorized messenger route");
60
+ if (!authorizeRoute(this.config, route) && !discordWorkThreadSource(this.config, this.store, route))
61
+ throw new Error("Unauthorized messenger route");
60
62
  }
61
63
 
62
64
  queue(run: AttachmentRun, intent: ResultAttachmentIntent, admission: {
@@ -0,0 +1,156 @@
1
+ import { createHash } from "node:crypto";
2
+ import { join } from "node:path";
3
+ import { Type } from "@sinclair/typebox/type";
4
+ import { Value } from "@sinclair/typebox/value";
5
+ import type { Lane, StorePort } from "../contracts";
6
+ import type { prepareWorkerMemoryImport } from "../omp/worker-memory-import";
7
+ import { parseWorkerMemoryPage } from "../worker/worker-memory-page";
8
+ import { workerMemoryCheckoutStamp, workerMemoryRepositoryMatches } from "../worker/worker-repository";
9
+ import type { WorkerProbe, WorkerRegistration } from "../worker/worker-wire";
10
+ import { successful, type RuntimeHost } from "./native-frames";
11
+
12
+ type Destination = NonNullable<ReturnType<typeof prepareWorkerMemoryImport>>;
13
+ export type MemoryDestination = (headId: string, headFile: string, cwd: string) => Destination | undefined;
14
+ const digest = (parts: readonly unknown[]) => createHash("sha256").update(JSON.stringify(parts)).digest("hex");
15
+ const statusKey = (id: string) => `worker-memory:status:${id}`;
16
+ const changeStamp = /^[a-f0-9]{64}$/;
17
+ const count = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
18
+ const observation = { generation: count, at: count };
19
+ const exact = { additionalProperties: false };
20
+ const pendingIndex = new WeakMap<StorePort, Map<string, string>>();
21
+ const report = Type.Union([
22
+ Type.Object({ ...observation, status: Type.Literal("unavailable") }, exact),
23
+ Type.Object({ ...observation, status: Type.Literal("unchanged") }, exact),
24
+ Type.Object({ ...observation, status: Type.Literal("checked"), cursor: count, records: count,
25
+ inserted: count, skipped: count, rejected: count, lexical: count, indexed: count, disabled: count, pending: count, deferred: count }, exact),
26
+ ]);
27
+
28
+ interface ScanCursor { after: number; start?: string; unchanged?: string }
29
+ function scanCursor(saved: string | null): ScanCursor {
30
+ if (!saved) return { after: 0 };
31
+ const cursor: ScanCursor = JSON.parse(saved);
32
+ if (!Number.isSafeInteger(cursor.after) || cursor.after < 0
33
+ || cursor.start !== undefined && !changeStamp.test(cursor.start)
34
+ || cursor.unchanged !== undefined && (!changeStamp.test(cursor.unchanged) || cursor.after !== 0))
35
+ throw new Error("Invalid memory scan cursor");
36
+ return cursor;
37
+ }
38
+
39
+ export function workerMemoryStatus(store: StorePort, laneId: string) {
40
+ const raw = store.getMeta(statusKey(laneId));
41
+ if (!raw) return null;
42
+ if (raw.length <= 512) {
43
+ try {
44
+ const status: unknown = JSON.parse(raw);
45
+ if (Value.Check(report, status)) {
46
+ if (status.status === "checked" && status.pending && pendingIndex.get(store)?.get(laneId) !== raw)
47
+ return { ...status, pending: 0, deferred: status.deferred + status.pending };
48
+ return status;
49
+ }
50
+ } catch (error) { if (!(error instanceof SyntaxError)) throw error; }
51
+ }
52
+ return { status: "unavailable" } as const;
53
+ }
54
+
55
+ /** Use the same checkout proof before redirecting a fresh worker bank and before importing it. */
56
+ export async function verifyMemoryCheckout(lane: Pick<Lane, "cwd" | "repoRoot" | "remote">) {
57
+ try {
58
+ if (!lane.remote || !lane.repoRoot) return;
59
+ const checkout = { ...lane.remote, repoRoot: lane.repoRoot, gitDir: join(lane.repoRoot, ".git") };
60
+ const stamp = workerMemoryCheckoutStamp(lane.cwd, checkout);
61
+ if (!stamp || !await workerMemoryRepositoryMatches(lane.cwd, checkout)) return;
62
+ return () => workerMemoryCheckoutStamp(lane.cwd, checkout) === stamp;
63
+ } catch (error) {
64
+ if (!(error instanceof Error)) throw error;
65
+ // Optional private storage must never prevent a normal remote launch.
66
+ return undefined;
67
+ }
68
+ }
69
+
70
+ /** A read of the already attached owner, never an open, resume, model turn or SSH path request. */
71
+ export async function pullWorkerMemory(store: StorePort, lane: Pick<Lane,
72
+ "id" | "generation" | "cwd" | "repoRoot" | "remote" | "pid" | "sessionId" | "sessionFile">, source: {
73
+ connection: Pick<RuntimeHost, "request">;
74
+ registration: WorkerRegistration;
75
+ lookup(): Promise<WorkerRegistration>;
76
+ probe(reg: WorkerRegistration): Promise<WorkerProbe>;
77
+ destination(): Destination | undefined;
78
+ current(): boolean;
79
+ confirmIdleHead(): Promise<boolean>;
80
+ ownsStatus(): boolean;
81
+ canIndex(): boolean;
82
+ }) {
83
+ const remote = lane.remote;
84
+ if (!remote || !lane.sessionId || !lane.repoRoot || join(lane.repoRoot, remote.subdir) !== lane.cwd) return;
85
+ try {
86
+ const dest = source.destination();
87
+ if (!dest || !source.current()) return;
88
+ const validEnrollment = (reg: WorkerRegistration) => reg.destination === source.registration.destination
89
+ && reg.identityFile === source.registration.identityFile && reg.description.workerId === remote.workerId
90
+ && reg.description.stateDir === remote.stateDir && reg.description.repos.some(repo => repo.id === remote.repoId
91
+ && source.registration.description.repos.some(saved => saved.id === repo.id && saved.cwd === repo.cwd));
92
+ const reg = await source.lookup();
93
+ if (!validEnrollment(reg) || !source.current()) return;
94
+ const [checkoutUnchanged, owner] = await Promise.all([verifyMemoryCheckout(lane), source.probe(reg)]);
95
+ if (!checkoutUnchanged?.() || !source.current()
96
+ || owner.memorySyncVersion !== 1 || owner.uncertain || !owner.socket || !owner.pidAlive || !owner.ownerAlive
97
+ || !owner.sessionFile || owner.pid !== lane.pid || owner.sessionId !== lane.sessionId) return;
98
+ const origin = digest([remote.workerId, remote.stateDir, remote.repoId, remote.revision, remote.subdir,
99
+ lane.id, lane.cwd, lane.sessionId, lane.sessionFile]);
100
+ const key = `worker-memory:cursor:${digest([dest.namespace, origin])}`;
101
+ const { after, start, unchanged } = scanCursor(store.getMeta(key));
102
+ const reply = await source.connection.request({ type: "get_worker_memory", after, ...(unchanged && { unchanged }) });
103
+ if (!source.current()) return;
104
+ const page = parseWorkerMemoryPage(successful(reply, "get_worker_memory"), after);
105
+ if (!validEnrollment(await source.lookup()) || !source.current()
106
+ || !await source.confirmIdleHead()) return;
107
+ const currentDest = source.destination();
108
+ if (!currentDest || currentDest.namespace !== dest.namespace || !source.current() || !checkoutUnchanged()) return;
109
+ if (unchanged === page.stamp && !after && !page.next && !page.records.length) {
110
+ // Keep the last actual index readback; an empty stamp response is not another vector check.
111
+ const previous = workerMemoryStatus(store, lane.id);
112
+ if (previous?.status !== "checked" || previous.generation !== lane.generation)
113
+ store.tryWorkerMemoryMeta(statusKey(lane.id), JSON.stringify({ generation: lane.generation, at: Date.now(), status: "unchanged" }));
114
+ return;
115
+ }
116
+ // Commit through the original live SDK capability. A same-path replacement
117
+ // or change in its native settings is not the policy that authorized the read.
118
+ const receiptKey = (id: string) => `worker-memory:imported:${digest([dest.receiptNamespace, id])}`;
119
+ const result = dest.importPage(page.records, origin, {
120
+ seen: id => store.getMeta(receiptKey(id)) === "1",
121
+ mark: ids => {
122
+ if (!store.tryWorkerMemoryMeta(ids.map(receiptKey), "1")) throw new Error("Memory receipts not reserved");
123
+ },
124
+ }, () => source.canIndex() && checkoutUnchanged());
125
+ if (result === undefined) return;
126
+ const first = after === 0 ? page.stamp : start;
127
+ const cursor: ScanCursor = { after: page.next };
128
+ if (first === page.stamp) {
129
+ if (page.next === 0) cursor.unchanged = first;
130
+ else cursor.start = first;
131
+ }
132
+ if (!store.tryWorkerMemoryMeta(key, JSON.stringify(cursor))) return;
133
+ const { confirmation, ...counts } = result;
134
+ const status = { generation: lane.generation, at: Date.now(), status: "checked",
135
+ cursor: page.next, records: page.records.length, ...counts };
136
+ const receipt = JSON.stringify(status);
137
+ store.tryWorkerMemoryMeta(statusKey(lane.id), receipt);
138
+ if (!confirmation) return;
139
+ const tasks = pendingIndex.get(store) ?? new Map<string, string>();
140
+ pendingIndex.set(store, tasks);
141
+ tasks.set(lane.id, receipt);
142
+ // Native indexing may finish after eviction. A later page, a different native
143
+ // generation, or stopped HEAD owns its own status; don't hold release to update it.
144
+ void confirmation.then(observed => {
145
+ if (observed && source.ownsStatus() && store.getMeta(statusKey(lane.id)) === receipt)
146
+ store.tryWorkerMemoryMeta(statusKey(lane.id), JSON.stringify({ ...status, ...observed }));
147
+ }).catch(() => { /* A lost readback is not confirmation of a vector. */ }).finally(() => {
148
+ if (tasks.get(lane.id) === receipt) tasks.delete(lane.id);
149
+ });
150
+ } catch {
151
+ // Neither worker error strings nor SDK diagnostics belong in logs, the ledger or a model turn.
152
+ if (source.current()) store.tryWorkerMemoryMeta(statusKey(lane.id), JSON.stringify({
153
+ generation: lane.generation, at: Date.now(), status: "unavailable",
154
+ }));
155
+ }
156
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Database } from "bun:sqlite";
2
- import { deferredRecoveryCandidate, physicalRouteKey, routingConversation, type DeferredRoutingPort, type Inbound, type Lane, type Route } from "../contracts";
2
+ import { deferredRecoveryCandidate, physicalRouteKey, routingConversation, type DeferredRoutingPort, type Inbound, type Lane } from "../contracts";
3
3
 
4
4
  const LEGACY_QUEUE = "intake:deferred-routing";
5
5
  const SCHEMA = `
@@ -132,12 +132,6 @@ export class DeferredRoutingQueue implements DeferredRoutingPort {
132
132
  this.db.query("DELETE FROM deferred_routing WHERE id = ?").run(id);
133
133
  }
134
134
 
135
- hasOnRoute(route: Route, exceptId: string): boolean {
136
- return this.db.query(`
137
- SELECT 1 FROM deferred_routing WHERE physical_route = ? AND id <> ? LIMIT 1
138
- `).get(physicalRouteKey(route), exceptId) !== null;
139
- }
140
-
141
135
  choices(input: Pick<Inbound, "id" | "route" | "receivedAt">, deadline: number): Iterable<DeferredChoiceRow> {
142
136
  return this.db.query<DeferredChoiceRow, [string, number, number, string]>(`
143
137
  SELECT id, json_extract(data, '$.text') AS text, message_id AS messageId,