omp-superagent 0.1.6 → 0.1.8
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.
- package/DESIGN.md +36 -20
- package/README.ko.md +140 -33
- package/README.md +165 -41
- package/THIRD_PARTY_NOTICES.md +9 -7
- package/config.example.json +3 -1
- package/docs/OPERATIONS.md +395 -157
- package/docs/design/execution.md +156 -22
- package/docs/design/messaging.md +258 -52
- package/docs/discord-voice.md +8 -4
- package/docs/releases/0.1.7.md +25 -0
- package/docs/releases/0.1.8.md +21 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +9 -9
- package/scripts/ci.ts +4 -4
- package/scripts/test-omp.sh +2 -1
- package/skills/head/SKILL.md +26 -5
- package/skills/head/references/routing.md +68 -33
- package/skills/head/references/supervision.md +20 -4
- package/skills/lane/references/workflow.md +16 -7
- package/src/board.ts +5 -3
- package/src/cli.ts +161 -19
- package/src/config.ts +21 -1
- package/src/contracts.ts +63 -8
- package/src/cron-jobs.ts +443 -19
- package/src/cron-pr-intake.ts +257 -0
- package/src/discord-markdown.ts +350 -123
- package/src/extension.ts +78 -13
- package/src/gateway-client.ts +8 -2
- package/src/head-quota.ts +80 -0
- package/src/head-recovery.ts +40 -1
- package/src/host-extension.ts +122 -4
- package/src/host-inventory-manifest.ts +2 -2
- package/src/host-protocol.ts +11 -0
- package/src/host-sdk-helper.ts +121 -12
- package/src/host.ts +175 -57
- package/src/installed-omp.ts +116 -4
- package/src/lane-rows.ts +44 -4
- package/src/lane-watch.ts +339 -0
- package/src/managed-memory-helper.ts +13 -10
- package/src/managed-memory.ts +62 -27
- package/src/managed-ulw-probe.ts +75 -20
- package/src/managed-ulw.ts +174 -21
- package/src/messenger-command-catalog.json +2 -2
- package/src/native-launch-profile.ts +4 -2
- package/src/native-presets.ts +32 -5
- package/src/native-sessions.ts +3 -1
- package/src/native-settings.ts +47 -9
- package/src/observation-request.ts +23 -0
- package/src/omp-usage.ts +254 -36
- package/src/pr-github-schema.ts +5 -1
- package/src/pr-github.ts +68 -19
- package/src/pr-intake-automation.ts +316 -0
- package/src/pr-intake-comment.ts +226 -0
- package/src/pr-intake-fix.ts +233 -0
- package/src/pr-intake-github.ts +480 -0
- package/src/pr-intake-material.ts +230 -0
- package/src/pr-intake-mode.ts +59 -0
- package/src/pr-intake-review.ts +397 -0
- package/src/pr-intake-tree.ts +69 -0
- package/src/pr-intake-work.ts +29 -0
- package/src/pr-watch.ts +91 -32
- package/src/runtime.ts +2702 -391
- package/src/setup-judge.ts +1 -1
- package/src/setup.ts +12 -16
- package/src/store.ts +429 -86
- package/src/topic-history.ts +243 -47
- package/src/worker-checkout.ts +106 -0
- package/src/worker-destination.ts +10 -0
- package/src/worker-doctor.ts +66 -0
- package/src/worker-enrollment.ts +165 -0
- package/src/worker-host.ts +180 -0
- package/src/worker-ledger.ts +188 -0
- package/src/worker-placement.ts +78 -0
- package/src/worker-profile.ts +274 -0
- package/src/worker-registration.ts +288 -0
- package/src/worker-repository.ts +233 -0
- package/src/worker-request.ts +74 -0
- package/src/worker-service.ts +230 -0
- package/src/worker-stdio.ts +61 -0
- package/src/worker-trust.ts +36 -0
- package/src/worker-wire.ts +204 -0
- package/src/workflow.ts +81 -32
- package/src/setup-memory.ts +0 -21
package/src/store.ts
CHANGED
|
@@ -24,25 +24,28 @@ import { existsSync, mkdirSync, realpathSync } from "node:fs";
|
|
|
24
24
|
import { basename, dirname, join, resolve } from "node:path";
|
|
25
25
|
import { isDeepStrictEqual } from "node:util";
|
|
26
26
|
import {
|
|
27
|
-
HEAD_MODEL_CONTROL, physicalRoute, physicalRouteKey, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
|
|
27
|
+
DEFERRED_ROUTING_META, HEAD_MODEL_CONTROL, physicalRoute, physicalRouteKey, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
|
|
28
28
|
type ActiveInputState, type KickoffHold, type OutputRecord, type Route, type StorePort, type WorkflowActivation,
|
|
29
29
|
type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect,
|
|
30
30
|
} from "./contracts.ts";
|
|
31
31
|
import type { ApprovalResolution } from "./contracts";
|
|
32
32
|
import { captureDecision, resolveDecision } from "./decisions";
|
|
33
33
|
import { isLaneModel, laneModelArgument, sameLaneModel } from "./lane-models";
|
|
34
|
-
import { readLaneRows, toLane } from "./lane-rows";
|
|
35
|
-
import { workflowChoice } from "./workflow";
|
|
34
|
+
import { laneData, readLaneRows, toLane, type LaneRow } from "./lane-rows";
|
|
35
|
+
import { storedWorkflowName, workflowChoice } from "./workflow";
|
|
36
36
|
import { laneWaitKey, type LaneReport } from "./lane-report";
|
|
37
|
+
import { laneWatchReplySource } from "./lane-watch";
|
|
37
38
|
import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "./topic-request";
|
|
38
39
|
import type { CronUpdate } from "./cron-jobs";
|
|
40
|
+
import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "./pr-intake-work";
|
|
41
|
+
import type { ReviewRound } from "./pr-intake-review";
|
|
39
42
|
|
|
40
43
|
const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
|
|
41
44
|
|
|
42
45
|
const SCHEMA = `
|
|
43
46
|
CREATE TABLE IF NOT EXISTS lanes (
|
|
44
47
|
id TEXT PRIMARY KEY, route_key TEXT NOT NULL UNIQUE, generation INTEGER NOT NULL,
|
|
45
|
-
data TEXT NOT NULL
|
|
48
|
+
data TEXT NOT NULL, remote TEXT
|
|
46
49
|
);
|
|
47
50
|
CREATE TABLE IF NOT EXISTS inputs (
|
|
48
51
|
sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
|
|
@@ -55,6 +58,8 @@ const SCHEMA = `
|
|
|
55
58
|
CREATE INDEX IF NOT EXISTS inputs_active_order ON inputs(sequence) WHERE ${ACTIVE_INPUTS};
|
|
56
59
|
CREATE INDEX IF NOT EXISTS inputs_target_active_order ON inputs(target, sequence) WHERE ${ACTIVE_INPUTS};
|
|
57
60
|
CREATE INDEX IF NOT EXISTS inputs_state_active_order ON inputs(state, sequence) WHERE ${ACTIVE_INPUTS};
|
|
61
|
+
CREATE INDEX IF NOT EXISTS inputs_lane_run_order ON inputs(target, sequence)
|
|
62
|
+
WHERE request_id IS NOT NULL AND target <> 'main';
|
|
58
63
|
CREATE INDEX IF NOT EXISTS inputs_message_id ON inputs(json_extract(data, '$.messageId'))
|
|
59
64
|
WHERE json_type(data, '$.messageId') = 'text';
|
|
60
65
|
CREATE TABLE IF NOT EXISTS lane_sources (
|
|
@@ -63,10 +68,11 @@ const SCHEMA = `
|
|
|
63
68
|
);
|
|
64
69
|
CREATE TABLE IF NOT EXISTS outputs (
|
|
65
70
|
sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
|
|
66
|
-
source_id TEXT NOT NULL, route TEXT NOT NULL, text TEXT NOT NULL,
|
|
71
|
+
source_id TEXT NOT NULL, route TEXT NOT NULL, physical_route TEXT, text TEXT NOT NULL,
|
|
67
72
|
state TEXT NOT NULL DEFAULT 'pending'
|
|
68
73
|
CHECK(state IN ('pending','sending','sent','uncertain','failed')),
|
|
69
|
-
remote_id TEXT, error TEXT, reply_to TEXT, picker TEXT, result_attachment TEXT
|
|
74
|
+
remote_id TEXT, error TEXT, reply_to TEXT, picker TEXT, result_attachment TEXT, edit_of TEXT,
|
|
75
|
+
status INTEGER NOT NULL DEFAULT 0
|
|
70
76
|
);
|
|
71
77
|
CREATE INDEX IF NOT EXISTS outputs_queue ON outputs(state, sequence);
|
|
72
78
|
CREATE INDEX IF NOT EXISTS outputs_sent_message ON outputs(remote_id) WHERE state = 'sent' AND remote_id IS NOT NULL;
|
|
@@ -103,6 +109,8 @@ interface OutputRow {
|
|
|
103
109
|
reply_to: string | null;
|
|
104
110
|
picker: string | null;
|
|
105
111
|
result_attachment: string | null;
|
|
112
|
+
edit_of: string | null;
|
|
113
|
+
status: number;
|
|
106
114
|
text: string;
|
|
107
115
|
state: OutputRecord["state"];
|
|
108
116
|
remote_id: string | null;
|
|
@@ -111,13 +119,15 @@ interface OutputRow {
|
|
|
111
119
|
interface ApprovalRow { data: string; state: Approval["state"]; remote_id: string | null }
|
|
112
120
|
|
|
113
121
|
const toInput = (row: InputRow): InputRecord => {
|
|
114
|
-
const input = JSON.parse(row.data) as Inbound & { workflow?: WorkflowActivation };
|
|
115
|
-
return { ...input, workflow:
|
|
122
|
+
const { workflow, ...input } = JSON.parse(row.data) as Inbound & { workflow?: Omit<WorkflowActivation, "name"> & { name: string } };
|
|
123
|
+
return { ...input, workflow: workflow ? { ...workflow, name: storedWorkflowName(workflow.name) } : null, target: row.target, state: row.state,
|
|
116
124
|
requestId: row.request_id, generation: row.generation };
|
|
117
125
|
};
|
|
118
126
|
const toOutput = (row: OutputRow): OutputRecord => ({
|
|
119
127
|
id: row.id, sourceId: row.source_id, route: JSON.parse(row.route) as Route,
|
|
120
128
|
...(row.reply_to === null ? {} : { replyTo: JSON.parse(row.reply_to) as NonNullable<OutputRecord["replyTo"]> }),
|
|
129
|
+
...(row.edit_of === null ? {} : { editOf: JSON.parse(row.edit_of) as NonNullable<OutputRecord["editOf"]> }),
|
|
130
|
+
...(row.status ? { status: true } : {}),
|
|
121
131
|
...(row.picker === null ? {} : { picker: JSON.parse(row.picker) as NonNullable<OutputRecord["picker"]> }),
|
|
122
132
|
...(row.result_attachment === null ? {} : { resultAttachment: JSON.parse(row.result_attachment) as NonNullable<OutputRecord["resultAttachment"]> }),
|
|
123
133
|
text: row.text, state: row.state, remoteId: row.remote_id, error: row.error,
|
|
@@ -127,6 +137,8 @@ const toApproval = (row: ApprovalRow): Approval => ({
|
|
|
127
137
|
});
|
|
128
138
|
const inboundData = (input: Inbound): Inbound => ({
|
|
129
139
|
id: input.id, route: input.route, messageId: input.messageId, text: input.text,
|
|
140
|
+
...(input.discordOriginalText === undefined ? {} : { discordOriginalText: input.discordOriginalText }),
|
|
141
|
+
...(input.routingText === undefined ? {} : { routingText: input.routingText }),
|
|
130
142
|
...(input.interactionId === undefined ? {} : { interactionId: input.interactionId }),
|
|
131
143
|
...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }),
|
|
132
144
|
...(input.pickerSelection === undefined ? {} : { pickerSelection: input.pickerSelection }),
|
|
@@ -135,9 +147,9 @@ const inboundData = (input: Inbound): Inbound => ({
|
|
|
135
147
|
receivedAt: input.receivedAt, attachments: input.attachments,
|
|
136
148
|
});
|
|
137
149
|
function inboundIdentity(input: Inbound) {
|
|
138
|
-
//
|
|
139
|
-
//
|
|
140
|
-
const { reply: _reply, discordContext: _context, ...data } = inboundData(input);
|
|
150
|
+
// Derived routing text and independently edited references do not change the
|
|
151
|
+
// event identity. Keep the first snapshot, including on pre-upgrade replay.
|
|
152
|
+
const { reply: _reply, discordContext: _context, routingText: _routingText, ...data } = inboundData(input);
|
|
141
153
|
return {
|
|
142
154
|
...data,
|
|
143
155
|
// Slack supplies no command timestamp. A transport redelivery has a fresh
|
|
@@ -161,6 +173,21 @@ function inboundIdentity(input: Inbound) {
|
|
|
161
173
|
}).sort((left, right) => left.id.localeCompare(right.id)),
|
|
162
174
|
};
|
|
163
175
|
}
|
|
176
|
+
|
|
177
|
+
/** Verify immutable inbound identity and return updated attachment URLs if refreshed, or null when unchanged. */
|
|
178
|
+
export function reconcileInboundRedelivery(existing: Inbound, incoming: Inbound): Inbound | null {
|
|
179
|
+
if (isDeepStrictEqual(inboundData(existing), inboundData(incoming))) return null;
|
|
180
|
+
if (!isDeepStrictEqual(inboundIdentity(existing), inboundIdentity(incoming))) {
|
|
181
|
+
throw new Error(`Inbound identity conflict: ${incoming.id}`);
|
|
182
|
+
}
|
|
183
|
+
const urls = new Map(incoming.attachments.map(file => [file.id, file.url]));
|
|
184
|
+
const attachments = existing.attachments.map(file => {
|
|
185
|
+
const url = urls.get(file.id)!;
|
|
186
|
+
return file.url === url ? file : { ...file, url };
|
|
187
|
+
});
|
|
188
|
+
if (!attachments.some((file, index) => file !== existing.attachments[index])) return null;
|
|
189
|
+
return { ...existing, attachments };
|
|
190
|
+
}
|
|
164
191
|
const approvalIdentity = (approval: Approval) => ({
|
|
165
192
|
id: approval.id, target: approval.target, generation: approval.generation,
|
|
166
193
|
requestId: approval.requestId, route: approval.route, request: approval.request,
|
|
@@ -194,10 +221,23 @@ export class Store implements StorePort {
|
|
|
194
221
|
db.run("PRAGMA synchronous = FULL");
|
|
195
222
|
db.run("PRAGMA foreign_keys = ON");
|
|
196
223
|
db.run(SCHEMA);
|
|
224
|
+
const laneColumns = db.query<{ name: string }, []>("PRAGMA table_info(lanes)").all();
|
|
225
|
+
if (!laneColumns.some(column => column.name === "remote")) db.run("ALTER TABLE lanes ADD COLUMN remote TEXT");
|
|
197
226
|
const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
|
|
198
227
|
if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
|
|
199
228
|
if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
|
|
200
229
|
if (!outputColumns.some(column => column.name === "result_attachment")) db.run("ALTER TABLE outputs ADD COLUMN result_attachment TEXT");
|
|
230
|
+
if (!outputColumns.some(column => column.name === "edit_of")) db.run("ALTER TABLE outputs ADD COLUMN edit_of TEXT");
|
|
231
|
+
if (!outputColumns.some(column => column.name === "status")) db.run("ALTER TABLE outputs ADD COLUMN status INTEGER NOT NULL DEFAULT 0");
|
|
232
|
+
if (!outputColumns.some(column => column.name === "physical_route")) db.run("ALTER TABLE outputs ADD COLUMN physical_route TEXT");
|
|
233
|
+
db.run("CREATE INDEX IF NOT EXISTS outputs_route_queue ON outputs(state, physical_route, sequence)");
|
|
234
|
+
const missingPhysical = db.query<{ id: string; route: string }, []>("SELECT id, route FROM outputs WHERE physical_route IS NULL").all();
|
|
235
|
+
if (missingPhysical.length) {
|
|
236
|
+
const update = db.query("UPDATE outputs SET physical_route = ? WHERE id = ?");
|
|
237
|
+
db.transaction(() => {
|
|
238
|
+
for (const row of missingPhysical) update.run(physicalRouteKey(JSON.parse(row.route) as Route), row.id);
|
|
239
|
+
})();
|
|
240
|
+
}
|
|
201
241
|
this.db = db;
|
|
202
242
|
this.writerLock = lock;
|
|
203
243
|
} catch (error) {
|
|
@@ -208,6 +248,10 @@ export class Store implements StorePort {
|
|
|
208
248
|
}
|
|
209
249
|
|
|
210
250
|
receive(input: Inbound, target: string | null, metadata: Readonly<Record<string, string>> = {}, workflow: WorkflowActivation | null = null): boolean {
|
|
251
|
+
if (input.discordOriginalText !== undefined && (input.route.platform !== "discord" || input.messageId === null
|
|
252
|
+
|| input.interactionId !== undefined || typeof input.discordOriginalText !== "string")) {
|
|
253
|
+
throw new Error("Original Discord text requires a physical Discord message");
|
|
254
|
+
}
|
|
211
255
|
const slackInvocation = input.route.platform === "slack" && typeof input.invocationId === "string" && /^[a-f0-9]{64}$/.test(input.invocationId);
|
|
212
256
|
const selection = input.pickerSelection;
|
|
213
257
|
if (selection ? input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
|
|
@@ -218,24 +262,43 @@ export class Store implements StorePort {
|
|
|
218
262
|
|| (input.messageId === null ? input.interactionId === undefined && !slackInvocation : typeof input.messageId !== "string" || !input.messageId.length)) {
|
|
219
263
|
throw new Error("Inbound event requires a real message ID, Discord interaction snowflake, scoped Slack invocation, or valid picker selection");
|
|
220
264
|
}
|
|
265
|
+
return this.insertInput(input, target, metadata, workflow);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
receivePrWork(input: Inbound, target: string | null, r: ReviewRound): boolean {
|
|
269
|
+
const parent = { ...input.route, threadId: null };
|
|
270
|
+
const offer = this.output(`cron-pr:offer:${r.repository}:${r.number}`);
|
|
271
|
+
if (!r.automation || input.route.platform !== "discord" || !input.route.guildId || input.route.topicId !== undefined
|
|
272
|
+
|| input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
|
|
273
|
+
|| input.pickerSelection || input.attachments.length || input.discordOriginalText !== undefined || input.reply
|
|
274
|
+
|| this.getMeta(`user-source:${input.id}`) !== null || r.automation.anchor !== input.route.threadId
|
|
275
|
+
|| r.source !== intakeWorkId(r.job, r.number, r.automation.revision, r.head)
|
|
276
|
+
|| !offer || offer.state !== "sent" || offer.remoteId !== r.automation.anchor || routeKey(offer.route) !== routeKey(parent)
|
|
277
|
+
|| this.getMeta(intakeThreadKey(r.job, r.number)) !== r.automation.anchor)
|
|
278
|
+
throw new Error("Static PR work requires the exact noninteractive receipt and confirmed bot starter.");
|
|
279
|
+
const scope = `pr-review:${r.job}:${r.number}`;
|
|
280
|
+
if (input.id === r.source && target === null)
|
|
281
|
+
return this.insertInput(input, target, { [scope]: JSON.stringify(r), [`pr-review-lane:${r.laneId}`]: scope,
|
|
282
|
+
[`topic-owner:${r.source}`]: r.laneId }, null);
|
|
283
|
+
const source = this.input(r.source);
|
|
284
|
+
if (input.id !== r.inputId || (target !== null && target !== r.laneId) || source?.target !== null
|
|
285
|
+
|| source.state !== "pending" || routeKey(source.route) !== routeKey(input.route)
|
|
286
|
+
|| this.getMeta(scope) !== JSON.stringify(r) || this.getMeta(`pr-review-lane:${r.laneId}`) !== scope)
|
|
287
|
+
throw new Error("Static PR lane handoff does not match its registered controller receipt.");
|
|
288
|
+
return this.insertInput(input, target, { [`handoff-source:${input.id}`]: r.source }, null);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private insertInput(input: Inbound, target: string | null, metadata: Readonly<Record<string, string>>, workflow: WorkflowActivation | null): boolean {
|
|
221
292
|
return this.db.transaction(() => {
|
|
222
293
|
const existing = this.input(input.id);
|
|
223
294
|
if (existing) {
|
|
224
295
|
if (!isDeepStrictEqual(existing.workflow, workflow)) throw new Error(`Workflow identity conflict: ${input.id}`);
|
|
225
|
-
|
|
226
|
-
if (
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const attachments = existing.attachments.map(file => {
|
|
232
|
-
const url = urls.get(file.id)!;
|
|
233
|
-
return file.url === url ? file : { ...file, url };
|
|
234
|
-
});
|
|
235
|
-
if (attachments.some((file, index) => file !== existing.attachments[index])) {
|
|
236
|
-
this.db.query("UPDATE inputs SET data = ? WHERE id = ? AND state = 'pending'")
|
|
237
|
-
.run(JSON.stringify({ ...inboundData(existing), attachments, workflow: existing.workflow }), input.id);
|
|
238
|
-
}
|
|
296
|
+
const refreshed = reconcileInboundRedelivery(existing, input);
|
|
297
|
+
if (existing.state === "pending" && refreshed) {
|
|
298
|
+
// Refresh only URLs. In particular, do not rewrite the original
|
|
299
|
+
// activation in a pre-rename input as a side effect of redelivery.
|
|
300
|
+
this.db.query("UPDATE inputs SET data = json_set(data, '$.attachments', json(?)) WHERE id = ? AND state = 'pending'")
|
|
301
|
+
.run(JSON.stringify(refreshed.attachments), input.id);
|
|
239
302
|
}
|
|
240
303
|
return false; // A replay never changes its current assignment or state.
|
|
241
304
|
}
|
|
@@ -293,10 +356,25 @@ export class Store implements StorePort {
|
|
|
293
356
|
const revisionOf = this.getMeta(`topic-revision:${source.id}`);
|
|
294
357
|
const original = revisionOf === null ? source : source.messageId === null ? null : this.firstAdmittedMessage(source.route, source.messageId);
|
|
295
358
|
if (!original || revisionOf !== null && (original.id !== revisionOf || original.id === source.id
|
|
296
|
-
|| routeKey(original.route) !== routeKey(source.route)
|
|
359
|
+
|| routeKey(original.route) !== routeKey(source.route))) {
|
|
297
360
|
throw new Error(`Invalid topic revision ancestry: ${source.id}`);
|
|
298
361
|
}
|
|
299
|
-
|
|
362
|
+
let route: Route;
|
|
363
|
+
if (revisionOf !== null && original.target === "main" && original.route.guildId === null && original.route.threadId === null) {
|
|
364
|
+
const placement = this.headLanePlacement(original.id);
|
|
365
|
+
if (!placement || placement === "unverified" || placement.id !== input.target
|
|
366
|
+
|| routeKey(placement.route) !== routeKey(input.route)
|
|
367
|
+
|| input.id !== `handoff:${source.id}:${placement.id}`
|
|
368
|
+
|| this.getMeta(`handoff-source:${input.id}`) !== source.id) {
|
|
369
|
+
throw new Error(`Invalid HEAD topic revision placement: ${source.id}`);
|
|
370
|
+
}
|
|
371
|
+
route = placement.route;
|
|
372
|
+
} else {
|
|
373
|
+
if (revisionOf !== null && this.getMeta(`topic-owner:${original.id}`) !== input.target) {
|
|
374
|
+
throw new Error(`Invalid topic revision owner: ${source.id}`);
|
|
375
|
+
}
|
|
376
|
+
route = this.deliveryRoute(original, input.target);
|
|
377
|
+
}
|
|
300
378
|
// Preserve the original identity on its own route. A selected work thread
|
|
301
379
|
// uses its exact handoff (which still links to the original owner source).
|
|
302
380
|
const outputSourceId = routeKey(route) === routeKey(source.route) ? source.id : input.id;
|
|
@@ -317,14 +395,21 @@ export class Store implements StorePort {
|
|
|
317
395
|
hasPendingTopicChoice(input: InputRecord, deadline: number): boolean {
|
|
318
396
|
const { platform, accountId, authorityId, guildId, channelId, threadId } = input.route;
|
|
319
397
|
if (platform !== "discord" || guildId === null || threadId === null) return false;
|
|
398
|
+
// An input already ACKed to Gateway but still awaiting deferred topic routing
|
|
399
|
+
// has no head receipt yet either; it fences the choice like a pending ledger row.
|
|
400
|
+
const deferred = (JSON.parse(this.getMeta(DEFERRED_ROUTING_META) ?? "[]") as Inbound[]).filter(item => !item.pickerSelection
|
|
401
|
+
&& (typeof item.messageId === "string" || typeof item.interactionId === "string")
|
|
402
|
+
&& Number.isSafeInteger(item.receivedAt) && item.receivedAt >= input.receivedAt && item.receivedAt <= deadline
|
|
403
|
+
&& item.id !== input.id && physicalRouteKey(item.route) === physicalRouteKey(input.route))
|
|
404
|
+
.map(item => ({ id: item.id, text: item.text, messageId: item.messageId, replyId: item.reply?.messageId ?? null, authoredAt: item.receivedAt }));
|
|
320
405
|
// Gateway creates the shared ingress ledger; standalone Store use has none.
|
|
321
|
-
|
|
406
|
+
const ledger = this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get() !== null;
|
|
322
407
|
const questionId = `${input.id}:workspace`;
|
|
323
408
|
const choices: readonly { readonly cwd: string }[] = JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]");
|
|
324
409
|
// The Gateway pending index skips delivered history, including terminal rejections.
|
|
325
410
|
// Unresolved rows stay pending. The durable insert, not its wall-clock timestamp,
|
|
326
411
|
// fences a timely-authored choice even when transport-delayed.
|
|
327
|
-
const rows = this.db.query<{
|
|
412
|
+
const rows = ledger ? this.db.query<{
|
|
328
413
|
readonly id: string; readonly text: string; readonly messageId: string | null;
|
|
329
414
|
readonly replyId: string | null; readonly authoredAt: number;
|
|
330
415
|
}, [number, number, string, string, string, string, string, string, string]>(`
|
|
@@ -347,8 +432,9 @@ export class Store implements StorePort {
|
|
|
347
432
|
AND json_extract(data, '$.input.route.guildId') = ?
|
|
348
433
|
AND json_extract(data, '$.input.route.channelId') = ?
|
|
349
434
|
AND json_extract(data, '$.input.route.threadId') = ?
|
|
350
|
-
`)
|
|
351
|
-
|
|
435
|
+
`) : null;
|
|
436
|
+
const pending = rows?.iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId) ?? [];
|
|
437
|
+
for (const row of [...deferred, ...pending]) {
|
|
352
438
|
if (row.messageId !== null && row.id.startsWith(`discord:${accountId}:${row.messageId}:edit:`)) continue;
|
|
353
439
|
const questionReply = row.replyId !== null && this.sentOutputForMessage(input.route, row.replyId)?.id === questionId;
|
|
354
440
|
const scopedReply = questionReply || row.replyId !== null && row.replyId === input.messageId;
|
|
@@ -402,6 +488,42 @@ export class Store implements StorePort {
|
|
|
402
488
|
return this.db.query("SELECT 1 FROM inputs WHERE target = ? AND state = ? LIMIT 1").get(target, state) !== null;
|
|
403
489
|
}
|
|
404
490
|
|
|
491
|
+
latestLaneRun(target: string): InputRecord | null {
|
|
492
|
+
const admitted = this.getMeta(`lane-latest-run:${target}`);
|
|
493
|
+
if (admitted) return this.input(admitted);
|
|
494
|
+
// Exclude joined inputs because they have no separate answer. A legacy
|
|
495
|
+
// goal resume could overtake an older queued input in the same generation.
|
|
496
|
+
const row = this.db.query<InputRow, [string]>(`SELECT latest.* FROM (SELECT inputs.* FROM inputs
|
|
497
|
+
LEFT JOIN metadata ON metadata.key = 'steering-owner:' || inputs.id
|
|
498
|
+
WHERE inputs.target = ? AND inputs.target <> 'main' AND inputs.request_id IS NOT NULL
|
|
499
|
+
AND (metadata.value IS NULL OR metadata.value = inputs.id)
|
|
500
|
+
ORDER BY inputs.sequence DESC LIMIT 1) AS latest
|
|
501
|
+
WHERE latest.id NOT LIKE 'resume:%' OR NOT EXISTS (
|
|
502
|
+
SELECT 1 FROM inputs AS earlier WHERE earlier.target = latest.target
|
|
503
|
+
AND earlier.generation = latest.generation AND earlier.request_id IS NOT NULL
|
|
504
|
+
AND earlier.sequence < latest.sequence)`).get(target);
|
|
505
|
+
return row ? toInput(row) : null;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
hasPendingLaneResult(target: string): boolean {
|
|
509
|
+
return this.db.query(`SELECT 1 FROM inputs AS run
|
|
510
|
+
LEFT JOIN inputs AS report ON report.id = 'report:' || run.id
|
|
511
|
+
LEFT JOIN inputs AS recovered ON recovered.id = 'report:' || run.id || ':done'
|
|
512
|
+
LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, run.id) || ':answer'
|
|
513
|
+
LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, run.id) || ':answer:done'
|
|
514
|
+
WHERE run.target = ? AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
|
|
515
|
+
AND (COALESCE(recovered.state, report.state) IN ('pending','submitted','uncertain')
|
|
516
|
+
OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain'))
|
|
517
|
+
LIMIT 1`).get(target) !== null;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
hasPendingLanePlacement(target: string): boolean {
|
|
521
|
+
return this.db.query(`SELECT 1 FROM inputs
|
|
522
|
+
JOIN metadata ON metadata.key = 'topic-owner:' || inputs.id
|
|
523
|
+
WHERE inputs.target IS NULL AND inputs.state IN ('pending','uncertain') AND metadata.value = ?
|
|
524
|
+
LIMIT 1`).get(target) !== null;
|
|
525
|
+
}
|
|
526
|
+
|
|
405
527
|
hasHeadRecoveryInput(): boolean {
|
|
406
528
|
return this.db.query(`SELECT 1 FROM inputs
|
|
407
529
|
JOIN metadata ON metadata.key = 'head-native-owner:' || inputs.id AND metadata.value <> ''
|
|
@@ -426,31 +548,146 @@ export class Store implements StorePort {
|
|
|
426
548
|
return row ? toInput(row) : null;
|
|
427
549
|
}
|
|
428
550
|
|
|
551
|
+
private admittedMessageRevisions(route: Route, messageId: string): InputRecord[] {
|
|
552
|
+
return this.db.query<InputRow, [string, string, string, string, string | null, string | null, string]>(
|
|
553
|
+
`SELECT inputs.* ${ADMITTED_MESSAGE_SCOPE} AND json_extract(inputs.data, '$.messageId') = ? ORDER BY inputs.sequence`,
|
|
554
|
+
).all(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId, messageId).map(toInput);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Recognize a misplaced choice without exposing another thread's question or granting it a vote. */
|
|
558
|
+
isDiscordWorkspaceQuestion(route: Route, messageId: string): boolean {
|
|
559
|
+
if (route.platform !== "discord") return false;
|
|
560
|
+
return this.db.query(`SELECT 1 FROM outputs WHERE state = 'sent' AND (remote_id = ? OR id = ?)
|
|
561
|
+
AND id = source_id || ':workspace' AND json_extract(route, '$.platform') = 'discord'
|
|
562
|
+
AND json_extract(route, '$.accountId') = ? AND json_extract(route, '$.authorityId') = ?
|
|
563
|
+
AND json_extract(route, '$.guildId') IS ? AND json_extract(route, '$.channelId') = ? LIMIT 1`)
|
|
564
|
+
.get(messageId, this.getMeta(`discord:output-part:${messageId}`), route.accountId, route.authorityId, route.guildId, route.channelId) !== null;
|
|
565
|
+
}
|
|
566
|
+
|
|
429
567
|
sentOutputForMessage(route: Route, messageId: string): OutputRecord | null {
|
|
568
|
+
const scoped = this.outputReceiptsForMessage(route, messageId).filter(output => output.state === "sent");
|
|
569
|
+
return scoped.length === 1 ? scoped[0] ?? null : null;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
private outputReceiptsForMessage(route: Route, messageId: string): OutputRecord[] {
|
|
430
573
|
const part = route.platform === "discord" ? this.getMeta(`discord:output-part:${messageId}`) : null;
|
|
574
|
+
// The Gateway can know a completed multipart send before this controller
|
|
575
|
+
// durably records its confirmation. Such a part identifies, but does not prove, placement.
|
|
431
576
|
const rows = this.db.query<OutputRow, [string, string | null]>(
|
|
432
|
-
"SELECT * FROM outputs WHERE state = 'sent' AND
|
|
577
|
+
"SELECT * FROM outputs WHERE (state = 'sent' AND remote_id = ?) OR id = ?",
|
|
433
578
|
).all(messageId, part);
|
|
434
|
-
|
|
435
|
-
return
|
|
579
|
+
// An in-place status edit shares its message with the output that created it.
|
|
580
|
+
return rows.map(toOutput).filter(output => physicalRouteKey(output.route) === physicalRouteKey(route)
|
|
581
|
+
&& output.editOf?.messageId !== messageId);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
repliedParentTopic(route: Route, messageId: string): Lane | "unverified" | null {
|
|
585
|
+
const placement = this.repliedPlacement(route, messageId, "logical");
|
|
586
|
+
return placement === "unverified" || placement?.route.topicId ? placement : null;
|
|
436
587
|
}
|
|
437
588
|
|
|
438
589
|
repliedTopicWorkspace(route: Route, messageId: string): string | null {
|
|
439
|
-
const
|
|
440
|
-
|
|
590
|
+
const placement = this.repliedPlacement(route, messageId, "workspace");
|
|
591
|
+
return placement === "unverified" ? null : placement?.cwd ?? null;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
repliedStop(route: Route, messageId: string): ReturnType<StorePort["repliedStop"]> {
|
|
595
|
+
const revisions = this.admittedMessageRevisions(route, messageId);
|
|
596
|
+
const outputs = this.outputReceiptsForMessage(route, messageId);
|
|
597
|
+
const [output] = outputs;
|
|
598
|
+
if (outputs.length > 1 || output && (revisions.length || output.state !== "sent" || !output.remoteId)) return { kind: "unverified" };
|
|
599
|
+
if (output && output.id === `${output.sourceId}:workspace`) return { kind: "workspace", sourceId: output.sourceId };
|
|
600
|
+
const placement = this.replyLanes(route, revisions, output, "stop");
|
|
601
|
+
if (placement === "unverified") return { kind: "unverified" };
|
|
602
|
+
if (placement.lane) return { kind: "lane", lane: placement.lane, unplaced: placement.unplaced };
|
|
441
603
|
const source = output && this.ownerSource(output.sourceId);
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
604
|
+
if (source && physicalRouteKey(source.route) === physicalRouteKey(route)) return { kind: "sources", sources: [source] };
|
|
605
|
+
return revisions.length ? { kind: "sources", sources: revisions } : { kind: "unknown" };
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
private repliedPlacement(route: Route, messageId: string, mode: "logical" | "workspace"): Lane | "unverified" | null {
|
|
609
|
+
const revisions = this.admittedMessageRevisions(route, messageId);
|
|
610
|
+
const outputs = this.outputReceiptsForMessage(route, messageId);
|
|
611
|
+
const [output] = outputs;
|
|
612
|
+
if (outputs.length > 1 || revisions.length && output) return "unverified";
|
|
613
|
+
const placement = this.replyLanes(route, revisions, output, mode);
|
|
614
|
+
return placement === "unverified" ? placement : placement.lane;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
private replyLanes(route: Route, revisions: readonly InputRecord[], output: OutputRecord | undefined,
|
|
618
|
+
mode: "logical" | "workspace" | "stop"): { readonly lane: Lane | null; readonly unplaced: readonly InputRecord[] } | "unverified" {
|
|
619
|
+
// A physical owner message can name several admitted revisions. Exact bot
|
|
620
|
+
// receipts instead name one source, independent of other revisions.
|
|
621
|
+
let placement: Lane | null = null;
|
|
622
|
+
const unplaced: InputRecord[] = [];
|
|
623
|
+
for (const original of revisions.length ? revisions : [null]) {
|
|
624
|
+
const lane = this.replyLane(route, original, output, mode);
|
|
625
|
+
if (lane === "unverified" || lane && placement && lane.id !== placement.id) return "unverified";
|
|
626
|
+
if (lane) placement = lane;
|
|
627
|
+
else if (original) unplaced.push(original);
|
|
452
628
|
}
|
|
453
|
-
return
|
|
629
|
+
return { lane: placement, unplaced };
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
private replyLane(route: Route, original: InputRecord | null, output: OutputRecord | undefined,
|
|
633
|
+
mode: "logical" | "workspace" | "stop"): Lane | "unverified" | null {
|
|
634
|
+
const head = this.repliedHeadPlacement(original, output, mode === "stop");
|
|
635
|
+
if (head === "unverified") return head;
|
|
636
|
+
if (head) return mode === "logical" && head.route.topicId && physicalRouteKey(head.route) !== physicalRouteKey(route) ? "unverified" : head;
|
|
637
|
+
if (output && output.state !== "sent") return null;
|
|
638
|
+
const source = original ?? (output ? this.ownerSource(output.sourceId) : null);
|
|
639
|
+
const owner = source && this.getMeta(`topic-owner:${source.id}`);
|
|
640
|
+
if (!source || !owner) return null;
|
|
641
|
+
const creation = this.getMeta(`topic-creator:${source.id}`);
|
|
642
|
+
const handoff = this.input(`handoff:${source.id}:${creation ? "lane" : owner}`);
|
|
643
|
+
if (!handoff) return mode === "stop" && source.state !== "pending" && source.state !== "cancelled" ? "unverified" : null;
|
|
644
|
+
const lane = this.lane(owner);
|
|
645
|
+
if (!lane || handoff.target !== owner) return mode === "stop" ? "unverified" : null;
|
|
646
|
+
if (mode === "logical" && (physicalRouteKey(lane.route) !== physicalRouteKey(route)
|
|
647
|
+
|| physicalRouteKey(source.route) !== physicalRouteKey(route))) return null;
|
|
648
|
+
if (mode !== "workspace") {
|
|
649
|
+
const kickoff = creation ? this.output(`${source.id}:kickoff`) : null;
|
|
650
|
+
if (routeKey(handoff.route) !== routeKey(lane.route) || this.getMeta(`handoff-source:${handoff.id}`) !== source.id
|
|
651
|
+
|| creation && (kickoff?.state !== "sent" || !kickoff.remoteId || kickoff.sourceId !== handoff.id
|
|
652
|
+
|| routeKey(kickoff.route) !== routeKey(lane.route))) return mode === "stop" ? "unverified" : null;
|
|
653
|
+
}
|
|
654
|
+
return lane;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
private repliedHeadPlacement(original: InputRecord | null, output: OutputRecord | undefined,
|
|
658
|
+
includeExplicitHead: boolean): Lane | "unverified" | null {
|
|
659
|
+
const notice = output?.id.endsWith(":topic-bound");
|
|
660
|
+
const suffix = notice ? ":topic-bound" : ":kickoff";
|
|
661
|
+
const origin = original ?? (output?.id.endsWith(suffix) ? this.input(output.id.slice(0, -suffix.length)) : null);
|
|
662
|
+
if (!origin || origin.target !== "main" || !includeExplicitHead && this.getMeta(`head-routing:${origin.id}`) !== "true") return null;
|
|
663
|
+
const lane = this.headLanePlacement(origin.id);
|
|
664
|
+
if (!lane || lane === "unverified" || !output) return lane;
|
|
665
|
+
if (notice ? output.state !== "sent" || !output.remoteId || output.sourceId !== origin.id || routeKey(output.route) !== routeKey(origin.route)
|
|
666
|
+
|| this.getMeta(`handoff-native:${origin.id}`) !== "true" : output.id !== `${origin.id}:kickoff`) return "unverified";
|
|
667
|
+
return lane;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
headLanePlacement(sourceId: string): Lane | "unverified" | null {
|
|
671
|
+
const origin = this.input(sourceId);
|
|
672
|
+
if (!origin || origin.target !== "main") return null;
|
|
673
|
+
const handoff = this.input(`handoff:${sourceId}:lane`);
|
|
674
|
+
if (!handoff && this.getMeta(`handoff-intent:${sourceId}`) === null) return null;
|
|
675
|
+
if (this.getMeta(`user-source:${origin.id}`) !== "true" || !handoff
|
|
676
|
+
|| this.getMeta(`handoff-source:${handoff.id}`) !== origin.id) return "unverified";
|
|
677
|
+
// lane_start registers its exact creation source here; lane_message only
|
|
678
|
+
// enqueues another input. The deterministic handoff ID alone is not proof.
|
|
679
|
+
const binding = this.db.query<{ lane_id: string }, [string]>(
|
|
680
|
+
"SELECT lane_id FROM lane_sources WHERE source_id = ?",
|
|
681
|
+
).get(handoff.id);
|
|
682
|
+
const lane = binding && this.lane(binding.lane_id);
|
|
683
|
+
if (!lane || handoff.target !== lane.id || routeKey(handoff.route) !== routeKey(lane.route)
|
|
684
|
+
|| (lane.route.topicId ? physicalRouteKey(origin.route) !== physicalRouteKey(lane.route)
|
|
685
|
+
: physicalRouteKey({ ...origin.route, threadId: null }) !== physicalRouteKey({ ...lane.route, threadId: null }))) return "unverified";
|
|
686
|
+
const kickoffId = `${origin.id}:kickoff`;
|
|
687
|
+
const kickoff = this.output(kickoffId);
|
|
688
|
+
if (this.getMeta(`kickoff-output:${handoff.id}`) !== kickoffId || kickoff?.state !== "sent" || !kickoff.remoteId
|
|
689
|
+
|| kickoff.sourceId !== handoff.id || routeKey(kickoff.route) !== routeKey(lane.route)) return "unverified";
|
|
690
|
+
return lane;
|
|
454
691
|
}
|
|
455
692
|
|
|
456
693
|
*admittedMessageIds(route: Route): Iterable<string> {
|
|
@@ -485,8 +722,26 @@ export class Store implements StorePort {
|
|
|
485
722
|
if (!Number.isSafeInteger(generation) || generation < 0) throw new Error("Invalid generation");
|
|
486
723
|
const lane = this.lane(input.target);
|
|
487
724
|
if (lane && (lane.generation !== generation || lane.workState !== "open")) return false;
|
|
488
|
-
|
|
725
|
+
const submitted = this.db.query(`UPDATE inputs SET state = 'submitted', request_id = ?, generation = ?
|
|
489
726
|
WHERE id = ? AND state = 'pending'`).run(requestId, generation, id).changes === 1;
|
|
727
|
+
const ownerId = submitted && lane ? this.getMeta(`steering-owner:${id}`) : null;
|
|
728
|
+
if (ownerId && ownerId !== id) {
|
|
729
|
+
const topic = this.topicDelivery(id);
|
|
730
|
+
if (topic && !this.topicDelivery(ownerId)) {
|
|
731
|
+
const owner = this.input(ownerId);
|
|
732
|
+
const source = owner && this.ownerSource(owner.id);
|
|
733
|
+
if (!owner || !source || owner.state !== "submitted" || owner.target !== input.target || owner.generation !== generation
|
|
734
|
+
|| routeKey(owner.route) !== routeKey(input.route) || routeKey(this.laneReplyRoute(owner, source)) !== routeKey(topic.route)) {
|
|
735
|
+
throw new Error(`Steering reply route differs from the current lane run: ${id}`);
|
|
736
|
+
}
|
|
737
|
+
// A later lane_start of the manager source must not redirect this cohort.
|
|
738
|
+
this.setMeta(`steering-topic-reply:${owner.id}`, JSON.stringify(topic.route));
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (submitted && lane?.route.platform === "discord" && lane.route.guildId && lane.route.threadId) {
|
|
742
|
+
if (ownerId === null || ownerId === id) this.setMeta(`lane-latest-run:${lane.id}`, id);
|
|
743
|
+
}
|
|
744
|
+
return submitted;
|
|
490
745
|
}).immediate();
|
|
491
746
|
}
|
|
492
747
|
|
|
@@ -506,19 +761,50 @@ export class Store implements StorePort {
|
|
|
506
761
|
return !!lane && lane.workState === "open" && lane.generation === context.generation && lane.sessionId === context.sessionId;
|
|
507
762
|
}
|
|
508
763
|
|
|
509
|
-
|
|
764
|
+
private progressStream(id: string): string {
|
|
765
|
+
let current = id;
|
|
766
|
+
const seen = new Set<string>([current]);
|
|
767
|
+
while (true) {
|
|
768
|
+
const parent = this.getMeta(`progress-source:${current}`);
|
|
769
|
+
if (!parent) return current;
|
|
770
|
+
const { inputId } = JSON.parse(parent) as { inputId: string };
|
|
771
|
+
if (seen.has(inputId)) return current;
|
|
772
|
+
seen.add(inputId);
|
|
773
|
+
current = inputId;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* When opted in on Discord (`editInPlace`), nonterminal progress uses one
|
|
779
|
+
* `⏳` status message edited in place. Each update stays its own immutable
|
|
780
|
+
* output; `claimOutput` decides whether it edits that message. By default (or
|
|
781
|
+
* on other platforms), every update posts as an ordinary new message.
|
|
782
|
+
*/
|
|
783
|
+
private queueStatus(
|
|
784
|
+
output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">,
|
|
785
|
+
stream: string,
|
|
786
|
+
editInPlace = false,
|
|
787
|
+
): boolean {
|
|
788
|
+
if (!editInPlace || output.route.platform !== "discord") return this.queueOutput(output);
|
|
789
|
+
this.setMeta(`status-stream:${output.id}`, stream);
|
|
790
|
+
const text = /^(?:`{3,}|~{3,})/.test(output.text.trimStart()) ? `⏳\n${output.text}` : `⏳ ${output.text}`;
|
|
791
|
+
return this.queueOutput({ ...output, text, status: true });
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace = false): boolean {
|
|
510
795
|
if (!text.trim()) return false;
|
|
511
796
|
return this.db.transaction(() => {
|
|
512
797
|
const context = { inputId: id, generation, sessionId };
|
|
513
798
|
if (!this.progressOpen(context)) return false;
|
|
514
799
|
const input = this.requireInput(id);
|
|
800
|
+
if (unattendedSource(this, input)) return false; // Static review has one final answer, not a HEAD progress prompt.
|
|
515
801
|
const receiptId = `progress:${id}:${eventId}`;
|
|
516
802
|
const seen = `progress-seen:${receiptId}`;
|
|
517
803
|
if (this.getMeta(seen)) return false;
|
|
518
804
|
this.setMeta(seen, "true");
|
|
519
805
|
if (input.target === "main") {
|
|
520
806
|
this.setMeta(`progress-output:${receiptId}`, JSON.stringify(context));
|
|
521
|
-
return this.
|
|
807
|
+
return this.queueStatus({ id: receiptId, sourceId: id, route: input.route, text }, this.progressStream(id), editInPlace);
|
|
522
808
|
}
|
|
523
809
|
const topic = this.topicDelivery(id);
|
|
524
810
|
if (topic) {
|
|
@@ -529,7 +815,7 @@ export class Store implements StorePort {
|
|
|
529
815
|
.run("Nonterminal progress superseded", previous);
|
|
530
816
|
this.setMeta(pendingKey, receiptId);
|
|
531
817
|
this.setMeta(`progress-output:${receiptId}`, JSON.stringify(context));
|
|
532
|
-
return this.
|
|
818
|
+
return this.queueStatus({ id: receiptId, sourceId: topic.outputSourceId, route: topic.route, text }, id, editInPlace);
|
|
533
819
|
}
|
|
534
820
|
const lane = this.requireLane(input.target!);
|
|
535
821
|
const sourceId = this.getMeta(`handoff-source:${id}`);
|
|
@@ -538,7 +824,7 @@ export class Store implements StorePort {
|
|
|
538
824
|
const previous = this.getMeta(pendingKey);
|
|
539
825
|
if (previous) this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(previous);
|
|
540
826
|
this.receive({
|
|
541
|
-
id: receiptId, route: this.
|
|
827
|
+
id: receiptId, route: this.laneReplyRoute(input, source), messageId: source.messageId,
|
|
542
828
|
receivedAt: source.receivedAt, attachments: [],
|
|
543
829
|
...(source.interactionId === undefined ? {} : { interactionId: source.interactionId }),
|
|
544
830
|
...(source.invocationId === undefined ? {} : { invocationId: source.invocationId }),
|
|
@@ -604,7 +890,7 @@ export class Store implements StorePort {
|
|
|
604
890
|
changed = true;
|
|
605
891
|
}
|
|
606
892
|
this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
607
|
-
.run(
|
|
893
|
+
.run(laneData({ ...lane, observation }), lane.id, generation);
|
|
608
894
|
this.setMeta(seen, serialized);
|
|
609
895
|
// Topic evidence stays inspectable; only assistant commentary is delivered.
|
|
610
896
|
// Legacy HEAD review needs a new evidence snapshot or waiting transition.
|
|
@@ -628,7 +914,7 @@ export class Store implements StorePort {
|
|
|
628
914
|
|| !waiting || waiting.target.kind !== kind || waiting.target.id !== nativeId) return false;
|
|
629
915
|
const resolved = { ...observation, waiting: null };
|
|
630
916
|
this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
631
|
-
.run(
|
|
917
|
+
.run(laneData({ ...lane, observation: resolved }), lane.id, generation);
|
|
632
918
|
// Completion/cancellation of a wait is not evidence of successful work.
|
|
633
919
|
if (!this.topicOwner(input)) this.progress(id, generation, sessionId, `resolved:${JSON.stringify([kind, nativeId, waiting.since])}`, [
|
|
634
920
|
`Native waiting target finished or was cancelled: ${JSON.stringify(waiting.target)}.`,
|
|
@@ -639,7 +925,7 @@ export class Store implements StorePort {
|
|
|
639
925
|
}).immediate();
|
|
640
926
|
}
|
|
641
927
|
|
|
642
|
-
settle(id: string, state: "done" | "uncertain" | "cancelled", output?: Pick<OutputRecord, "id" | "text" | "picker">, headModel?: HeadModelChange): boolean {
|
|
928
|
+
settle(id: string, state: "done" | "uncertain" | "cancelled", output?: Pick<OutputRecord, "id" | "text" | "picker">, headModel?: HeadModelChange, editInPlace = false): boolean {
|
|
643
929
|
return this.db.transaction(() => {
|
|
644
930
|
const input = this.input(id);
|
|
645
931
|
if (!input || input.state === "done" || input.state === "cancelled" || input.state === state) return false;
|
|
@@ -648,8 +934,12 @@ export class Store implements StorePort {
|
|
|
648
934
|
const progress = this.getMeta(`progress-source:${id}`);
|
|
649
935
|
if (progress && !this.progressOpen(JSON.parse(progress))) output = undefined;
|
|
650
936
|
// An uncertain request can only be resolved explicitly, never resubmitted.
|
|
651
|
-
const
|
|
652
|
-
|
|
937
|
+
const reviewSource = unattendedSource(this, input);
|
|
938
|
+
const topic = output && !reviewSource && this.topicDelivery(id);
|
|
939
|
+
if (reviewSource) {
|
|
940
|
+
if (output?.text.trim() && hasIntakeReplyRoute(this, input, reviewSource))
|
|
941
|
+
this.queueOutput({ ...output, sourceId: input.id, route: input.route });
|
|
942
|
+
} else if (output && topic) {
|
|
653
943
|
if (output.text.trim() && (topic.source.id === id
|
|
654
944
|
|| topic.source.state !== "cancelled" && topic.source.state !== "uncertain")) {
|
|
655
945
|
this.queueOutput({
|
|
@@ -665,7 +955,7 @@ export class Store implements StorePort {
|
|
|
665
955
|
const receiptId = input.state === "uncertain" ? `${reportId}:${state}` : reportId;
|
|
666
956
|
this.receive({
|
|
667
957
|
id: receiptId,
|
|
668
|
-
route: this.
|
|
958
|
+
route: this.laneReplyRoute(input, source), messageId: source.messageId, receivedAt: source.receivedAt, attachments: [],
|
|
669
959
|
...(source.interactionId === undefined ? {} : { interactionId: source.interactionId }),
|
|
670
960
|
...(source.invocationId === undefined ? {} : { invocationId: source.invocationId }),
|
|
671
961
|
text: [
|
|
@@ -677,8 +967,16 @@ export class Store implements StorePort {
|
|
|
677
967
|
].join("\n\n"),
|
|
678
968
|
}, "main", { [`activity-source:${receiptId}`]: source.id });
|
|
679
969
|
} else if (output) {
|
|
680
|
-
if (progress)
|
|
681
|
-
|
|
970
|
+
if (progress) {
|
|
971
|
+
this.setMeta(`progress-output:${output.id}`, progress);
|
|
972
|
+
if (!output.picker) {
|
|
973
|
+
this.queueStatus({ ...output, sourceId: id, route: input.route }, this.progressStream(id), editInPlace);
|
|
974
|
+
} else {
|
|
975
|
+
this.queueOutput({ ...output, sourceId: id, route: input.route });
|
|
976
|
+
}
|
|
977
|
+
} else {
|
|
978
|
+
this.queueOutput({ ...output, sourceId: id, route: input.route });
|
|
979
|
+
}
|
|
682
980
|
}
|
|
683
981
|
this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
|
|
684
982
|
if (headModel && state === "done" && input.state === "submitted" && input.target === "main") {
|
|
@@ -795,6 +1093,11 @@ export class Store implements StorePort {
|
|
|
795
1093
|
}).immediate();
|
|
796
1094
|
}
|
|
797
1095
|
|
|
1096
|
+
laneReplyRoute(input: InputRecord, source: InputRecord): Route {
|
|
1097
|
+
const pinned = this.getMeta(`steering-topic-reply:${input.id}`);
|
|
1098
|
+
return pinned ? JSON.parse(pinned) : this.deliveryRoute(source);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
798
1101
|
private deliveryRoute(source: InputRecord, expectedLane?: string | null): Route {
|
|
799
1102
|
const stored = this.getMeta(`head-delivery:${source.id}`);
|
|
800
1103
|
if (!stored) return source.route;
|
|
@@ -809,12 +1112,16 @@ export class Store implements StorePort {
|
|
|
809
1112
|
return decision.destination;
|
|
810
1113
|
}
|
|
811
1114
|
|
|
812
|
-
queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error">): boolean {
|
|
1115
|
+
queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
|
|
1116
|
+
if (output.status && (output.route.platform !== "discord" || output.picker || output.resultAttachment)) {
|
|
1117
|
+
throw new Error(`Status delivery requires a plain Discord message: ${output.id}`);
|
|
1118
|
+
}
|
|
813
1119
|
return this.db.transaction(() => {
|
|
814
1120
|
const existing = this.output(output.id);
|
|
815
1121
|
if (existing) {
|
|
816
1122
|
if (existing.sourceId !== output.sourceId || routeKey(existing.route) !== routeKey(output.route)
|
|
817
|
-
|| existing.text !== output.text ||
|
|
1123
|
+
|| existing.text !== output.text || Boolean(existing.status) !== Boolean(output.status)
|
|
1124
|
+
|| !isDeepStrictEqual(existing.picker, output.picker)
|
|
818
1125
|
|| !isDeepStrictEqual(existing.resultAttachment, output.resultAttachment)
|
|
819
1126
|
|| output.replyTo !== undefined && (!existing.replyTo
|
|
820
1127
|
|| existing.replyTo.messageId !== output.replyTo.messageId
|
|
@@ -848,20 +1155,25 @@ export class Store implements StorePort {
|
|
|
848
1155
|
throw new Error(`Result attachment does not match its original native request: ${output.id}`);
|
|
849
1156
|
}
|
|
850
1157
|
}
|
|
851
|
-
const
|
|
852
|
-
|
|
853
|
-
|
|
1158
|
+
const replyOrigin = original ?? laneWatchReplySource(this, source, output.id);
|
|
1159
|
+
const replyTo = replyOrigin?.route.platform === "discord" && replyOrigin.messageId
|
|
1160
|
+
&& physicalRouteKey(replyOrigin.route) === physicalRouteKey(output.route)
|
|
1161
|
+
? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId } : undefined;
|
|
854
1162
|
if (output.replyTo !== undefined && (!replyTo || output.replyTo.messageId !== replyTo.messageId
|
|
855
1163
|
|| physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
|
|
856
1164
|
throw new Error(`Output reply differs from its source: ${output.id}`);
|
|
857
1165
|
}
|
|
858
|
-
return this.db.query("INSERT INTO outputs(id, source_id, route, text, reply_to, picker, result_attachment) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
859
|
-
.run(output.id, output.sourceId, JSON.stringify(output.route), output.text, replyTo ? JSON.stringify(replyTo) : null,
|
|
860
|
-
output.picker ? JSON.stringify(output.picker) : null, attachment ? JSON.stringify(attachment) : null).changes === 1;
|
|
1166
|
+
return this.db.query("INSERT INTO outputs(id, source_id, route, physical_route, text, reply_to, picker, result_attachment, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
1167
|
+
.run(output.id, output.sourceId, JSON.stringify(output.route), physicalRouteKey(output.route), output.text, replyTo ? JSON.stringify(replyTo) : null,
|
|
1168
|
+
output.picker ? JSON.stringify(output.picker) : null, attachment ? JSON.stringify(attachment) : null, output.status ? 1 : 0).changes === 1;
|
|
861
1169
|
}).immediate();
|
|
862
1170
|
}
|
|
863
1171
|
|
|
864
|
-
outputs(): OutputRecord[] {
|
|
1172
|
+
outputs(physicalRoute?: string): OutputRecord[] {
|
|
1173
|
+
if (physicalRoute !== undefined) {
|
|
1174
|
+
return (this.db.query("SELECT * FROM outputs WHERE state = 'pending' AND physical_route = ? ORDER BY sequence")
|
|
1175
|
+
.all(physicalRoute) as OutputRow[]).map(toOutput);
|
|
1176
|
+
}
|
|
865
1177
|
return (this.db.query("SELECT * FROM outputs WHERE state = 'pending' ORDER BY sequence")
|
|
866
1178
|
.all() as OutputRow[]).map(toOutput);
|
|
867
1179
|
}
|
|
@@ -873,14 +1185,30 @@ export class Store implements StorePort {
|
|
|
873
1185
|
(inputs.target IS NULL OR inputs.target = 'main') LIMIT 1`).get() !== null;
|
|
874
1186
|
}
|
|
875
1187
|
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
return this.db.
|
|
883
|
-
.
|
|
1188
|
+
/**
|
|
1189
|
+
* A Discord status update edits the stream's message only after that message's
|
|
1190
|
+
* creation was confirmed. The edit target is persisted with the claim, so a
|
|
1191
|
+
* redelivery of this output keeps the same physical message.
|
|
1192
|
+
*/
|
|
1193
|
+
claimOutput(id: string, editInPlace = false): boolean {
|
|
1194
|
+
return this.db.transaction(() => {
|
|
1195
|
+
const progress = this.getMeta(`progress-output:${id}`);
|
|
1196
|
+
if (progress && !this.progressOpen(JSON.parse(progress))) {
|
|
1197
|
+
this.db.query("UPDATE outputs SET state = 'failed', error = 'Nonterminal progress superseded or no longer authorized' WHERE id = ? AND state = 'pending'").run(id);
|
|
1198
|
+
return false;
|
|
1199
|
+
}
|
|
1200
|
+
const output = this.output(id);
|
|
1201
|
+
if (output?.state !== "pending") return false;
|
|
1202
|
+
const stream = editInPlace ? this.getMeta(`status-stream:${id}`) : null;
|
|
1203
|
+
const anchorId = stream && !output.editOf ? this.getMeta(`status-anchor:${stream}`) : null;
|
|
1204
|
+
const anchor = anchorId ? this.output(anchorId) : null;
|
|
1205
|
+
if (anchor?.state === "sent" && anchor.remoteId && physicalRouteKey(anchor.route) === physicalRouteKey(output.route)) {
|
|
1206
|
+
this.db.query("UPDATE outputs SET edit_of = ? WHERE id = ?")
|
|
1207
|
+
.run(JSON.stringify({ route: physicalRoute(output.route), messageId: anchor.remoteId }), id);
|
|
1208
|
+
}
|
|
1209
|
+
return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'")
|
|
1210
|
+
.run(id).changes === 1;
|
|
1211
|
+
}).immediate();
|
|
884
1212
|
}
|
|
885
1213
|
|
|
886
1214
|
finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void {
|
|
@@ -901,6 +1229,18 @@ export class Store implements StorePort {
|
|
|
901
1229
|
}
|
|
902
1230
|
this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
|
|
903
1231
|
.run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
|
|
1232
|
+
const stream = this.getMeta(`status-stream:${id}`);
|
|
1233
|
+
if (stream) {
|
|
1234
|
+
const anchorKey = `status-anchor:${stream}`;
|
|
1235
|
+
const anchor = this.getMeta(anchorKey);
|
|
1236
|
+
// Only a confirmed new post becomes the message later updates edit;
|
|
1237
|
+
// an uncertain post never does. A rejected edit (for example, the
|
|
1238
|
+
// owner deleted the message) releases it so the next update posts anew.
|
|
1239
|
+
if (state === "sent" && !output.editOf && !anchor) this.setMeta(anchorKey, id);
|
|
1240
|
+
if (state === "failed" && output.editOf && anchor && this.output(anchor)?.remoteId === output.editOf.messageId) {
|
|
1241
|
+
this.db.query("DELETE FROM metadata WHERE key = ?").run(anchorKey);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
904
1244
|
// Start the owner's response window with the durable question receipt,
|
|
905
1245
|
// never with input admission or an unconfirmed send attempt.
|
|
906
1246
|
if (state === "sent" && id === `${output.sourceId}:workspace`
|
|
@@ -928,6 +1268,9 @@ export class Store implements StorePort {
|
|
|
928
1268
|
|| existing.cwd !== lane.cwd || existing.repoRoot !== lane.repoRoot)) {
|
|
929
1269
|
throw new Error("Cannot reuse a lane for a different route or repository");
|
|
930
1270
|
}
|
|
1271
|
+
if (existing && !isDeepStrictEqual(existing.remote, lane.remote)) {
|
|
1272
|
+
throw new Error("Cannot reuse a lane with different remote placement");
|
|
1273
|
+
}
|
|
931
1274
|
if (existing && (!sameLaneModel(existing.model, lane.model) || existing.modelPreset !== lane.modelPreset
|
|
932
1275
|
|| !isDeepStrictEqual(existing.modelPresetSnapshot, lane.modelPresetSnapshot))) {
|
|
933
1276
|
throw new Error("Cannot reuse a lane with a different model; inspect/adopt legacy native state before reusing it");
|
|
@@ -940,10 +1283,10 @@ export class Store implements StorePort {
|
|
|
940
1283
|
}
|
|
941
1284
|
const selected = existing ?? lane;
|
|
942
1285
|
if (!existing) {
|
|
943
|
-
this.db.query("INSERT INTO lanes(id, route_key, generation, data) VALUES (?, ?, ?, ?)")
|
|
944
|
-
.run(lane.id, routeKey(lane.route), lane.generation,
|
|
1286
|
+
this.db.query("INSERT INTO lanes(id, route_key, generation, data, remote) VALUES (?, ?, ?, ?, ?)")
|
|
1287
|
+
.run(lane.id, routeKey(lane.route), lane.generation, laneData({
|
|
945
1288
|
...lane, model: { provider: lane.model.provider, id: lane.model.id },
|
|
946
|
-
}));
|
|
1289
|
+
}), lane.remote ? JSON.stringify(lane.remote) : null);
|
|
947
1290
|
}
|
|
948
1291
|
this.db.query("INSERT INTO lane_sources(source_id, lane_id) VALUES (?, ?)").run(sourceId, selected.id);
|
|
949
1292
|
this.db.query("UPDATE inputs SET target = ? WHERE id = ? AND state = 'pending'").run(selected.id, sourceId);
|
|
@@ -952,12 +1295,12 @@ export class Store implements StorePort {
|
|
|
952
1295
|
}
|
|
953
1296
|
|
|
954
1297
|
lane(id: string): Lane | null {
|
|
955
|
-
const row = this.db.query("SELECT data FROM lanes WHERE id = ?").get(id)
|
|
1298
|
+
const row = this.db.query<LaneRow, [string]>("SELECT data, remote FROM lanes WHERE id = ?").get(id);
|
|
956
1299
|
return row ? toLane(row) : null;
|
|
957
1300
|
}
|
|
958
1301
|
|
|
959
1302
|
laneForRoute(route: Route): Lane | null {
|
|
960
|
-
const row = this.db.query("SELECT data FROM lanes WHERE route_key = ?").get(routeKey(route))
|
|
1303
|
+
const row = this.db.query<LaneRow, [string]>("SELECT data, remote FROM lanes WHERE route_key = ?").get(routeKey(route));
|
|
961
1304
|
return row ? toLane(row) : null;
|
|
962
1305
|
}
|
|
963
1306
|
|
|
@@ -976,7 +1319,7 @@ export class Store implements StorePort {
|
|
|
976
1319
|
if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
|
|
977
1320
|
}
|
|
978
1321
|
return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
979
|
-
.run(
|
|
1322
|
+
.run(laneData(lane), id, generation).changes === 1;
|
|
980
1323
|
}).immediate();
|
|
981
1324
|
}
|
|
982
1325
|
|
|
@@ -988,7 +1331,7 @@ export class Store implements StorePort {
|
|
|
988
1331
|
lane.runtimeState = "starting";
|
|
989
1332
|
lane.pid = null;
|
|
990
1333
|
this.db.query("UPDATE lanes SET generation = ?, data = ? WHERE id = ?")
|
|
991
|
-
.run(lane.generation,
|
|
1334
|
+
.run(lane.generation, laneData(lane), id);
|
|
992
1335
|
return lane;
|
|
993
1336
|
}).immediate();
|
|
994
1337
|
}
|
|
@@ -1003,7 +1346,7 @@ export class Store implements StorePort {
|
|
|
1003
1346
|
lane.model = { provider: model.provider, id: model.id };
|
|
1004
1347
|
lane.modelReason = reason;
|
|
1005
1348
|
return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
1006
|
-
.run(
|
|
1349
|
+
.run(laneData(lane), id, generation).changes === 1;
|
|
1007
1350
|
}).immediate();
|
|
1008
1351
|
}
|
|
1009
1352
|
|
|
@@ -1020,7 +1363,7 @@ export class Store implements StorePort {
|
|
|
1020
1363
|
lane.modelReason = reason;
|
|
1021
1364
|
lane.modelPreset = preset;
|
|
1022
1365
|
lane.modelPresetSnapshot = snapshot === null ? null : structuredClone(snapshot);
|
|
1023
|
-
this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?").run(
|
|
1366
|
+
this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?").run(laneData(lane), id, generation);
|
|
1024
1367
|
for (const [key, value] of Object.entries(metadata)) this.setMeta(key, value);
|
|
1025
1368
|
return true;
|
|
1026
1369
|
}).immediate();
|