omp-superagent 0.1.9 → 0.1.11
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 +68 -21
- package/README.ko.md +30 -372
- package/README.md +31 -419
- package/THIRD_PARTY_NOTICES.md +35 -436
- package/assets/architecture-dark.svg +7 -12
- package/assets/architecture.ko-dark.svg +7 -12
- package/assets/architecture.ko.svg +7 -12
- package/assets/architecture.mmd +5 -13
- package/assets/architecture.svg +7 -12
- package/config.example.json +8 -0
- package/docs/OPERATIONS.en.md +2277 -0
- package/docs/OPERATIONS.md +198 -45
- package/docs/design/execution.md +163 -54
- package/docs/design/messaging.md +125 -34
- package/docs/kakao-bridge-protocol.md +193 -0
- package/docs/releases/0.1.10.md +17 -0
- package/docs/releases/0.1.11.md +18 -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 +10 -11
- package/scripts/{prepare-ulw.ts → prepare-super.ts} +1 -1
- package/skills/head/SKILL.md +36 -5
- package/skills/head/references/routing.md +1 -1
- package/skills/head/references/supervision.md +32 -26
- package/skills/lane/SKILL.md +39 -21
- package/skills/lane/references/workflow.md +23 -16
- package/src/cli.ts +35 -33
- package/src/{config.ts → config/config.ts} +51 -6
- package/src/config/wake-config.ts +36 -0
- package/src/contracts.ts +91 -13
- package/src/{cron-jobs.ts → cron/cron-jobs.ts} +21 -13
- package/src/{cron-pr-intake.ts → cron/cron-pr-intake.ts} +4 -4
- package/src/{cron-schedule.ts → cron/cron-schedule.ts} +3 -3
- package/src/extension.ts +64 -28
- package/src/{gateway-client.ts → gateway/gateway-client.ts} +89 -32
- package/src/{gateway-native.ts → gateway/gateway-native.ts} +4 -4
- package/src/{gateway-protocol.ts → gateway/gateway-protocol.ts} +69 -14
- package/src/{gateway-wire.ts → gateway/gateway-wire.ts} +12 -7
- package/src/gateway-config.ts +1 -1
- package/src/gateway-restart-env.ts +3 -3
- package/src/{group-access.ts → group/group-access.ts} +8 -3
- package/src/{group-policy.ts → group/group-policy.ts} +2 -2
- package/src/{group-runner.ts → group/group-runner.ts} +11 -6
- package/src/host-extension.ts +213 -43
- package/src/host-sdk-helper.ts +62 -65
- package/src/{decision-tool.ts → lane/decision-tool.ts} +12 -4
- package/src/{decisions.ts → lane/decisions.ts} +12 -10
- package/src/{lane-models.ts → lane/lane-models.ts} +1 -1
- package/src/{lane-report.ts → lane/lane-report.ts} +22 -0
- package/src/{lane-rows.ts → lane/lane-rows.ts} +2 -2
- package/src/{lane-watch.ts → lane/lane-watch.ts} +6 -2
- package/src/{workflow.ts → lane/workflow.ts} +1 -1
- package/src/lane-extension.ts +69 -13
- package/src/managed-memory-helper.ts +2 -2
- package/src/{managed-ulw-probe.ts → managed-super-probe.ts} +3 -3
- package/src/{delivery.ts → messaging/delivery.ts} +1 -1
- package/src/{discord-command-registration.ts → messaging/discord-command-registration.ts} +3 -2
- package/src/{discord-context.ts → messaging/discord-context.ts} +1 -1
- package/src/{messenger-command-catalog.json → messaging/messenger-command-catalog.json} +1 -0
- package/src/messaging/messenger-commands.ts +55 -0
- package/src/{result-attachment.ts → messaging/result-attachment.ts} +3 -3
- package/src/{slack-command-registration.ts → messaging/slack-command-registration.ts} +3 -3
- package/src/{telegram-command-registration.ts → messaging/telegram-command-registration.ts} +2 -2
- package/src/omp/head-resume.ts +123 -0
- package/src/{host-owner-path.ts → omp/host-owner-path.ts} +1 -1
- package/src/{host-protocol.ts → omp/host-protocol.ts} +11 -2
- package/src/omp/host-reply-voice.ts +181 -0
- package/src/{host-superkit.ts → omp/host-superkit.ts} +1 -1
- package/src/{host.ts → omp/host.ts} +26 -17
- package/src/{installed-omp.ts → omp/installed-omp.ts} +1 -1
- package/src/{managed-memory.ts → omp/managed-memory.ts} +2 -2
- package/src/{managed-ulw.ts → omp/managed-super.ts} +42 -16
- package/src/omp/native-journal.ts +124 -0
- package/src/{native-launch-profile.ts → omp/native-launch-profile.ts} +6 -2
- package/src/{native-presets.ts → omp/native-presets.ts} +2 -2
- package/src/omp/native-sessions.ts +124 -0
- package/src/{omp-usage.ts → omp/omp-usage.ts} +1 -1
- package/src/omp/soul.ts +214 -0
- package/src/omp/stock-head-launch.ts +31 -0
- package/src/{autostart.ts → operator/autostart.ts} +3 -3
- package/src/{operator.ts → operator/operator.ts} +2 -2
- package/src/{setup-judge.ts → operator/setup-judge.ts} +1 -1
- package/src/{setup-profiles.ts → operator/setup-profiles.ts} +2 -2
- package/src/{setup.ts → operator/setup.ts} +7 -6
- package/src/{pr-intake-automation.ts → pr/pr-intake-automation.ts} +1 -1
- package/src/{pr-intake-mode.ts → pr/pr-intake-mode.ts} +3 -3
- package/src/{pr-intake-review.ts → pr/pr-intake-review.ts} +5 -5
- package/src/{pr-intake-work.ts → pr/pr-intake-work.ts} +1 -1
- package/src/{pr-review-models.ts → pr/pr-review-models.ts} +2 -2
- package/src/{pr-watch.ts → pr/pr-watch.ts} +36 -26
- package/src/{message-order.ts → routing/message-order.ts} +3 -2
- package/src/{topic-history.ts → routing/topic-history.ts} +2 -2
- package/src/{topic-request.ts → routing/topic-request.ts} +4 -2
- package/src/{runtime.ts → runtime/controller.ts} +1278 -1267
- package/src/runtime/deferred-routing.ts +106 -0
- package/src/runtime/dm-timeline.ts +194 -0
- package/src/{head-recovery.ts → runtime/head-recovery.ts} +1 -1
- package/src/{head-rotation.ts → runtime/head-rotation.ts} +32 -5
- package/src/runtime/model-journal.ts +119 -0
- package/src/runtime/native-frames.ts +131 -0
- package/src/{observation-request.ts → runtime/observation-request.ts} +1 -1
- package/src/runtime/preset-sync.ts +232 -0
- package/src/runtime/preset-watch-paths.ts +137 -0
- package/src/runtime/result-attachments.ts +146 -0
- package/src/storage/deferred-routing.ts +149 -0
- package/src/{store.ts → storage/store.ts} +450 -49
- package/src/{worker-bridge.ts → worker/worker-bridge.ts} +2 -2
- package/src/{worker-enrollment.ts → worker/worker-enrollment.ts} +2 -2
- package/src/{worker-host.ts → worker/worker-host.ts} +7 -3
- package/src/{worker-placement.ts → worker/worker-placement.ts} +1 -1
- package/src/{worker-profile.ts → worker/worker-profile.ts} +1 -1
- package/src/{worker-registration.ts → worker/worker-registration.ts} +2 -2
- package/src/{worker-request.ts → worker/worker-request.ts} +5 -5
- package/src/{worker-service.ts → worker/worker-service.ts} +2 -2
- package/src/{worker-trust.ts → worker/worker-trust.ts} +1 -1
- package/src/{worker-wire.ts → worker/worker-wire.ts} +3 -3
- package/src/worker-serve-prepare.ts +4 -4
- package/src/board-extension.ts +0 -217
- package/src/board.ts +0 -467
- package/src/gateway-host-helper.ts +0 -13
- package/src/messenger-commands.ts +0 -15
- package/src/native-sessions.ts +0 -34
- /package/src/{credentials.ts → config/credentials.ts} +0 -0
- /package/src/{dialog.ts → messaging/dialog.ts} +0 -0
- /package/src/{telegram-command-languages.json → messaging/telegram-command-languages.json} +0 -0
- /package/src/{host-broker-services.ts → omp/host-broker-services.ts} +0 -0
- /package/src/{host-inventory-manifest.ts → omp/host-inventory-manifest.ts} +0 -0
- /package/src/{host-services.ts → omp/host-services.ts} +0 -0
- /package/src/{native-settings.ts → omp/native-settings.ts} +0 -0
- /package/src/{superkit-skills.ts → omp/superkit-skills.ts} +0 -0
- /package/src/{repository.ts → operator/repository.ts} +0 -0
- /package/src/{pr-github-schema.ts → pr/pr-github-schema.ts} +0 -0
- /package/src/{pr-github.ts → pr/pr-github.ts} +0 -0
- /package/src/{pr-intake-comment.ts → pr/pr-intake-comment.ts} +0 -0
- /package/src/{pr-intake-fix.ts → pr/pr-intake-fix.ts} +0 -0
- /package/src/{pr-intake-github.ts → pr/pr-intake-github.ts} +0 -0
- /package/src/{pr-intake-material.ts → pr/pr-intake-material.ts} +0 -0
- /package/src/{pr-intake-tree.ts → pr/pr-intake-tree.ts} +0 -0
- /package/src/{head-quota.ts → runtime/head-quota.ts} +0 -0
- /package/src/{worker-checkout.ts → worker/worker-checkout.ts} +0 -0
- /package/src/{worker-destination.ts → worker/worker-destination.ts} +0 -0
- /package/src/{worker-doctor.ts → worker/worker-doctor.ts} +0 -0
- /package/src/{worker-ledger.ts → worker/worker-ledger.ts} +0 -0
- /package/src/{worker-repository.ts → worker/worker-repository.ts} +0 -0
- /package/upstream/{ulw.json → super.json} +0 -0
|
@@ -24,24 +24,30 @@ 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
|
-
|
|
27
|
+
HEAD_MODEL_CONTROL, SCOPE_REVIEW_PREFIX, laneFallbackKey, laneModelPickerRestoreKey, physicalRoute, physicalRouteKey, resolvePickerOption, 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 SettlementOutput, type StorePort, type WorkflowActivation,
|
|
29
|
-
type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope,
|
|
30
|
-
} from "
|
|
31
|
-
import type { ApprovalResolution } from "
|
|
32
|
-
import { captureDecision, resolveDecision } from "
|
|
33
|
-
import { isLaneModel, laneModelArgument, sameLaneModel } from "
|
|
34
|
-
import { laneData, readLaneRows, toLane, type LaneRow } from "
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
40
|
-
import
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
29
|
+
type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope, type ScopeReview, type ScopeReviewNativeProof,
|
|
30
|
+
} from "../contracts.ts";
|
|
31
|
+
import type { ApprovalResolution } from "../contracts";
|
|
32
|
+
import { captureDecision, resolveDecision } from "../lane/decisions";
|
|
33
|
+
import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
|
|
34
|
+
import { laneData, readLaneRows, toLane, type LaneRow } from "../lane/lane-rows";
|
|
35
|
+
import { compareMessageIds } from "../routing/message-order";
|
|
36
|
+
import { storedWorkflowName, workflowChoice } from "../lane/workflow";
|
|
37
|
+
import { laneWaitKey, scopeReviewApproval, type LaneReport } from "../lane/lane-report";
|
|
38
|
+
import { laneWatchReplySource } from "../lane/lane-watch";
|
|
39
|
+
import { isOriginalAttachmentMessage, isResultAttachmentSnapshot } from "../messaging/result-attachment";
|
|
40
|
+
import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
|
|
41
|
+
import type { CronUpdate } from "../cron/cron-jobs";
|
|
42
|
+
import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "../pr/pr-intake-work";
|
|
43
|
+
import { isPrReviewLane, type ReviewRound } from "../pr/pr-intake-review";
|
|
44
|
+
import { DeferredRoutingQueue, type DeferredChoiceRow } from "./deferred-routing";
|
|
43
45
|
|
|
44
46
|
const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
|
|
47
|
+
const SCOPE_CORRECTION_PREFIX = `handoff:${SCOPE_REVIEW_PREFIX}`;
|
|
48
|
+
const SCOPE_REVIEW_NOT_GRANTED = "Scope correction was not authorized. The existing lane scope is unchanged. If needed, send a new, explicit request in this topic.";
|
|
49
|
+
const SCOPE_CORRECTION_NOT_CURRENT = "The scope correction is no longer current. It was not repeated; the existing lane scope is unchanged.";
|
|
50
|
+
const SCOPE_CORRECTION_NO_ANSWER = "The corrective request settled, but the lane returned no final answer.";
|
|
45
51
|
|
|
46
52
|
const SCHEMA = `
|
|
47
53
|
CREATE TABLE IF NOT EXISTS lanes (
|
|
@@ -84,6 +90,17 @@ const SCHEMA = `
|
|
|
84
90
|
remote_id TEXT, UNIQUE(target, generation, request_id)
|
|
85
91
|
);
|
|
86
92
|
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
93
|
+
CREATE TABLE IF NOT EXISTS scope_reviews (
|
|
94
|
+
id TEXT PRIMARY KEY, handoff_id TEXT NOT NULL UNIQUE REFERENCES inputs(id),
|
|
95
|
+
source_id TEXT NOT NULL REFERENCES inputs(id), lane_id TEXT NOT NULL REFERENCES lanes(id),
|
|
96
|
+
generation INTEGER NOT NULL, session_id TEXT NOT NULL, request_id TEXT NOT NULL,
|
|
97
|
+
tool_call_id TEXT, approval_id TEXT REFERENCES approvals(id),
|
|
98
|
+
operator_revision TEXT NOT NULL, lane_revision TEXT NOT NULL,
|
|
99
|
+
state TEXT NOT NULL CHECK(state IN ('candidate','review','granted','closed')),
|
|
100
|
+
correction_id TEXT NOT NULL UNIQUE, correction_requested INTEGER NOT NULL DEFAULT 0
|
|
101
|
+
);
|
|
102
|
+
CREATE INDEX IF NOT EXISTS pending_scope_reviews ON scope_reviews(lane_id)
|
|
103
|
+
WHERE state IN ('review','granted');
|
|
87
104
|
`;
|
|
88
105
|
|
|
89
106
|
const ADMITTED_MESSAGE_SCOPE = `FROM inputs
|
|
@@ -118,6 +135,26 @@ interface OutputRow {
|
|
|
118
135
|
error: string | null;
|
|
119
136
|
}
|
|
120
137
|
interface ApprovalRow { data: string; state: Approval["state"]; remote_id: string | null }
|
|
138
|
+
interface ScopeReviewRow {
|
|
139
|
+
readonly id: string;
|
|
140
|
+
readonly handoff_id: string;
|
|
141
|
+
readonly source_id: string;
|
|
142
|
+
readonly lane_id: string;
|
|
143
|
+
readonly generation: number;
|
|
144
|
+
readonly session_id: string;
|
|
145
|
+
readonly request_id: string;
|
|
146
|
+
readonly tool_call_id: string | null;
|
|
147
|
+
readonly approval_id: string | null;
|
|
148
|
+
readonly operator_revision: string;
|
|
149
|
+
readonly lane_revision: string;
|
|
150
|
+
readonly state: "candidate" | "review" | "granted" | "closed";
|
|
151
|
+
readonly correction_id: string;
|
|
152
|
+
readonly correction_requested: 0 | 1;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
class ScopeReviewError extends Error {
|
|
156
|
+
override readonly name = "ScopeReviewError";
|
|
157
|
+
}
|
|
121
158
|
|
|
122
159
|
const toInput = (row: InputRow): InputRecord => {
|
|
123
160
|
const { workflow, ...input } = JSON.parse(row.data) as Inbound & { workflow?: Omit<WorkflowActivation, "name"> & { name: string } };
|
|
@@ -140,17 +177,20 @@ const inboundData = (input: Inbound): Inbound => ({
|
|
|
140
177
|
id: input.id, route: input.route, messageId: input.messageId, text: input.text,
|
|
141
178
|
...(input.discordOriginalText === undefined ? {} : { discordOriginalText: input.discordOriginalText }),
|
|
142
179
|
...(input.routingText === undefined ? {} : { routingText: input.routingText }),
|
|
180
|
+
...(input.telegramProtectedCommand === undefined ? {} : { telegramProtectedCommand: input.telegramProtectedCommand }),
|
|
181
|
+
...(input.telegramOriginalText === undefined ? {} : { telegramOriginalText: input.telegramOriginalText }),
|
|
143
182
|
...(input.interactionId === undefined ? {} : { interactionId: input.interactionId }),
|
|
144
183
|
...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }),
|
|
145
184
|
...(input.pickerSelection === undefined ? {} : { pickerSelection: input.pickerSelection }),
|
|
146
185
|
...(input.reply === undefined ? {} : { reply: input.reply }),
|
|
186
|
+
...(input.unresolvedReply === undefined ? {} : { unresolvedReply: input.unresolvedReply }),
|
|
147
187
|
...(input.discordContext === undefined ? {} : { discordContext: input.discordContext }),
|
|
148
188
|
receivedAt: input.receivedAt, attachments: input.attachments,
|
|
149
189
|
});
|
|
150
190
|
function inboundIdentity(input: Inbound) {
|
|
151
191
|
// Derived routing text and independently edited references do not change the
|
|
152
192
|
// event identity. Keep the first snapshot, including on pre-upgrade replay.
|
|
153
|
-
const { reply: _reply, discordContext: _context, routingText: _routingText, ...data } = inboundData(input);
|
|
193
|
+
const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText, ...data } = inboundData(input);
|
|
154
194
|
return {
|
|
155
195
|
...data,
|
|
156
196
|
// Slack supplies no command timestamp. A transport redelivery has a fresh
|
|
@@ -176,9 +216,17 @@ function inboundIdentity(input: Inbound) {
|
|
|
176
216
|
}
|
|
177
217
|
|
|
178
218
|
/** Verify immutable inbound identity and return updated attachment URLs if refreshed, or null when unchanged. */
|
|
179
|
-
|
|
219
|
+
function reconcileInboundRedelivery(existing: Inbound, incoming: Inbound): Inbound | null {
|
|
180
220
|
if (isDeepStrictEqual(inboundData(existing), inboundData(incoming))) return null;
|
|
181
|
-
|
|
221
|
+
const candidate = inboundIdentity(incoming);
|
|
222
|
+
// Before the Telegram verdict field existed, unchanged, unmasked prose
|
|
223
|
+
// had the same receipt. Compare that representation; never update the original.
|
|
224
|
+
if (existing.route.platform === "telegram" && existing.telegramProtectedCommand === undefined
|
|
225
|
+
&& candidate.telegramProtectedCommand === false && incoming.routingText === incoming.text
|
|
226
|
+
&& (existing.routingText === undefined || existing.routingText === incoming.routingText)) {
|
|
227
|
+
delete candidate.telegramProtectedCommand;
|
|
228
|
+
}
|
|
229
|
+
if (!isDeepStrictEqual(inboundIdentity(existing), candidate)) {
|
|
182
230
|
throw new Error(`Inbound identity conflict: ${incoming.id}`);
|
|
183
231
|
}
|
|
184
232
|
const urls = new Map(incoming.attachments.map(file => [file.id, file.url]));
|
|
@@ -196,6 +244,7 @@ const approvalIdentity = (approval: Approval) => ({
|
|
|
196
244
|
});
|
|
197
245
|
|
|
198
246
|
export class Store implements StorePort {
|
|
247
|
+
readonly deferredRouting: DeferredRoutingQueue;
|
|
199
248
|
private readonly db: Database;
|
|
200
249
|
private readonly writerLock: Database | null;
|
|
201
250
|
private closed = false;
|
|
@@ -224,6 +273,9 @@ export class Store implements StorePort {
|
|
|
224
273
|
db.run(SCHEMA);
|
|
225
274
|
const laneColumns = db.query<{ name: string }, []>("PRAGMA table_info(lanes)").all();
|
|
226
275
|
if (!laneColumns.some(column => column.name === "remote")) db.run("ALTER TABLE lanes ADD COLUMN remote TEXT");
|
|
276
|
+
const reviewColumns = db.query<{ name: string }, []>("PRAGMA table_info(scope_reviews)").all();
|
|
277
|
+
if (!reviewColumns.some(column => column.name === "tool_call_id")) db.run("ALTER TABLE scope_reviews ADD COLUMN tool_call_id TEXT");
|
|
278
|
+
if (!reviewColumns.some(column => column.name === "approval_id")) db.run("ALTER TABLE scope_reviews ADD COLUMN approval_id TEXT REFERENCES approvals(id)");
|
|
227
279
|
const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
|
|
228
280
|
if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
|
|
229
281
|
if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
|
|
@@ -239,6 +291,7 @@ export class Store implements StorePort {
|
|
|
239
291
|
for (const row of missingPhysical) update.run(physicalRouteKey(JSON.parse(row.route) as Route), row.id);
|
|
240
292
|
})();
|
|
241
293
|
}
|
|
294
|
+
this.deferredRouting = new DeferredRoutingQueue(db, reconcileInboundRedelivery);
|
|
242
295
|
this.db = db;
|
|
243
296
|
this.writerLock = lock;
|
|
244
297
|
} catch (error) {
|
|
@@ -359,11 +412,187 @@ export class Store implements StorePort {
|
|
|
359
412
|
return { lane, failed, original };
|
|
360
413
|
}
|
|
361
414
|
|
|
415
|
+
recordScopeReview(inputId: string, generation: number, sessionId: string, sourceId: string, proof: ScopeReviewNativeProof): boolean {
|
|
416
|
+
return this.db.transaction(() => {
|
|
417
|
+
const handoff = this.input(inputId);
|
|
418
|
+
if (handoff?.state !== "submitted" || !handoff.target || handoff.target === "main" || !handoff.requestId
|
|
419
|
+
|| !proof.toolCallId) return false;
|
|
420
|
+
const id = `${SCOPE_REVIEW_PREFIX}${inputId}`;
|
|
421
|
+
const row: ScopeReviewRow = {
|
|
422
|
+
id, handoff_id: inputId, lane_id: handoff.target, source_id: sourceId, generation, session_id: sessionId,
|
|
423
|
+
request_id: handoff.requestId, tool_call_id: proof.toolCallId, approval_id: proof.approvalId ?? null,
|
|
424
|
+
operator_revision: this.laneOperatorRevision(handoff.target),
|
|
425
|
+
lane_revision: this.scopeLaneRevision(handoff.target), state: "candidate",
|
|
426
|
+
correction_id: `handoff:${id}:${handoff.target}`, correction_requested: 0,
|
|
427
|
+
};
|
|
428
|
+
if (!this.scopeReviewBinding(row)) return false;
|
|
429
|
+
return this.db.query(`INSERT OR IGNORE INTO scope_reviews
|
|
430
|
+
(id, handoff_id, source_id, lane_id, generation, session_id, request_id, tool_call_id, approval_id,
|
|
431
|
+
operator_revision, lane_revision, state, correction_id)
|
|
432
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'candidate', ?)`)
|
|
433
|
+
.run(id, inputId, sourceId, row.lane_id, generation, sessionId, row.request_id,
|
|
434
|
+
row.tool_call_id, row.approval_id, row.operator_revision, row.lane_revision, row.correction_id).changes === 1;
|
|
435
|
+
}).immediate();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
scopeReview(reviewId: string): ScopeReview | null {
|
|
439
|
+
const row = this.db.query<ScopeReviewRow, [string]>("SELECT * FROM scope_reviews WHERE id = ?").get(reviewId);
|
|
440
|
+
if (!row || (row.state !== "review" && row.state !== "granted")) return null;
|
|
441
|
+
const review = this.input(reviewId);
|
|
442
|
+
if (review?.target !== "main" || this.getMeta(`activity-source:${review.id}`) !== row.source_id
|
|
443
|
+
|| this.getMeta(`user-source:${review.id}`) !== null || review.workflow || review.messageId !== null
|
|
444
|
+
|| review.attachments.length || review.reply || review.discordContext || review.pickerSelection
|
|
445
|
+
|| review.interactionId !== undefined || review.invocationId !== undefined) return null;
|
|
446
|
+
if (row.state === "review") {
|
|
447
|
+
if (review.state !== "pending" && (review.state !== "submitted" || !review.requestId || !this.soloScopeAdmission(review.id)
|
|
448
|
+
|| review.generation !== Number(this.getMeta("main:generation") ?? "0"))) return null;
|
|
449
|
+
} else if (review.state !== "done" || !review.requestId) return null;
|
|
450
|
+
const scope = this.scopeReviewBinding(row);
|
|
451
|
+
if (!scope || routeKey(review.route) !== routeKey(scope.original.route)) return null;
|
|
452
|
+
if (row.state === "granted" && !this.scopeCorrectionInput(row, scope)) return null;
|
|
453
|
+
return scope;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
requestScopeCorrection(reviewId: string): string {
|
|
457
|
+
return this.db.transaction(() => {
|
|
458
|
+
const scope = this.scopeReview(reviewId);
|
|
459
|
+
if (!scope || this.input(reviewId)?.state !== "submitted" || this.getMeta("head:restart-fence"))
|
|
460
|
+
throw new ScopeReviewError("Scope correction requires the current submitted HEAD review and exact owner request");
|
|
461
|
+
const row = this.db.query<Pick<ScopeReviewRow, "correction_id">, [string]>(
|
|
462
|
+
"UPDATE scope_reviews SET correction_requested = 1 WHERE id = ? AND state = 'review' RETURNING correction_id",
|
|
463
|
+
).get(reviewId);
|
|
464
|
+
if (!row) throw new ScopeReviewError("Scope review no longer accepts corrective intent");
|
|
465
|
+
return row.correction_id;
|
|
466
|
+
}).immediate();
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
private scopeReviewBinding(row: ScopeReviewRow): ScopeReview | null {
|
|
470
|
+
const handoff = this.input(row.handoff_id);
|
|
471
|
+
const original = this.input(row.source_id);
|
|
472
|
+
const lane = this.lane(row.lane_id);
|
|
473
|
+
if (!handoff || !original || !lane || lane.workState !== "open" || (!lane.route.threadId && !lane.route.topicId)
|
|
474
|
+
|| !row.session_id || lane.sessionId !== row.session_id || lane.generation !== row.generation
|
|
475
|
+
|| row.operator_revision !== this.laneOperatorRevision(lane.id) || row.lane_revision !== this.scopeLaneRevision(lane.id)
|
|
476
|
+
|| this.getMeta("head:restart-fence") || isPrReviewLane(this, lane.id) || this.getMeta(`lane-quota-hold:${lane.id}`)
|
|
477
|
+
|| original.state !== "done" || original.target !== null || original.workflow || original.unresolvedReply || !original.text.trim()
|
|
478
|
+
|| original.text.trimStart().startsWith("/")
|
|
479
|
+
|| original.discordOriginalText !== undefined && original.discordOriginalText.trim() !== original.text.trim()
|
|
480
|
+
|| original.interactionId !== undefined || original.invocationId !== undefined || original.pickerSelection
|
|
481
|
+
|| !isOriginalAttachmentMessage(original) || this.getMeta(`user-source:${original.id}`) !== "true"
|
|
482
|
+
|| this.getMeta(`topic-owner:${original.id}`) !== lane.id
|
|
483
|
+
|| this.getMeta(`topic-creator:${original.id}`) !== null || this.getMeta(`topic-revision:${original.id}`) !== null
|
|
484
|
+
|| this.getMeta(`handoff-source:${original.id}`) !== null || this.getMeta(`activity-source:${original.id}`) !== null
|
|
485
|
+
|| routeKey(original.route) !== routeKey(lane.route) || routeKey(handoff.route) !== routeKey(lane.route)
|
|
486
|
+
|| this.laneForRoute(original.route)?.id !== lane.id
|
|
487
|
+
|| handoff.id !== `handoff:${original.id}:${lane.id}` || handoff.target !== lane.id || handoff.workflow
|
|
488
|
+
|| this.getMeta(`handoff-source:${handoff.id}`) !== original.id
|
|
489
|
+
|| handoff.state !== (row.state === "candidate" ? "submitted" : "done")
|
|
490
|
+
|| handoff.requestId !== row.request_id || handoff.generation !== row.generation || !this.soloScopeAdmission(handoff.id)) return null;
|
|
491
|
+
if (original.messageId === null || this.firstAdmittedMessage(original.route, original.messageId)?.id !== original.id) return null;
|
|
492
|
+
const native = this.getMeta(`lane-observation-owner:${handoff.id}`);
|
|
493
|
+
if (!native || !this.db.query(`SELECT 1 WHERE json_valid(?1)
|
|
494
|
+
AND json_extract(?1, '$.requestId') = ?2 AND json_extract(?1, '$.sessionId') = ?3
|
|
495
|
+
AND json_extract(?1, '$.generation') = ?4 AND json_extract(?1, '$.sessionFile') = ?5`)
|
|
496
|
+
.get(native, row.request_id, row.session_id, row.generation, lane.sessionFile)) return null;
|
|
497
|
+
const latest = this.latestLaneRun(lane.id)?.id;
|
|
498
|
+
if (latest !== handoff.id && (row.state !== "granted" || latest !== row.correction_id)
|
|
499
|
+
|| this.inputs(lane.id).some(input => input.state !== "pending" && input.id !== handoff.id && input.id !== row.correction_id)
|
|
500
|
+
|| this.scopeOwnerSuperseded(original, lane.id)) return null;
|
|
501
|
+
// The exception is only the exact approved call that produced this
|
|
502
|
+
// review receipt. All other native cards remain outside review authority.
|
|
503
|
+
if (row.approval_id !== null) {
|
|
504
|
+
const approval = this.approval(row.approval_id);
|
|
505
|
+
if (!row.tool_call_id || approval?.state !== "answered" || approval.target !== lane.id || approval.generation !== row.generation
|
|
506
|
+
|| routeKey(approval.route) !== routeKey(original.route)
|
|
507
|
+
|| this.getMeta(`topic-approval:${approval.id}`) !== original.id
|
|
508
|
+
|| this.getMeta(`scope-review-approved-input:${approval.id}`) !== handoff.id) return null;
|
|
509
|
+
}
|
|
510
|
+
if (this.db.query(`SELECT 1 FROM approvals
|
|
511
|
+
JOIN metadata AS topic ON topic.key = 'topic-approval:' || approvals.id
|
|
512
|
+
WHERE topic.value IN (?1, ?2) AND approvals.id IS NOT ?3 AND NOT EXISTS (
|
|
513
|
+
SELECT 1 FROM metadata WHERE key = 'scope-correction-approval-input:' || approvals.id
|
|
514
|
+
) LIMIT 1`).get(original.id, handoff.id, row.approval_id)) return null;
|
|
515
|
+
if (this.inputEffects(original, [original.id, handoff.id], () => false)
|
|
516
|
+
.some(effect => effect.state === "uncertain" || effect.state === "sending")) return null;
|
|
517
|
+
return { lane, original, handoff };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private soloScopeAdmission(id: string): boolean {
|
|
521
|
+
return this.getMeta(`steering-owner:${id}`) === id && !this.db.query(`SELECT 1 FROM inputs
|
|
522
|
+
JOIN metadata ON metadata.key = 'steering-owner:' || inputs.id
|
|
523
|
+
WHERE inputs.target = (SELECT target FROM inputs WHERE id = ?1)
|
|
524
|
+
AND inputs.generation = (SELECT generation FROM inputs WHERE id = ?1)
|
|
525
|
+
AND inputs.request_id IS NOT NULL AND inputs.id <> ?1 AND metadata.value = ?1 LIMIT 1`).get(id);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
private scopeOwnerSuperseded(original: InputRecord, laneId: string): boolean {
|
|
529
|
+
const { platform, accountId, authorityId, guildId, channelId, threadId, topicId } = original.route;
|
|
530
|
+
// Retain later owner admissions as a permanent fence, even if they settle
|
|
531
|
+
// without dispatch. Edits and priority controls supersede too.
|
|
532
|
+
if (this.db.query(`SELECT 1 FROM inputs AS newer
|
|
533
|
+
JOIN metadata AS owner ON owner.key = 'user-source:' || newer.id AND owner.value = 'true'
|
|
534
|
+
LEFT JOIN metadata AS topic ON topic.key = 'topic-owner:' || newer.id
|
|
535
|
+
WHERE newer.sequence > (SELECT sequence FROM inputs WHERE id = ?1)
|
|
536
|
+
AND (topic.value = ?2 OR (
|
|
537
|
+
json_extract(newer.data, '$.route.platform') = ?3 AND json_extract(newer.data, '$.route.accountId') = ?4
|
|
538
|
+
AND json_extract(newer.data, '$.route.authorityId') = ?5 AND json_extract(newer.data, '$.route.guildId') IS ?6
|
|
539
|
+
AND json_extract(newer.data, '$.route.channelId') = ?7 AND json_extract(newer.data, '$.route.threadId') IS ?8
|
|
540
|
+
AND json_extract(newer.data, '$.route.topicId') IS ?9
|
|
541
|
+
)) LIMIT 1`).get(original.id, laneId, platform, accountId, authorityId, guildId, channelId, threadId, topicId ?? null)) return true;
|
|
542
|
+
const originalMessageId = original.messageId;
|
|
543
|
+
if (originalMessageId !== null) {
|
|
544
|
+
// Catchup can admit a physically newer original first. Use the exact
|
|
545
|
+
// topic and platform message clock, not an edit ID or arrival time.
|
|
546
|
+
const earlierAdmissions = this.db.query<InputRow, [string, string, string, string, string | null, string | null, string, string | null]>(
|
|
547
|
+
`SELECT inputs.* ${ADMITTED_MESSAGE_SCOPE}
|
|
548
|
+
AND inputs.sequence < (SELECT sequence FROM inputs WHERE id = ?)
|
|
549
|
+
AND json_extract(inputs.data, '$.route.topicId') IS ?`,
|
|
550
|
+
).iterate(platform, channelId, accountId, authorityId, guildId, threadId, original.id, topicId ?? null);
|
|
551
|
+
for (const row of earlierAdmissions) {
|
|
552
|
+
const source = toInput(row);
|
|
553
|
+
if (source.messageId !== null && compareMessageIds(platform, source.messageId, originalMessageId) === 1
|
|
554
|
+
&& isOriginalAttachmentMessage(source)) return true;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (this.deferredRouting.hasOnRoute(original.route, original.id)) return true;
|
|
558
|
+
// Gateway can durably admit an input before head routing classifies it.
|
|
559
|
+
if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get()) return false;
|
|
560
|
+
return this.db.query(`SELECT 1 FROM gateway_events INDEXED BY gateway_events_pending
|
|
561
|
+
WHERE delivered_at IS NULL AND json_extract(data, '$.kind') = 'message'
|
|
562
|
+
AND json_extract(data, '$.input.id') <> ?1
|
|
563
|
+
AND NOT EXISTS (SELECT 1 FROM inputs WHERE id = json_extract(gateway_events.data, '$.input.id'))
|
|
564
|
+
AND json_extract(data, '$.input.route.platform') = ?2 AND json_extract(data, '$.input.route.accountId') = ?3
|
|
565
|
+
AND json_extract(data, '$.input.route.authorityId') = ?4 AND json_extract(data, '$.input.route.guildId') IS ?5
|
|
566
|
+
AND json_extract(data, '$.input.route.channelId') = ?6 AND json_extract(data, '$.input.route.threadId') IS ?7
|
|
567
|
+
LIMIT 1`).get(original.id, platform, accountId, authorityId, guildId, channelId, threadId) !== null;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
private scopeCorrectionInput(row: ScopeReviewRow, scope: ScopeReview): InputRecord | null {
|
|
571
|
+
const input = this.input(row.correction_id);
|
|
572
|
+
if (!input || input.target !== scope.lane.id || input.state !== "pending" && (input.state !== "submitted"
|
|
573
|
+
|| !input.requestId || input.generation !== row.generation || !this.soloScopeAdmission(input.id))
|
|
574
|
+
|| routeKey(input.route) !== routeKey(scope.lane.route) || input.text !== scope.original.text.trim()
|
|
575
|
+
|| input.workflow || input.messageId !== null || input.attachments.length || input.reply || input.discordContext
|
|
576
|
+
|| input.interactionId !== undefined || input.invocationId !== undefined || input.pickerSelection
|
|
577
|
+
|| this.getMeta(`user-source:${input.id}`) !== null || this.getMeta(`topic-owner:${input.id}`) !== null
|
|
578
|
+
|| this.getMeta(`handoff-source:${input.id}`) !== row.id
|
|
579
|
+
|| this.getMeta(`report-approval-source:${row.id}`) !== scope.original.id) return null;
|
|
580
|
+
return input;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
private scopeLaneRevision(id: string): string {
|
|
584
|
+
return this.getMeta(`scope-review-lane-revision:${id}`) ?? "0";
|
|
585
|
+
}
|
|
586
|
+
|
|
362
587
|
reportApprovalSource(id: string): InputRecord | null {
|
|
363
588
|
const input = this.input(id);
|
|
364
589
|
if (!input) return null;
|
|
365
590
|
const reportId = input.target === "main" ? id : this.getMeta(`handoff-source:${id}`);
|
|
366
591
|
if (!reportId || this.input(reportId)?.target !== "main") return null;
|
|
592
|
+
if (reportId.startsWith(SCOPE_REVIEW_PREFIX)) {
|
|
593
|
+
const scope = this.scopeReview(reportId);
|
|
594
|
+
return scope && id === `handoff:${reportId}:${scope.lane.id}` && input.state === "submitted" ? scope.original : null;
|
|
595
|
+
}
|
|
367
596
|
const sourceId = this.getMeta(`report-approval-source:${reportId}`);
|
|
368
597
|
const original = sourceId === null ? null : this.ownerSource(id);
|
|
369
598
|
return original?.id === sourceId ? original : null;
|
|
@@ -427,11 +656,7 @@ export class Store implements StorePort {
|
|
|
427
656
|
if (platform !== "discord" || guildId === null || threadId === null) return false;
|
|
428
657
|
// An input already ACKed to Gateway but still awaiting deferred topic routing
|
|
429
658
|
// has no head receipt yet either; it fences the choice like a pending ledger row.
|
|
430
|
-
const deferred =
|
|
431
|
-
&& (typeof item.messageId === "string" || typeof item.interactionId === "string")
|
|
432
|
-
&& Number.isSafeInteger(item.receivedAt) && item.receivedAt >= input.receivedAt && item.receivedAt <= deadline
|
|
433
|
-
&& item.id !== input.id && physicalRouteKey(item.route) === physicalRouteKey(input.route))
|
|
434
|
-
.map(item => ({ id: item.id, text: item.text, messageId: item.messageId, replyId: item.reply?.messageId ?? null, authoredAt: item.receivedAt }));
|
|
659
|
+
const deferred = this.deferredRouting.choices(input, deadline);
|
|
435
660
|
// Gateway creates the shared ingress ledger; standalone Store use has none.
|
|
436
661
|
const ledger = this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get() !== null;
|
|
437
662
|
const questionId = `${input.id}:workspace`;
|
|
@@ -439,10 +664,7 @@ export class Store implements StorePort {
|
|
|
439
664
|
// The Gateway pending index skips delivered history, including terminal rejections.
|
|
440
665
|
// Unresolved rows stay pending. The durable insert, not its wall-clock timestamp,
|
|
441
666
|
// fences a timely-authored choice even when transport-delayed.
|
|
442
|
-
const rows = ledger ? this.db.query<
|
|
443
|
-
readonly id: string; readonly text: string; readonly messageId: string | null;
|
|
444
|
-
readonly replyId: string | null; readonly authoredAt: number;
|
|
445
|
-
}, [number, number, string, string, string, string, string, string, string]>(`
|
|
667
|
+
const rows = ledger ? this.db.query<DeferredChoiceRow, [number, number, string, string, string, string, string, string, string]>(`
|
|
446
668
|
SELECT json_extract(data, '$.input.id') AS id,
|
|
447
669
|
json_extract(data, '$.input.text') AS text,
|
|
448
670
|
json_extract(data, '$.input.messageId') AS messageId,
|
|
@@ -464,20 +686,22 @@ export class Store implements StorePort {
|
|
|
464
686
|
AND json_extract(data, '$.input.route.threadId') = ?
|
|
465
687
|
`) : null;
|
|
466
688
|
const pending = rows?.iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId) ?? [];
|
|
467
|
-
for (const
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
689
|
+
for (const candidates of [deferred, pending]) {
|
|
690
|
+
for (const row of candidates) {
|
|
691
|
+
if (row.messageId !== null && row.id.startsWith(`discord:${accountId}:${row.messageId}:edit:`)) continue;
|
|
692
|
+
const questionReply = row.replyId !== null && this.sentOutputForMessage(input.route, row.replyId)?.id === questionId;
|
|
693
|
+
const scopedReply = questionReply || row.replyId !== null && row.replyId === input.messageId;
|
|
694
|
+
if (!questionReply && row.authoredAt < deadline - TOPIC_CHOICE_WAIT_MS) continue;
|
|
695
|
+
const text = row.text.trim();
|
|
696
|
+
if (text === "/stop") return true;
|
|
697
|
+
if (row.messageId === null || row.replyId !== null && !scopedReply || /^\/new(?:\s|$)/.test(text)) continue;
|
|
698
|
+
if (/^[1-9]\d*$/.test(text)) return true;
|
|
699
|
+
const request = topicRequest(text);
|
|
700
|
+
if (request.cwd === null ? !scopedReply : request.text.trim()) continue;
|
|
701
|
+
const cwd = existingWorkspace(request.cwd ?? text);
|
|
702
|
+
if (choices.some(ref => cwd !== null ? ref.cwd === cwd
|
|
703
|
+
: request.cwd === null && basename(ref.cwd).toLowerCase() === text.toLowerCase())) return true;
|
|
704
|
+
}
|
|
481
705
|
}
|
|
482
706
|
return false;
|
|
483
707
|
}
|
|
@@ -536,15 +760,24 @@ export class Store implements StorePort {
|
|
|
536
760
|
}
|
|
537
761
|
|
|
538
762
|
hasPendingLaneResult(target: string): boolean {
|
|
763
|
+
if (this.hasPendingScopeReview(target)) return true;
|
|
539
764
|
return this.db.query(`SELECT 1 FROM inputs AS run
|
|
540
765
|
LEFT JOIN inputs AS report ON report.id = 'report:' || run.id
|
|
541
766
|
LEFT JOIN inputs AS recovered ON recovered.id = 'report:' || run.id || ':done'
|
|
542
|
-
LEFT JOIN
|
|
543
|
-
LEFT JOIN outputs AS
|
|
544
|
-
|
|
767
|
+
LEFT JOIN inputs AS scope ON scope.id = ?2 || run.id
|
|
768
|
+
LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer'
|
|
769
|
+
LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer:done'
|
|
770
|
+
WHERE run.target = ?1 AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
|
|
545
771
|
AND (COALESCE(recovered.state, report.state) IN ('pending','submitted','uncertain')
|
|
546
772
|
OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain'))
|
|
547
|
-
LIMIT 1`).get(target) !== null;
|
|
773
|
+
LIMIT 1`).get(target, SCOPE_REVIEW_PREFIX) !== null;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
hasPendingScopeReview(target: string): boolean {
|
|
777
|
+
const rows = this.db.query<Pick<ScopeReviewRow, "id">, [string]>(
|
|
778
|
+
"SELECT id FROM scope_reviews WHERE lane_id = ? AND state IN ('review','granted')",
|
|
779
|
+
).all(target);
|
|
780
|
+
return rows.some(row => this.scopeReview(row.id) !== null);
|
|
548
781
|
}
|
|
549
782
|
|
|
550
783
|
hasPendingLanePlacement(target: string): boolean {
|
|
@@ -557,7 +790,8 @@ export class Store implements StorePort {
|
|
|
557
790
|
hasHeadRecoveryInput(): boolean {
|
|
558
791
|
return this.db.query(`SELECT 1 FROM inputs
|
|
559
792
|
JOIN metadata ON metadata.key = 'head-native-owner:' || inputs.id AND metadata.value <> ''
|
|
560
|
-
WHERE inputs.target = 'main' AND inputs.state = 'uncertain'
|
|
793
|
+
WHERE inputs.target = 'main' AND inputs.state = 'uncertain'
|
|
794
|
+
AND NOT EXISTS (SELECT 1 FROM scope_reviews WHERE scope_reviews.id = inputs.id) LIMIT 1`).get() !== null;
|
|
561
795
|
}
|
|
562
796
|
|
|
563
797
|
kickoffHold(target: string): KickoffHold | null {
|
|
@@ -744,6 +978,17 @@ export class Store implements StorePort {
|
|
|
744
978
|
return this.db.transaction(() => {
|
|
745
979
|
const input = this.input(id);
|
|
746
980
|
if (!input || input.state !== "pending" || input.target === null) return false;
|
|
981
|
+
if (id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) {
|
|
982
|
+
const reviewId = input.target === "main" ? id : this.getMeta(`handoff-source:${id}`);
|
|
983
|
+
const scope = reviewId && this.scopeReview(reviewId);
|
|
984
|
+
if (!scope || this.getMeta(`steering-owner:${id}`) !== id || (input.target === "main"
|
|
985
|
+
? id !== reviewId || generation !== Number(this.getMeta("main:generation") ?? "0")
|
|
986
|
+
: id !== `handoff:${reviewId}:${scope.lane.id}` || generation !== scope.lane.generation)
|
|
987
|
+
|| this.getMeta("head:restart-fence")) {
|
|
988
|
+
this.settle(id, "cancelled");
|
|
989
|
+
return false;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
747
992
|
const progress = this.getMeta(`progress-source:${id}`);
|
|
748
993
|
if (progress && !this.progressOpen(JSON.parse(progress))) {
|
|
749
994
|
this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(id);
|
|
@@ -849,7 +1094,7 @@ export class Store implements StorePort {
|
|
|
849
1094
|
}
|
|
850
1095
|
|
|
851
1096
|
progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace = false): boolean {
|
|
852
|
-
if (!text.trim()) return false;
|
|
1097
|
+
if (!text.trim() || id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) return false;
|
|
853
1098
|
return this.db.transaction(() => {
|
|
854
1099
|
const context = { inputId: id, generation, sessionId };
|
|
855
1100
|
if (!this.progressOpen(context)) return false;
|
|
@@ -982,6 +1227,69 @@ export class Store implements StorePort {
|
|
|
982
1227
|
}).immediate();
|
|
983
1228
|
}
|
|
984
1229
|
|
|
1230
|
+
/** Called only inside settle: one transaction owns the state transition, output and next receipt. */
|
|
1231
|
+
private settleScopeReview(input: InputRecord, state: "done" | "uncertain" | "cancelled", settlement?: SettlementOutput): boolean {
|
|
1232
|
+
const id = input.id;
|
|
1233
|
+
const eligible = input.state === "submitted" && state === "done" && settlement?.scopeReviewEligible === true
|
|
1234
|
+
&& settlement.laneFailure === undefined && !settlement.picker && !this.getMeta("head:restart-fence");
|
|
1235
|
+
const shut = this.db.query("UPDATE scope_reviews SET state = 'closed', correction_requested = 0 WHERE id = ?");
|
|
1236
|
+
if (id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) {
|
|
1237
|
+
const row = id.startsWith(SCOPE_REVIEW_PREFIX)
|
|
1238
|
+
? this.db.query<ScopeReviewRow, [string]>("SELECT * FROM scope_reviews WHERE id = ?").get(id)
|
|
1239
|
+
: this.db.query<ScopeReviewRow, [string]>("SELECT * FROM scope_reviews WHERE correction_id = ?").get(id);
|
|
1240
|
+
if (!row) return true; // Reserved internal identities cannot use ordinary report routing.
|
|
1241
|
+
const scope = this.scopeReview(row.id);
|
|
1242
|
+
if (id === row.id && row.state === "review" && eligible && scope && row.correction_requested === 1
|
|
1243
|
+
&& !this.input(row.correction_id)) {
|
|
1244
|
+
this.insertInput({
|
|
1245
|
+
id: row.correction_id, route: scope.lane.route, messageId: null, receivedAt: scope.original.receivedAt,
|
|
1246
|
+
text: scope.original.text.trim(), attachments: [],
|
|
1247
|
+
}, scope.lane.id, {
|
|
1248
|
+
[`handoff-source:${row.correction_id}`]: id,
|
|
1249
|
+
[`report-approval-source:${id}`]: scope.original.id,
|
|
1250
|
+
}, null);
|
|
1251
|
+
this.db.query("UPDATE scope_reviews SET state = 'granted', correction_requested = 0 WHERE id = ?").run(id);
|
|
1252
|
+
return true; // No HEAD final when the correction was actually admitted.
|
|
1253
|
+
}
|
|
1254
|
+
const correction = id === row.correction_id;
|
|
1255
|
+
const deliver = row.state === (correction ? "granted" : "review");
|
|
1256
|
+
shut.run(row.id);
|
|
1257
|
+
if (deliver && input.state !== "uncertain") {
|
|
1258
|
+
const original = this.input(row.source_id);
|
|
1259
|
+
if (!original || this.getMeta(`user-source:${original.id}`) !== "true" || routeKey(original.route) !== routeKey(input.route)) return true;
|
|
1260
|
+
const answer = settlement?.text.trim();
|
|
1261
|
+
const text = correction
|
|
1262
|
+
? answer || (state === "done" ? SCOPE_CORRECTION_NO_ANSWER : SCOPE_CORRECTION_NOT_CURRENT)
|
|
1263
|
+
: eligible && scope && row.correction_requested === 0 && answer && answer.length <= 1200 ? answer : SCOPE_REVIEW_NOT_GRANTED;
|
|
1264
|
+
this.queueOutput({ id: settlement?.id ?? `${id}:answer`, text, sourceId: original.id, route: original.route });
|
|
1265
|
+
}
|
|
1266
|
+
return true;
|
|
1267
|
+
}
|
|
1268
|
+
const row = this.db.query<ScopeReviewRow, [string]>(
|
|
1269
|
+
"SELECT * FROM scope_reviews WHERE handoff_id = ? AND state = 'candidate'",
|
|
1270
|
+
).get(id);
|
|
1271
|
+
if (!row) return false;
|
|
1272
|
+
const scope = eligible ? this.scopeReviewBinding(row) : null;
|
|
1273
|
+
if (!scope || this.input(row.id)) {
|
|
1274
|
+
shut.run(row.id);
|
|
1275
|
+
// Preserve ordinary answers and failure routing. A completed native
|
|
1276
|
+
// turn with no answer still owes a bounded result at its original source.
|
|
1277
|
+
if (input.state !== "submitted" || state !== "done" || !settlement || settlement.laneFailure !== undefined
|
|
1278
|
+
|| settlement.picker || settlement.text.trim()) return false;
|
|
1279
|
+
const original = this.input(row.source_id);
|
|
1280
|
+
if (!original || this.getMeta(`user-source:${original.id}`) !== "true"
|
|
1281
|
+
|| routeKey(original.route) !== routeKey(input.route)) return false;
|
|
1282
|
+
this.queueOutput({ id: settlement.id, text: SCOPE_REVIEW_NOT_GRANTED, sourceId: original.id, route: original.route });
|
|
1283
|
+
return true;
|
|
1284
|
+
}
|
|
1285
|
+
this.insertInput({
|
|
1286
|
+
id: row.id, route: scope.original.route, messageId: null, receivedAt: scope.original.receivedAt,
|
|
1287
|
+
text: "Internal review of the independently verified original owner request.", attachments: [],
|
|
1288
|
+
}, "main", { [`activity-source:${row.id}`]: scope.original.id }, null);
|
|
1289
|
+
this.db.query("UPDATE scope_reviews SET state = 'review' WHERE id = ?").run(row.id);
|
|
1290
|
+
return true;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
985
1293
|
settle(id: string, state: "done" | "uncertain" | "cancelled", settlement?: SettlementOutput, headModel?: HeadModelChange, editInPlace = false): boolean {
|
|
986
1294
|
return this.db.transaction(() => {
|
|
987
1295
|
const input = this.input(id);
|
|
@@ -999,6 +1307,14 @@ export class Store implements StorePort {
|
|
|
999
1307
|
if (input.state === state && (state !== "uncertain" || !newQuota)) return false;
|
|
1000
1308
|
const pending = this.getMeta(`progress-pending:${id}`);
|
|
1001
1309
|
if (pending) this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(pending);
|
|
1310
|
+
if (this.settleScopeReview(input, state, settlement)) {
|
|
1311
|
+
if (newQuota && input.target && id.startsWith(SCOPE_CORRECTION_PREFIX)) {
|
|
1312
|
+
this.setMeta(quotaKey, "true");
|
|
1313
|
+
this.setMeta(`lane-quota-hold:${input.target}`, id);
|
|
1314
|
+
}
|
|
1315
|
+
this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
|
|
1316
|
+
return true;
|
|
1317
|
+
}
|
|
1002
1318
|
const reportId = `report:${id}`;
|
|
1003
1319
|
if (input.state === "uncertain" && (newQuota || state !== "uncertain")
|
|
1004
1320
|
&& this.getMeta(`lane-recovery-input:${reportId}`) === id
|
|
@@ -1125,6 +1441,10 @@ export class Store implements StorePort {
|
|
|
1125
1441
|
const input = this.requireInput(inputId);
|
|
1126
1442
|
const related = [inputId, ...this.inputs().filter(candidate =>
|
|
1127
1443
|
this.getMeta(`handoff-source:${candidate.id}`) === inputId).map(candidate => candidate.id)];
|
|
1444
|
+
return this.inputEffects(input, related, id => this.approval(id)?.target === "main");
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
private inputEffects(input: InputRecord, related: readonly string[], ownsApproval: (id: string) => boolean): HeadRecoveryEffect[] {
|
|
1128
1448
|
const outputs = (this.db.query("SELECT id,source_id,state FROM outputs ORDER BY sequence").all() as
|
|
1129
1449
|
Array<{ id: string; source_id: string; state: string }>).filter(row => related.includes(row.source_id));
|
|
1130
1450
|
const effects: HeadRecoveryEffect[] = outputs.map(row => ({ id: row.id, kind: "output", state: row.state }));
|
|
@@ -1144,7 +1464,7 @@ export class Store implements StorePort {
|
|
|
1144
1464
|
const relevant = related.includes(row.source ?? "") || outputs.some(output => output.id === row.target)
|
|
1145
1465
|
|| row.operation === "createThread" && input.messageId !== null && row.message === input.messageId
|
|
1146
1466
|
|| (row.operation === "showApproval" || row.operation === "dismissApproval")
|
|
1147
|
-
&&
|
|
1467
|
+
&& row.target !== null && ownsApproval(row.target);
|
|
1148
1468
|
if (relevant) effects.push({ id: row.id, kind: row.operation,
|
|
1149
1469
|
state: row.state === "attempted" || row.certainty === "uncertain" || row.ok === null ? "uncertain"
|
|
1150
1470
|
: row.ok === 0 ? "failed" : "sent" });
|
|
@@ -1158,6 +1478,7 @@ export class Store implements StorePort {
|
|
|
1158
1478
|
const input = this.input(attempt.inputId);
|
|
1159
1479
|
if (attempt.state !== "prepared" || this.getMeta("head:recovery-active")
|
|
1160
1480
|
|| this.getMeta(`head:recovery:${attempt.inputId}`) || input?.target !== "main" || input.state !== "uncertain"
|
|
1481
|
+
|| input.id.startsWith(SCOPE_REVIEW_PREFIX)
|
|
1161
1482
|
|| input.requestId !== attempt.requestId || input.generation !== attempt.generation
|
|
1162
1483
|
|| this.getMeta("head:stop-boundary") !== attempt.stopBoundary) return false;
|
|
1163
1484
|
this.setMeta(`head:recovery:${attempt.inputId}`, JSON.stringify(attempt));
|
|
@@ -1285,6 +1606,29 @@ export class Store implements StorePort {
|
|
|
1285
1606
|
}).immediate();
|
|
1286
1607
|
}
|
|
1287
1608
|
|
|
1609
|
+
saveHeadJobs(bindingKey: string, owners: readonly (readonly [string, string, string])[],
|
|
1610
|
+
outputs: readonly Pick<OutputRecord, "id" | "sourceId" | "route" | "text">[] = []): void {
|
|
1611
|
+
this.db.transaction(() => {
|
|
1612
|
+
for (const output of outputs) this.queueOutput(output);
|
|
1613
|
+
if (owners.length) this.setMeta(bindingKey, JSON.stringify(owners));
|
|
1614
|
+
else this.db.query("DELETE FROM metadata WHERE key = ?").run(bindingKey);
|
|
1615
|
+
}).immediate();
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
recordRestartCheckpointFailure(expectedFence: string, stopBoundary: string | null, failedFence: string,
|
|
1619
|
+
output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean {
|
|
1620
|
+
return this.db.transaction(() => {
|
|
1621
|
+
// The Rust Gateway writes the stop boundary through its own connection.
|
|
1622
|
+
// Do not reserve the only result ID if that operator stop already won.
|
|
1623
|
+
if (this.getMeta("head:restart-fence") !== expectedFence
|
|
1624
|
+
|| this.getMeta("gateway:operator-stop") !== stopBoundary) return false;
|
|
1625
|
+
this.setMeta(`head:restart:${output.sourceId}`, failedFence);
|
|
1626
|
+
this.setMeta("head:restart-fence", failedFence);
|
|
1627
|
+
if (!this.output(output.id)) this.queueOutput(output);
|
|
1628
|
+
return true;
|
|
1629
|
+
}).immediate();
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1288
1632
|
recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
|
|
1289
1633
|
return this.db.transaction(() => {
|
|
1290
1634
|
const marker = `head:hold-notice:${blockerId}`;
|
|
@@ -1319,6 +1663,14 @@ export class Store implements StorePort {
|
|
|
1319
1663
|
(inputs.target IS NULL OR inputs.target = 'main') LIMIT 1`).get() !== null;
|
|
1320
1664
|
}
|
|
1321
1665
|
|
|
1666
|
+
hasHeadSleepWork(): boolean {
|
|
1667
|
+
return this.db.query(`SELECT 1 WHERE
|
|
1668
|
+
EXISTS (SELECT 1 FROM inputs WHERE ${ACTIVE_INPUTS}) OR
|
|
1669
|
+
EXISTS (SELECT 1 FROM deferred_routing) OR
|
|
1670
|
+
EXISTS (SELECT 1 FROM approvals WHERE state = 'pending') OR
|
|
1671
|
+
EXISTS (SELECT 1 FROM outputs WHERE state IN ('pending','sending','uncertain'))`).get() !== null;
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1322
1674
|
/**
|
|
1323
1675
|
* A Discord status update edits the stream's message only after that message's
|
|
1324
1676
|
* creation was confirmed. The edit target is persisted with the claim, so a
|
|
@@ -1452,6 +1804,10 @@ export class Store implements StorePort {
|
|
|
1452
1804
|
return this.db.transaction(() => {
|
|
1453
1805
|
const lane = this.lane(id);
|
|
1454
1806
|
if (!lane || lane.generation !== generation) return false;
|
|
1807
|
+
if ((patch.workState !== undefined && patch.workState !== lane.workState)
|
|
1808
|
+
|| (patch.sessionId !== undefined && patch.sessionId !== lane.sessionId)) {
|
|
1809
|
+
this.setMeta(`scope-review-lane-revision:${id}`, String(BigInt(this.scopeLaneRevision(id)) + 1n));
|
|
1810
|
+
}
|
|
1455
1811
|
// Explicitly copy the contract whitelist; runtime callers cannot change identity.
|
|
1456
1812
|
for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result"] as const) {
|
|
1457
1813
|
if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
|
|
@@ -1461,6 +1817,18 @@ export class Store implements StorePort {
|
|
|
1461
1817
|
}).immediate();
|
|
1462
1818
|
}
|
|
1463
1819
|
|
|
1820
|
+
retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath">): boolean {
|
|
1821
|
+
return this.db.transaction(() => {
|
|
1822
|
+
const lane = this.lane(expected.id);
|
|
1823
|
+
if (!lane || lane.remote || expected.pid === null || lane.generation !== expected.generation
|
|
1824
|
+
|| lane.pid !== expected.pid || lane.sessionId !== expected.sessionId || lane.socketPath !== expected.socketPath) return false;
|
|
1825
|
+
lane.pid = null;
|
|
1826
|
+
if (lane.runtimeState !== "unloaded") lane.runtimeState = "interrupted";
|
|
1827
|
+
return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
|
|
1828
|
+
.run(laneData(lane), lane.id, lane.generation).changes === 1;
|
|
1829
|
+
}).immediate();
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1464
1832
|
private sentLaneModelPicker(source: InputRecord) {
|
|
1465
1833
|
const selection = source.pickerSelection;
|
|
1466
1834
|
if (source.route.platform !== "discord" || selection?.target !== "lane" || selection.confirmed !== undefined
|
|
@@ -1599,11 +1967,19 @@ export class Store implements StorePort {
|
|
|
1599
1967
|
if (reportSource) {
|
|
1600
1968
|
if (routeKey(reportSource.route) !== routeKey(approval.route))
|
|
1601
1969
|
throw new Error(`Approval does not match its original report source: ${approval.id}`);
|
|
1970
|
+
if (owner.id.startsWith(SCOPE_CORRECTION_PREFIX)) {
|
|
1971
|
+
this.setMeta(`topic-approval:${approval.id}`, reportSource.id);
|
|
1972
|
+
this.setMeta(`scope-correction-approval-input:${approval.id}`, owner.id);
|
|
1973
|
+
}
|
|
1602
1974
|
} else {
|
|
1603
1975
|
const topic = this.topicDelivery(owner.id);
|
|
1604
1976
|
if (!topic || routeKey(topic.route) !== routeKey(approval.route))
|
|
1605
1977
|
throw new Error(`Approval does not match its topic source: ${approval.id}`);
|
|
1606
1978
|
this.setMeta(`topic-approval:${approval.id}`, topic.source.id);
|
|
1979
|
+
if (owner.state === "submitted" && owner.requestId && owner.id === `handoff:${topic.source.id}:${approval.target}`
|
|
1980
|
+
&& scopeReviewApproval(approval.request)) {
|
|
1981
|
+
this.setMeta(`scope-review-approval-input:${approval.id}`, owner.id);
|
|
1982
|
+
}
|
|
1607
1983
|
}
|
|
1608
1984
|
} else this.checkTarget(approval.target, approval.route);
|
|
1609
1985
|
const lane = this.lane(approval.target);
|
|
@@ -1631,9 +2007,25 @@ export class Store implements StorePort {
|
|
|
1631
2007
|
if (!approval || approval.state !== "pending" || approval.generation !== generation) return false;
|
|
1632
2008
|
const lane = this.lane(approval.target);
|
|
1633
2009
|
if (state === "answered" && lane && (lane.generation !== generation || lane.workState !== "open")) return false;
|
|
2010
|
+
const correction = this.getMeta(`scope-correction-approval-input:${approval.id}`);
|
|
2011
|
+
if (correction && state === "answered" && !this.reportApprovalSource(correction)) {
|
|
2012
|
+
const response = resolution?.response;
|
|
2013
|
+
const request = approval.request;
|
|
2014
|
+
const denied = isDeepStrictEqual(response, { cancelled: true })
|
|
2015
|
+
|| request.method === "confirm" && isDeepStrictEqual(response, { confirmed: false })
|
|
2016
|
+
|| request.method === "select" && Array.isArray(request.options) && request.options.includes("Deny")
|
|
2017
|
+
&& isDeepStrictEqual(response, { value: "Deny" });
|
|
2018
|
+
if (!denied || resolution?.headSelection) return false;
|
|
2019
|
+
}
|
|
1634
2020
|
resolveDecision(this, approval, state, resolution);
|
|
1635
|
-
|
|
2021
|
+
const resolved = this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
|
|
1636
2022
|
.run(state, id, generation).changes === 1;
|
|
2023
|
+
if (resolved && state === "answered" && resolution?.headSelection === undefined
|
|
2024
|
+
&& resolution?.response && scopeReviewApproval(approval.request, resolution.response)) {
|
|
2025
|
+
const inputId = this.getMeta(`scope-review-approval-input:${id}`);
|
|
2026
|
+
if (inputId) this.setMeta(`scope-review-approved-input:${id}`, inputId);
|
|
2027
|
+
}
|
|
2028
|
+
return resolved;
|
|
1637
2029
|
}).immediate();
|
|
1638
2030
|
}
|
|
1639
2031
|
|
|
@@ -1661,6 +2053,15 @@ export class Store implements StorePort {
|
|
|
1661
2053
|
.run(key, value);
|
|
1662
2054
|
}
|
|
1663
2055
|
|
|
2056
|
+
completeHistoryBoundary(key: string, cursor: string, sequence: string | null): void {
|
|
2057
|
+
// A reconnect may have been queued (or staged by ordered Discord
|
|
2058
|
+
// verification) while this read was running. Preserve its oldest pin.
|
|
2059
|
+
this.db.query("UPDATE metadata SET value = '' WHERE key = ? AND value = ? AND "
|
|
2060
|
+
+ "(SELECT value FROM metadata WHERE key = 'gateway:history-sequence') IS ? AND "
|
|
2061
|
+
+ "NOT EXISTS(SELECT 1 FROM metadata WHERE key = 'gateway:discord-history-staged')")
|
|
2062
|
+
.run(key, cursor, sequence);
|
|
2063
|
+
}
|
|
2064
|
+
|
|
1664
2065
|
close(): void {
|
|
1665
2066
|
if (this.closed) return;
|
|
1666
2067
|
this.db.close(true);
|