omp-superagent 0.1.13 → 0.1.15
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 +8 -5
- package/THIRD_PARTY_NOTICES.md +6 -0
- package/assets/architecture-dark.svg +4 -4
- package/assets/architecture.ko-dark.svg +4 -4
- package/assets/architecture.ko.svg +4 -4
- package/assets/architecture.mmd +5 -5
- package/assets/architecture.svg +4 -4
- package/config.example.json +1 -0
- package/docs/OPERATIONS.en.md +59 -23
- package/docs/OPERATIONS.md +53 -18
- package/docs/design/execution.md +161 -43
- package/docs/design/messaging.md +45 -9
- package/docs/releases/0.1.15.md +13 -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 +6 -3
- package/scripts/prepare-worker-memory.ts +37 -0
- package/skills/head/SKILL.md +22 -47
- package/skills/head/references/routing.md +11 -12
- package/skills/head/references/supervision.md +10 -14
- package/skills/lane/SKILL.md +14 -16
- package/skills/lane/references/workflow.md +14 -27
- package/src/cli.ts +56 -56
- package/src/config/config.ts +4 -0
- package/src/contracts.ts +34 -27
- package/src/cron/cron-jobs.ts +4 -3
- package/src/cron/cron-pr-intake.ts +1 -2
- package/src/extension.ts +57 -14
- package/src/gateway/gateway-client.ts +14 -12
- package/src/group/group-runner.ts +3 -2
- package/src/group-runner-extension.ts +7 -3
- package/src/host-extension.ts +109 -2
- package/src/host-sdk-helper.ts +6 -1
- package/src/lane/decision-tool.ts +2 -3
- package/src/lane/lane-report.ts +8 -30
- package/src/lane/lane-rows.ts +1 -1
- package/src/lane/workflow.ts +44 -3
- package/src/lane-extension.ts +5 -46
- package/src/messaging/discord-context.ts +8 -6
- package/src/omp/host-protocol.ts +4 -3
- package/src/omp/host.ts +24 -7
- package/src/omp/managed-super.ts +43 -27
- package/src/omp/native-sessions.ts +12 -0
- package/src/omp/worker-memory-import.ts +410 -0
- package/src/omp/worker-memory-sdk.ts +8 -0
- package/src/operator/setup.ts +8 -13
- package/src/pr/pr-github-schema.ts +9 -0
- package/src/pr/pr-github.ts +6 -2
- package/src/pr/pr-intake-automation.ts +11 -8
- package/src/pr/pr-intake-fix.ts +2 -5
- package/src/pr/pr-intake-review.ts +7 -7
- package/src/routing/topic-history.ts +2 -2
- package/src/runtime/controller.ts +444 -408
- package/src/runtime/head-recovery.ts +7 -7
- package/src/runtime/worker-memory.ts +156 -0
- package/src/storage/deferred-routing.ts +1 -7
- package/src/storage/store.ts +441 -375
- package/src/worker/worker-host.ts +3 -2
- package/src/worker/worker-ledger.ts +20 -11
- package/src/worker/worker-memory-page.ts +83 -0
- package/src/worker/worker-memory-proofs.ts +260 -0
- package/src/worker/worker-memory-source.ts +305 -0
- package/src/worker/worker-memory-storage.ts +130 -0
- package/src/worker/worker-profile.ts +2 -0
- package/src/worker/worker-repository.ts +92 -7
- package/src/worker/worker-request.ts +1 -0
- package/src/worker/worker-service.ts +25 -8
- package/src/worker/worker-wire.ts +20 -6
package/src/storage/store.ts
CHANGED
|
@@ -19,14 +19,14 @@
|
|
|
19
19
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
20
20
|
* SOFTWARE.
|
|
21
21
|
*/
|
|
22
|
-
import { Database } from "bun:sqlite";
|
|
22
|
+
import { Database, SQLiteError } from "bun:sqlite";
|
|
23
23
|
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,
|
|
27
|
+
HEAD_MODEL_CONTROL, headRecoveryEffectsSettled, isRetiredScopeInput, 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,
|
|
29
|
+
type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope,
|
|
30
30
|
} from "../contracts.ts";
|
|
31
31
|
import type { ApprovalResolution } from "../contracts";
|
|
32
32
|
import { captureDecision, resolveDecision } from "../lane/decisions";
|
|
@@ -34,9 +34,9 @@ import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-mode
|
|
|
34
34
|
import { laneData, readLaneRows, toLane, type LaneRow } from "../lane/lane-rows";
|
|
35
35
|
import { compareMessageIds } from "../routing/message-order";
|
|
36
36
|
import { storedWorkflowName, workflowChoice } from "../lane/workflow";
|
|
37
|
-
import { laneWaitKey,
|
|
37
|
+
import { laneWaitKey, type LaneReport } from "../lane/lane-report";
|
|
38
38
|
import { laneWatchReplySource } from "../lane/lane-watch";
|
|
39
|
-
import {
|
|
39
|
+
import { isResultAttachmentSnapshot } from "../messaging/result-attachment";
|
|
40
40
|
import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
|
|
41
41
|
import type { CronUpdate } from "../cron/cron-jobs";
|
|
42
42
|
import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "../pr/pr-intake-work";
|
|
@@ -44,10 +44,8 @@ import { isPrReviewLane, type ReviewRound } from "../pr/pr-intake-review";
|
|
|
44
44
|
import { DeferredRoutingQueue, type DeferredChoiceRow } from "./deferred-routing";
|
|
45
45
|
|
|
46
46
|
const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
|
|
47
|
-
const
|
|
48
|
-
|
|
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.";
|
|
47
|
+
const retiredScopeId = (column: "id" | "source_id" | "retired.id" | "newer.id") =>
|
|
48
|
+
`(${column} GLOB 'scope-review:*' OR ${column} GLOB 'handoff:scope-review:*')`;
|
|
51
49
|
|
|
52
50
|
const SCHEMA = `
|
|
53
51
|
CREATE TABLE IF NOT EXISTS lanes (
|
|
@@ -90,17 +88,6 @@ const SCHEMA = `
|
|
|
90
88
|
remote_id TEXT, UNIQUE(target, generation, request_id)
|
|
91
89
|
);
|
|
92
90
|
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');
|
|
104
91
|
`;
|
|
105
92
|
|
|
106
93
|
const ADMITTED_MESSAGE_SCOPE = `FROM inputs
|
|
@@ -135,26 +122,6 @@ interface OutputRow {
|
|
|
135
122
|
error: string | null;
|
|
136
123
|
}
|
|
137
124
|
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
|
-
}
|
|
158
125
|
|
|
159
126
|
const toInput = (row: InputRow): InputRecord => {
|
|
160
127
|
const { workflow, ...input } = JSON.parse(row.data) as Inbound & { workflow?: Omit<WorkflowActivation, "name"> & { name: string } };
|
|
@@ -273,9 +240,6 @@ export class Store implements StorePort {
|
|
|
273
240
|
db.run(SCHEMA);
|
|
274
241
|
const laneColumns = db.query<{ name: string }, []>("PRAGMA table_info(lanes)").all();
|
|
275
242
|
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)");
|
|
279
243
|
const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
|
|
280
244
|
if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
|
|
281
245
|
if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
|
|
@@ -294,6 +258,8 @@ export class Store implements StorePort {
|
|
|
294
258
|
this.deferredRouting = new DeferredRoutingQueue(db, reconcileInboundRedelivery);
|
|
295
259
|
this.db = db;
|
|
296
260
|
this.writerLock = lock;
|
|
261
|
+
this.retireScopeRecords();
|
|
262
|
+
this.retireScopeApprovals();
|
|
297
263
|
} catch (error) {
|
|
298
264
|
db?.close(true);
|
|
299
265
|
lock?.close(true);
|
|
@@ -301,6 +267,93 @@ export class Store implements StorePort {
|
|
|
301
267
|
}
|
|
302
268
|
}
|
|
303
269
|
|
|
270
|
+
private retireScopeRecords(): void {
|
|
271
|
+
this.db.transaction(() => {
|
|
272
|
+
if (this.getMeta("migration:retire-scope-review") === "true") return;
|
|
273
|
+
// Keep native admissions and delivery receipts. Pending synthetic work
|
|
274
|
+
// never ran; an admission or send without a final receipt is uncertain.
|
|
275
|
+
this.db.run(`UPDATE inputs SET state = CASE state WHEN 'pending' THEN 'cancelled' ELSE 'uncertain' END
|
|
276
|
+
WHERE state IN ('pending','submitted') AND ${retiredScopeId("id")}`);
|
|
277
|
+
this.retireScopeOutputs();
|
|
278
|
+
if (this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'scope_reviews'").get()) {
|
|
279
|
+
this.db.run("UPDATE scope_reviews SET state = 'closed', correction_requested = 0 WHERE state <> 'closed' OR correction_requested <> 0");
|
|
280
|
+
}
|
|
281
|
+
const active = this.getMeta("main:active-lane-recovery");
|
|
282
|
+
if (active && isRetiredScopeInput(active)) this.setMeta("main:active-lane-recovery", "");
|
|
283
|
+
// Legacy HEAD reviews did not record a per-prompt native owner.
|
|
284
|
+
const headSession = this.getMeta("main:sessionId");
|
|
285
|
+
const headGeneration = Number(this.getMeta("main:generation") ?? "0");
|
|
286
|
+
if (headSession && this.db.query(`SELECT 1 FROM inputs WHERE target = 'main' AND generation = ?
|
|
287
|
+
AND request_id IS NOT NULL AND state IN ('uncertain','cancelled') AND ${retiredScopeId("id")} LIMIT 1`)
|
|
288
|
+
.get(headGeneration)) this.setMeta(`retired-scope-head-session:${headGeneration}`, headSession);
|
|
289
|
+
|
|
290
|
+
this.setMeta("migration:retire-scope-review", "true");
|
|
291
|
+
}).immediate();
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private retireScopeApprovals(): void {
|
|
295
|
+
this.db.transaction(() => {
|
|
296
|
+
if (this.getMeta("migration:retire-scope-approvals") === "true") return;
|
|
297
|
+
// Before 3e03dd1, HEAD never stored its scope-review input on the
|
|
298
|
+
// card. A submitted review could create any dialog on its original
|
|
299
|
+
// route. A sibling route or generation rules it out; an existing
|
|
300
|
+
// approval row, method or native UI ID does not.
|
|
301
|
+
const headReviews = this.db.query<InputRow & { sequence: number }, []>(`SELECT data,target,state,request_id,generation,sequence
|
|
302
|
+
FROM inputs WHERE target = 'main' AND request_id IS NOT NULL AND state IN ('uncertain','cancelled')
|
|
303
|
+
AND ${retiredScopeId("id")} ORDER BY sequence`).all();
|
|
304
|
+
const lastReview = new Map(headReviews.map(row => [
|
|
305
|
+
JSON.stringify([row.generation, routeKey(toInput(row).route)]), row.sequence,
|
|
306
|
+
]));
|
|
307
|
+
// scope-review-approval-input was also stamped on ordinary topic
|
|
308
|
+
// selects. Only the HEAD and correction markers prove retirement.
|
|
309
|
+
const approvals = this.db.query<ApprovalRow, []>(`SELECT approvals.* FROM approvals WHERE EXISTS (
|
|
310
|
+
SELECT 1 FROM metadata WHERE key IN (
|
|
311
|
+
'scope-head-approval-input:' || approvals.id,
|
|
312
|
+
'scope-correction-approval-input:' || approvals.id,
|
|
313
|
+
'native-approval-held:' || approvals.id
|
|
314
|
+
)) OR (target = 'main' AND generation IN (SELECT generation FROM inputs
|
|
315
|
+
WHERE target = 'main' AND request_id IS NOT NULL AND state IN ('uncertain','cancelled')
|
|
316
|
+
AND ${retiredScopeId("id")}))`).all();
|
|
317
|
+
for (const row of approvals) {
|
|
318
|
+
const approval = toApproval(row);
|
|
319
|
+
const marked = this.getMeta(`scope-head-approval-input:${approval.id}`) !== null
|
|
320
|
+
|| this.getMeta(`scope-correction-approval-input:${approval.id}`) !== null
|
|
321
|
+
|| this.getMeta(`native-approval-held:${approval.id}`) !== null;
|
|
322
|
+
if (!marked) {
|
|
323
|
+
const sequence = lastReview.get(JSON.stringify([approval.generation, routeKey(approval.route)]));
|
|
324
|
+
if (sequence === undefined || this.hasLaterHeadDecisionOwner(approval, sequence)) continue;
|
|
325
|
+
}
|
|
326
|
+
if (approval.state === "pending") {
|
|
327
|
+
this.resolveApproval(approval.id, approval.generation, "cancelled", { reason: "Retired scope workflow; no native response sent" });
|
|
328
|
+
}
|
|
329
|
+
this.setMeta(`native-approval-held:${approval.id}`, "true");
|
|
330
|
+
this.setMeta(`retired-approval-dismissal:${approval.id}`, "pending");
|
|
331
|
+
}
|
|
332
|
+
this.setMeta("migration:retire-scope-approvals", "true");
|
|
333
|
+
}).immediate();
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private hasLaterHeadDecisionOwner(approval: Approval, retiredSequence: number): boolean {
|
|
337
|
+
const decision = approval.decision;
|
|
338
|
+
// This source is embedded in a tracked decision, unlike a generic
|
|
339
|
+
// confirmation. An original owner source admitted after every possible
|
|
340
|
+
// legacy review cannot be that review's original source.
|
|
341
|
+
if (!decision?.sourceId || this.getMeta(`user-source:${decision.sourceId}`) !== "true") return false;
|
|
342
|
+
const row = this.db.query<InputRow, [string, number, number, string]>(`SELECT inputs.data,target,state,request_id,generation
|
|
343
|
+
FROM inputs JOIN metadata AS native ON native.key = 'head-native-owner:' || inputs.id
|
|
344
|
+
AND json_valid(native.value)
|
|
345
|
+
WHERE inputs.id = ?1 AND sequence > ?2 AND target = 'main' AND generation = ?3
|
|
346
|
+
AND state IN ('submitted','done','uncertain')
|
|
347
|
+
AND json_extract(native.value, '$.requestId') = request_id
|
|
348
|
+
AND json_extract(native.value, '$.generation') = generation
|
|
349
|
+
AND json_extract(native.value, '$.sessionId') = ?4
|
|
350
|
+
AND json_type(native.value, '$.sessionFile') = 'text'
|
|
351
|
+
AND length(json_extract(native.value, '$.sessionFile')) > 0
|
|
352
|
+
AND json_type(native.value, '$.cursor') IN ('text','null')`)
|
|
353
|
+
.get(decision.sourceId, retiredSequence, approval.generation, decision.sessionId);
|
|
354
|
+
return row !== null && !isRetiredScopeInput(decision.sourceId) && routeKey(toInput(row).route) === routeKey(approval.route);
|
|
355
|
+
}
|
|
356
|
+
|
|
304
357
|
receive(input: Inbound, target: string | null, metadata: Readonly<Record<string, string>> = {}, workflow: WorkflowActivation | null = null): boolean {
|
|
305
358
|
if (input.discordOriginalText !== undefined && (input.route.platform !== "discord" || input.messageId === null
|
|
306
359
|
|| input.interactionId !== undefined || typeof input.discordOriginalText !== "string")) {
|
|
@@ -358,6 +411,7 @@ export class Store implements StorePort {
|
|
|
358
411
|
}
|
|
359
412
|
return false; // A replay never changes its current assignment or state.
|
|
360
413
|
}
|
|
414
|
+
if (isRetiredScopeInput(input.id)) throw new Error(`Retired scope workflow input: ${input.id}`);
|
|
361
415
|
if (workflow !== null) {
|
|
362
416
|
workflowChoice({ name: workflow.name, reason: workflow.reason });
|
|
363
417
|
if (workflow.provenance === "user") {
|
|
@@ -388,11 +442,12 @@ export class Store implements StorePort {
|
|
|
388
442
|
|
|
389
443
|
ownerSource(id: string): InputRecord | null {
|
|
390
444
|
let source = this.input(id);
|
|
391
|
-
while (source &&
|
|
445
|
+
while (source && !isRetiredScopeInput(source.id)) {
|
|
446
|
+
if (this.getMeta(`user-source:${source.id}`) === "true") return source;
|
|
392
447
|
const linked = this.getMeta(`handoff-source:${source.id}`) ?? this.getMeta(`activity-source:${source.id}`);
|
|
393
448
|
source = linked ? this.input(linked) : null;
|
|
394
449
|
}
|
|
395
|
-
return
|
|
450
|
+
return null;
|
|
396
451
|
}
|
|
397
452
|
|
|
398
453
|
laneRecoveryScope(reportId: string): LaneRecoveryScope | null {
|
|
@@ -412,187 +467,11 @@ export class Store implements StorePort {
|
|
|
412
467
|
return { lane, failed, original };
|
|
413
468
|
}
|
|
414
469
|
|
|
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
|
-
|
|
587
470
|
reportApprovalSource(id: string): InputRecord | null {
|
|
588
471
|
const input = this.input(id);
|
|
589
|
-
if (!input) return null;
|
|
472
|
+
if (!input || isRetiredScopeInput(id)) return null;
|
|
590
473
|
const reportId = input.target === "main" ? id : this.getMeta(`handoff-source:${id}`);
|
|
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
|
-
}
|
|
474
|
+
if (!reportId || isRetiredScopeInput(reportId) || this.input(reportId)?.target !== "main") return null;
|
|
596
475
|
const sourceId = this.getMeta(`report-approval-source:${reportId}`);
|
|
597
476
|
const original = sourceId === null ? null : this.ownerSource(id);
|
|
598
477
|
return original?.id === sourceId ? original : null;
|
|
@@ -601,11 +480,14 @@ export class Store implements StorePort {
|
|
|
601
480
|
private topicOwner(input: InputRecord): InputRecord | null {
|
|
602
481
|
if (!input.target || input.target === "main") return null;
|
|
603
482
|
let source: InputRecord | null = input;
|
|
604
|
-
while (source &&
|
|
483
|
+
while (source && !isRetiredScopeInput(source.id)) {
|
|
484
|
+
if (this.getMeta(`user-source:${source.id}`) === "true") {
|
|
485
|
+
return this.getMeta(`topic-owner:${source.id}`) === input.target ? source : null;
|
|
486
|
+
}
|
|
605
487
|
const linked: string | null = this.getMeta(`handoff-source:${source.id}`);
|
|
606
488
|
source = linked ? this.input(linked) : null;
|
|
607
489
|
}
|
|
608
|
-
return
|
|
490
|
+
return null;
|
|
609
491
|
}
|
|
610
492
|
|
|
611
493
|
topicDelivery(id: string) {
|
|
@@ -760,24 +642,20 @@ export class Store implements StorePort {
|
|
|
760
642
|
}
|
|
761
643
|
|
|
762
644
|
hasPendingLaneResult(target: string): boolean {
|
|
763
|
-
if (this.
|
|
645
|
+
if (this.hasLegacyScopeReviews() && this.db.query(`SELECT 1 FROM scope_reviews AS review
|
|
646
|
+
JOIN outputs ON outputs.id IN (review.id || ':answer', review.correction_id || ':answer')
|
|
647
|
+
WHERE review.lane_id = ? AND outputs.state IN ('pending','sending','uncertain') LIMIT 1`).get(target)) return true;
|
|
764
648
|
return this.db.query(`SELECT 1 FROM inputs AS run
|
|
765
649
|
LEFT JOIN inputs AS report ON report.id = 'report:' || run.id
|
|
766
650
|
LEFT JOIN inputs AS recovered ON recovered.id = 'report:' || run.id || ':done'
|
|
767
|
-
LEFT JOIN
|
|
768
|
-
LEFT JOIN outputs AS
|
|
769
|
-
LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer:done'
|
|
651
|
+
LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, run.id) || ':answer'
|
|
652
|
+
LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, run.id) || ':answer:done'
|
|
770
653
|
WHERE run.target = ?1 AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
|
|
771
654
|
AND (COALESCE(recovered.state, report.state) IN ('pending','submitted','uncertain')
|
|
772
|
-
OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain')
|
|
773
|
-
|
|
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);
|
|
655
|
+
OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain')
|
|
656
|
+
-- A retired review cannot run, but its interrupted send still holds this lane.
|
|
657
|
+
OR EXISTS (SELECT 1 FROM outputs WHERE id = 'scope-review:' || run.id || ':answer' AND state = 'uncertain'))
|
|
658
|
+
LIMIT 1`).get(target) !== null;
|
|
781
659
|
}
|
|
782
660
|
|
|
783
661
|
hasPendingLanePlacement(target: string): boolean {
|
|
@@ -787,11 +665,36 @@ export class Store implements StorePort {
|
|
|
787
665
|
LIMIT 1`).get(target) !== null;
|
|
788
666
|
}
|
|
789
667
|
|
|
668
|
+
hasWorkerMemoryHold(target: string): boolean {
|
|
669
|
+
return this.db.query(`SELECT 1 WHERE
|
|
670
|
+
EXISTS (SELECT 1 FROM inputs WHERE (target IS NULL OR target IN ('main', ?1)) AND ${ACTIVE_INPUTS}) OR
|
|
671
|
+
EXISTS (SELECT 1 FROM approvals WHERE target IN ('main', ?1) AND state = 'pending')`).get(target) !== null
|
|
672
|
+
|| this.hasPendingLaneResult(target);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
tryWorkerMemoryMeta(keys: string | readonly string[], value: string): boolean {
|
|
676
|
+
const batch = typeof keys === "string" ? [keys] : keys;
|
|
677
|
+
if (!batch.every(key => key.startsWith("worker-memory:"))) throw new Error("Invalid worker memory receipt key");
|
|
678
|
+
const policy = this.db.query<{ timeout: number }, []>("PRAGMA busy_timeout").get();
|
|
679
|
+
if (!policy || this.db.inTransaction) return false;
|
|
680
|
+
this.db.run("PRAGMA busy_timeout = 0");
|
|
681
|
+
try {
|
|
682
|
+
// One autocommit for the entire page. A concurrent ingress writer
|
|
683
|
+
// cannot reserve only a suffix/prefix of its native fact IDs.
|
|
684
|
+
this.db.query(`INSERT INTO metadata(key,value) SELECT value, ?2 FROM json_each(?1) WHERE true
|
|
685
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(JSON.stringify(batch), value);
|
|
686
|
+
return true;
|
|
687
|
+
} catch (error) {
|
|
688
|
+
if (error instanceof SQLiteError && [5, 6].includes(error.errno & 255)) return false;
|
|
689
|
+
throw error;
|
|
690
|
+
} finally { this.db.run(`PRAGMA busy_timeout = ${policy.timeout}`); }
|
|
691
|
+
}
|
|
692
|
+
|
|
790
693
|
hasHeadRecoveryInput(): boolean {
|
|
791
694
|
return this.db.query(`SELECT 1 FROM inputs
|
|
792
695
|
JOIN metadata ON metadata.key = 'head-native-owner:' || inputs.id AND metadata.value <> ''
|
|
793
696
|
WHERE inputs.target = 'main' AND inputs.state = 'uncertain'
|
|
794
|
-
AND NOT
|
|
697
|
+
AND NOT ${retiredScopeId("id")} LIMIT 1`).get() !== null;
|
|
795
698
|
}
|
|
796
699
|
|
|
797
700
|
kickoffHold(target: string): KickoffHold | null {
|
|
@@ -818,6 +721,25 @@ export class Store implements StorePort {
|
|
|
818
721
|
).all(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId, messageId).map(toInput);
|
|
819
722
|
}
|
|
820
723
|
|
|
724
|
+
isLateTopicOriginal(source: InputRecord): boolean {
|
|
725
|
+
const { messageId, route } = source;
|
|
726
|
+
if (messageId === null) return false;
|
|
727
|
+
// Normally this is the newest physical message. A higher cursor alone is
|
|
728
|
+
// not proof: it may belong to another logical topic or a later admission.
|
|
729
|
+
const cursor = this.getMeta(`cursor:${physicalRouteKey(route)}`);
|
|
730
|
+
if (cursor === messageId && this.getMeta(`topic-revision:${source.id}`) === null) return false;
|
|
731
|
+
const rows = this.db.query<{ messageId: string }, [string, string, string, string, string | null, string | null, string | null, string]>(
|
|
732
|
+
`SELECT json_extract(inputs.data, '$.messageId') AS messageId ${ADMITTED_MESSAGE_SCOPE}
|
|
733
|
+
AND json_extract(inputs.data, '$.route.topicId') IS ? AND inputs.sequence < (SELECT sequence FROM inputs WHERE id = ?)
|
|
734
|
+
ORDER BY inputs.sequence DESC`,
|
|
735
|
+
).iterate(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId, route.topicId ?? null, source.id);
|
|
736
|
+
for (const earlier of rows) {
|
|
737
|
+
const order = compareMessageIds(route.platform, earlier.messageId, messageId);
|
|
738
|
+
if (order === 1 || order === 0) return true;
|
|
739
|
+
}
|
|
740
|
+
return false;
|
|
741
|
+
}
|
|
742
|
+
|
|
821
743
|
/** Recognize a misplaced choice without exposing another thread's question or granting it a vote. */
|
|
822
744
|
isDiscordWorkspaceQuestion(route: Route, messageId: string): boolean {
|
|
823
745
|
if (route.platform !== "discord") return false;
|
|
@@ -977,18 +899,7 @@ export class Store implements StorePort {
|
|
|
977
899
|
submit(id: string, requestId: string, generation: number): boolean {
|
|
978
900
|
return this.db.transaction(() => {
|
|
979
901
|
const input = this.input(id);
|
|
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
|
-
}
|
|
902
|
+
if (!input || input.state !== "pending" || input.target === null || isRetiredScopeInput(id)) return false;
|
|
992
903
|
const progress = this.getMeta(`progress-source:${id}`);
|
|
993
904
|
if (progress && !this.progressOpen(JSON.parse(progress))) {
|
|
994
905
|
this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(id);
|
|
@@ -1020,12 +931,32 @@ export class Store implements StorePort {
|
|
|
1020
931
|
}).immediate();
|
|
1021
932
|
}
|
|
1022
933
|
|
|
934
|
+
submitGoalResume(input: Inbound, target: string, sourceId: string, owner: Parameters<StorePort["submitGoalResume"]>[3],
|
|
935
|
+
priorWorkState?: Lane["workState"]): InputRecord {
|
|
936
|
+
return this.db.transaction(() => {
|
|
937
|
+
if (target !== "main") {
|
|
938
|
+
const lane = this.lane(target);
|
|
939
|
+
if (!lane || lane.workState !== priorWorkState || lane.workState === "cancelled" || lane.sessionId !== owner.sessionId
|
|
940
|
+
|| lane.generation !== owner.generation || !this.updateLane(target, owner.generation, {
|
|
941
|
+
workState: "open", runtimeState: "running", lastActivityAt: Date.now(),
|
|
942
|
+
})) throw new Error("The original lane changed before goal resume");
|
|
943
|
+
}
|
|
944
|
+
// Separate from prompt ownership: an interrupted goal resume must never replay as a prompt.
|
|
945
|
+
if (!this.receive(input, target, {
|
|
946
|
+
[`handoff-source:${input.id}`]: sourceId,
|
|
947
|
+
[`native-goal-resume-owner:${input.id}`]: JSON.stringify(owner),
|
|
948
|
+
}) || !this.submit(input.id, owner.requestId, owner.generation)) throw new Error("Native goal resume was not admitted");
|
|
949
|
+
return this.requireInput(input.id);
|
|
950
|
+
}).immediate();
|
|
951
|
+
}
|
|
952
|
+
|
|
1023
953
|
private progressOpen(context: { inputId: string; generation: number; sessionId: string }): boolean {
|
|
1024
954
|
const input = this.input(context.inputId);
|
|
1025
|
-
if (!input || input.state !== "submitted" || input.generation !== context.generation
|
|
955
|
+
if (!input || input.state !== "submitted" || input.generation !== context.generation
|
|
956
|
+
|| isRetiredScopeInput(input.id) || this.laneRecoveryObsolete(input.id)) return false;
|
|
1026
957
|
const sourceId = this.getMeta(`handoff-source:${input.id}`);
|
|
1027
958
|
const source = sourceId ? this.input(sourceId) : input;
|
|
1028
|
-
if (!source || source.state === "cancelled" || source.state === "uncertain") return false;
|
|
959
|
+
if (!source || isRetiredScopeInput(source.id) || source.state === "cancelled" || source.state === "uncertain") return false;
|
|
1029
960
|
if (input.target === "main") {
|
|
1030
961
|
const parent = this.getMeta(`progress-source:${input.id}`);
|
|
1031
962
|
return (!parent || this.progressOpen(JSON.parse(parent)))
|
|
@@ -1094,7 +1025,7 @@ export class Store implements StorePort {
|
|
|
1094
1025
|
}
|
|
1095
1026
|
|
|
1096
1027
|
progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace = false): boolean {
|
|
1097
|
-
if (!text.trim()
|
|
1028
|
+
if (!text.trim()) return false;
|
|
1098
1029
|
return this.db.transaction(() => {
|
|
1099
1030
|
const context = { inputId: id, generation, sessionId };
|
|
1100
1031
|
if (!this.progressOpen(context)) return false;
|
|
@@ -1227,73 +1158,16 @@ export class Store implements StorePort {
|
|
|
1227
1158
|
}).immediate();
|
|
1228
1159
|
}
|
|
1229
1160
|
|
|
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
|
-
|
|
1293
1161
|
settle(id: string, state: "done" | "uncertain" | "cancelled", settlement?: SettlementOutput, headModel?: HeadModelChange, editInPlace = false): boolean {
|
|
1294
1162
|
return this.db.transaction(() => {
|
|
1295
1163
|
const input = this.input(id);
|
|
1296
1164
|
if (!input || input.state === "done" || input.state === "cancelled") return false;
|
|
1165
|
+
if (isRetiredScopeInput(id)) {
|
|
1166
|
+
// Explicit resolution may close a held receipt, but it cannot turn
|
|
1167
|
+
// retired work into a successful result or ordinary delivery.
|
|
1168
|
+
if (state !== "cancelled") return false;
|
|
1169
|
+
return this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ?").run(id).changes === 1;
|
|
1170
|
+
}
|
|
1297
1171
|
const progress = this.getMeta(`progress-source:${id}`);
|
|
1298
1172
|
const output = settlement && (!progress || this.progressOpen(JSON.parse(progress))) && !this.laneRecoveryObsolete(id)
|
|
1299
1173
|
? { id: settlement.id, text: settlement.text, picker: settlement.picker } : undefined;
|
|
@@ -1307,14 +1181,6 @@ export class Store implements StorePort {
|
|
|
1307
1181
|
if (input.state === state && (state !== "uncertain" || !newQuota)) return false;
|
|
1308
1182
|
const pending = this.getMeta(`progress-pending:${id}`);
|
|
1309
1183
|
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
|
-
}
|
|
1318
1184
|
const reportId = `report:${id}`;
|
|
1319
1185
|
if (input.state === "uncertain" && (newQuota || state !== "uncertain")
|
|
1320
1186
|
&& this.getMeta(`lane-recovery-input:${reportId}`) === id
|
|
@@ -1390,8 +1256,11 @@ export class Store implements StorePort {
|
|
|
1390
1256
|
} else {
|
|
1391
1257
|
this.queueOutput({ ...output, sourceId: id, route: input.route });
|
|
1392
1258
|
}
|
|
1393
|
-
} else {
|
|
1394
|
-
|
|
1259
|
+
} else if (this.queueOutput({ ...output, sourceId: id, route: input.route })
|
|
1260
|
+
&& settlement?.discordHeadFollowups?.length && state === "done" && input.state === "submitted"
|
|
1261
|
+
&& input.target === "main" && input.route.platform === "discord" && output.id === `${id}:answer`
|
|
1262
|
+
&& !output.picker && output.text.trim() && this.ownerSource(id)?.id === id) {
|
|
1263
|
+
this.setMeta(`discord-head-followups:${output.id}`, JSON.stringify(settlement.discordHeadFollowups));
|
|
1395
1264
|
}
|
|
1396
1265
|
}
|
|
1397
1266
|
this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
|
|
@@ -1439,16 +1308,15 @@ export class Store implements StorePort {
|
|
|
1439
1308
|
|
|
1440
1309
|
headRecoveryEffects(inputId: string): HeadRecoveryEffect[] {
|
|
1441
1310
|
const input = this.requireInput(inputId);
|
|
1442
|
-
const related = [inputId
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
private inputEffects(input: InputRecord, related: readonly string[], ownsApproval: (id: string) => boolean): HeadRecoveryEffect[] {
|
|
1311
|
+
const related = new Set([inputId]);
|
|
1312
|
+
for (const candidate of this.inputs()) {
|
|
1313
|
+
if (this.getMeta(`handoff-source:${candidate.id}`) === inputId) related.add(candidate.id);
|
|
1314
|
+
}
|
|
1448
1315
|
const outputs = (this.db.query("SELECT id,source_id,state FROM outputs ORDER BY sequence").all() as
|
|
1449
|
-
Array<{ id: string; source_id: string; state: string }>).filter(row => related.
|
|
1316
|
+
Array<{ id: string; source_id: string; state: string }>).filter(row => related.has(row.source_id));
|
|
1450
1317
|
const effects: HeadRecoveryEffect[] = outputs.map(row => ({ id: row.id, kind: "output", state: row.state }));
|
|
1451
1318
|
if (this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='gateway_effects'").get()) {
|
|
1319
|
+
const outputIds = new Set(outputs.map(row => row.id));
|
|
1452
1320
|
// Never select arguments/results into a model-visible snapshot. The SQL
|
|
1453
1321
|
// projection reads only identity and delivery certainty, not credentials.
|
|
1454
1322
|
const rows = this.db.query(`SELECT id,operation,state,
|
|
@@ -1461,10 +1329,10 @@ export class Store implements StorePort {
|
|
|
1461
1329
|
Array<{ id: string; operation: string; state: string; source: string | null; target: string | null;
|
|
1462
1330
|
message: string | null; certainty: string | null; ok: number | null }>;
|
|
1463
1331
|
for (const row of rows) {
|
|
1464
|
-
const relevant = related.
|
|
1332
|
+
const relevant = related.has(row.source ?? "") || (row.target !== null && outputIds.has(row.target))
|
|
1465
1333
|
|| row.operation === "createThread" && input.messageId !== null && row.message === input.messageId
|
|
1466
1334
|
|| (row.operation === "showApproval" || row.operation === "dismissApproval")
|
|
1467
|
-
&& row.target !== null &&
|
|
1335
|
+
&& row.target !== null && this.approval(row.target)?.target === "main";
|
|
1468
1336
|
if (relevant) effects.push({ id: row.id, kind: row.operation,
|
|
1469
1337
|
state: row.state === "attempted" || row.certainty === "uncertain" || row.ok === null ? "uncertain"
|
|
1470
1338
|
: row.ok === 0 ? "failed" : "sent" });
|
|
@@ -1478,7 +1346,7 @@ export class Store implements StorePort {
|
|
|
1478
1346
|
const input = this.input(attempt.inputId);
|
|
1479
1347
|
if (attempt.state !== "prepared" || this.getMeta("head:recovery-active")
|
|
1480
1348
|
|| this.getMeta(`head:recovery:${attempt.inputId}`) || input?.target !== "main" || input.state !== "uncertain"
|
|
1481
|
-
|| input.id
|
|
1349
|
+
|| isRetiredScopeInput(input.id)
|
|
1482
1350
|
|| input.requestId !== attempt.requestId || input.generation !== attempt.generation
|
|
1483
1351
|
|| this.getMeta("head:stop-boundary") !== attempt.stopBoundary) return false;
|
|
1484
1352
|
this.setMeta(`head:recovery:${attempt.inputId}`, JSON.stringify(attempt));
|
|
@@ -1490,7 +1358,7 @@ export class Store implements StorePort {
|
|
|
1490
1358
|
commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean {
|
|
1491
1359
|
return this.db.transaction(() => {
|
|
1492
1360
|
const input = this.input(expected.inputId);
|
|
1493
|
-
if (this.getMeta("head:recovery-active") !== expected.inputId
|
|
1361
|
+
if (isRetiredScopeInput(expected.inputId) || this.getMeta("head:recovery-active") !== expected.inputId
|
|
1494
1362
|
|| this.getMeta(`head:recovery:${expected.inputId}`) !== JSON.stringify(expected)
|
|
1495
1363
|
|| decided.decision?.decision === "release" && this.getMeta("head:stop-boundary") !== expected.stopBoundary
|
|
1496
1364
|
|| input?.target !== "main" || input.state !== "uncertain"
|
|
@@ -1498,8 +1366,7 @@ export class Store implements StorePort {
|
|
|
1498
1366
|
|| decided.attemptId !== expected.attemptId || decided.inputId !== expected.inputId
|
|
1499
1367
|
|| !decided.decision || !["decided", "settled"].includes(decided.state)) return false;
|
|
1500
1368
|
if (decided.decision.decision === "release") {
|
|
1501
|
-
if (!decided.outcome || this.headRecoveryEffects(input.id)
|
|
1502
|
-
!["sent", "complete", "failed"].includes(effect.state))) return false;
|
|
1369
|
+
if (!decided.outcome || !headRecoveryEffectsSettled(this.headRecoveryEffects(input.id))) return false;
|
|
1503
1370
|
if (decided.state === "settled") this.settle(input.id, decided.outcome, { id: `${input.id}:recovery:${expected.attemptId}`,
|
|
1504
1371
|
text: decided.outcome === "done"
|
|
1505
1372
|
? "원래 세션의 정확한 요청 접수 기록과 마지막 실행 근거로 native 처리 종료를 확인했습니다. 사용자 작업의 완료·수락 기준 충족을 주장하지 않으며 원래 작업을 다시 실행하지 않았습니다."
|
|
@@ -1547,6 +1414,7 @@ export class Store implements StorePort {
|
|
|
1547
1414
|
}
|
|
1548
1415
|
|
|
1549
1416
|
queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
|
|
1417
|
+
if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) return false;
|
|
1550
1418
|
if (output.status && (output.route.platform !== "discord" || output.picker || output.resultAttachment)) {
|
|
1551
1419
|
throw new Error(`Status delivery requires a plain Discord message: ${output.id}`);
|
|
1552
1420
|
}
|
|
@@ -1559,6 +1427,7 @@ export class Store implements StorePort {
|
|
|
1559
1427
|
|| !isDeepStrictEqual(existing.resultAttachment, output.resultAttachment)
|
|
1560
1428
|
|| output.replyTo !== undefined && (!existing.replyTo
|
|
1561
1429
|
|| existing.replyTo.messageId !== output.replyTo.messageId
|
|
1430
|
+
|| existing.replyTo.requireExisting !== output.replyTo.requireExisting
|
|
1562
1431
|
|| physicalRouteKey(existing.replyTo.route) !== physicalRouteKey(output.replyTo.route))) {
|
|
1563
1432
|
throw new Error(`Output identity conflict: ${output.id}`);
|
|
1564
1433
|
}
|
|
@@ -1595,7 +1464,8 @@ export class Store implements StorePort {
|
|
|
1595
1464
|
const replyOrigin = original ?? laneWatchReplySource(this, source, output.id);
|
|
1596
1465
|
const replyTo = replyOrigin?.route.platform === "discord" && replyOrigin.messageId
|
|
1597
1466
|
&& physicalRouteKey(replyOrigin.route) === physicalRouteKey(output.route)
|
|
1598
|
-
? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId
|
|
1467
|
+
? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId,
|
|
1468
|
+
...(output.replyTo?.requireExisting ? { requireExisting: true } : {}) } : undefined;
|
|
1599
1469
|
if (output.replyTo !== undefined && (!replyTo || output.replyTo.messageId !== replyTo.messageId
|
|
1600
1470
|
|| physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
|
|
1601
1471
|
throw new Error(`Output reply differs from its source: ${output.id}`);
|
|
@@ -1671,6 +1541,66 @@ export class Store implements StorePort {
|
|
|
1671
1541
|
EXISTS (SELECT 1 FROM outputs WHERE state IN ('pending','sending','uncertain'))`).get() !== null;
|
|
1672
1542
|
}
|
|
1673
1543
|
|
|
1544
|
+
private hasLegacyScopeReviews(): boolean {
|
|
1545
|
+
return this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'scope_reviews'").get() !== null;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
private retireScopeOutputs(): void {
|
|
1549
|
+
const scope = `(${retiredScopeId("id")} OR ${retiredScopeId("source_id")})`;
|
|
1550
|
+
this.db.run(`UPDATE outputs SET state = 'uncertain',
|
|
1551
|
+
error = 'Retired scope workflow; delivery interrupted before a durable receipt'
|
|
1552
|
+
WHERE state = 'sending' AND ${scope}`);
|
|
1553
|
+
const pending = this.db.query<OutputRow, []>(`SELECT * FROM outputs WHERE state = 'pending' AND ${scope}`).all();
|
|
1554
|
+
const hasReviews = pending.length > 0 && this.hasLegacyScopeReviews();
|
|
1555
|
+
const fail = this.db.query(`UPDATE outputs SET state = 'failed',
|
|
1556
|
+
error = 'Retired scope workflow; no delivery attempted' WHERE id = ?`);
|
|
1557
|
+
for (const row of pending) {
|
|
1558
|
+
if (!hasReviews || !this.isSettledLegacyScopeAnswer(toOutput(row))) fail.run(row.id);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
private isSettledLegacyScopeAnswer(output: OutputRecord): boolean {
|
|
1563
|
+
// The old settlement transaction closed the review, queued the final
|
|
1564
|
+
// answer using source_id, and marked the synthetic admission done.
|
|
1565
|
+
if (!output.id.endsWith(":answer")) return false;
|
|
1566
|
+
const resultInputId = output.id.slice(0, -":answer".length);
|
|
1567
|
+
const review = this.db.query<{
|
|
1568
|
+
id: string; correction_id: string; handoff_id: string; lane_id: string; generation: number; request_id: string;
|
|
1569
|
+
}, [string, string]>(`SELECT id, correction_id, handoff_id, lane_id, generation, request_id
|
|
1570
|
+
FROM scope_reviews WHERE state = 'closed' AND correction_requested = 0 AND source_id = ?1
|
|
1571
|
+
AND (?2 = id OR ?2 = correction_id)`).get(output.sourceId, resultInputId);
|
|
1572
|
+
if (!review || review.id !== `scope-review:${review.handoff_id}`
|
|
1573
|
+
|| review.handoff_id !== `handoff:${output.sourceId}:${review.lane_id}`
|
|
1574
|
+
|| review.correction_id !== `handoff:${review.id}:${review.lane_id}`
|
|
1575
|
+
|| output.remoteId !== null || output.editOf || output.status || output.picker || output.resultAttachment
|
|
1576
|
+
|| !output.text.trim()) return false;
|
|
1577
|
+
const source = this.input(output.sourceId);
|
|
1578
|
+
const handoff = this.input(review.handoff_id);
|
|
1579
|
+
const reviewed = this.input(review.id);
|
|
1580
|
+
if (!source?.messageId || source.target !== null || source.state !== "done"
|
|
1581
|
+
|| isRetiredScopeInput(source.id) || this.getMeta(`user-source:${source.id}`) !== "true"
|
|
1582
|
+
|| this.getMeta(`topic-owner:${source.id}`) !== review.lane_id
|
|
1583
|
+
|| handoff?.target !== review.lane_id || handoff.state !== "done"
|
|
1584
|
+
|| !handoff.requestId || handoff.requestId !== review.request_id || handoff.generation !== review.generation
|
|
1585
|
+
|| this.getMeta(`handoff-source:${handoff.id}`) !== source.id
|
|
1586
|
+
|| reviewed?.target !== "main" || reviewed.state !== "done" || !reviewed.requestId || reviewed.generation === null
|
|
1587
|
+
|| this.getMeta(`activity-source:${reviewed.id}`) !== source.id) return false;
|
|
1588
|
+
const route = routeKey(source.route);
|
|
1589
|
+
if (routeKey(handoff.route) !== route || routeKey(reviewed.route) !== route || routeKey(output.route) !== route) return false;
|
|
1590
|
+
if (resultInputId === review.correction_id) {
|
|
1591
|
+
const correction = this.input(review.correction_id);
|
|
1592
|
+
if (correction?.target !== review.lane_id || correction.state !== "done" || !correction.requestId
|
|
1593
|
+
|| correction.generation !== review.generation || routeKey(correction.route) !== route
|
|
1594
|
+
|| this.getMeta(`handoff-source:${correction.id}`) !== reviewed.id
|
|
1595
|
+
|| this.getMeta(`report-approval-source:${reviewed.id}`) !== source.id) return false;
|
|
1596
|
+
} else if (this.input(review.correction_id)) {
|
|
1597
|
+
return false; // The old review did not queue an answer when it granted a correction.
|
|
1598
|
+
}
|
|
1599
|
+
return source.route.platform === "discord"
|
|
1600
|
+
? output.replyTo?.messageId === source.messageId && routeKey(output.replyTo.route) === physicalRouteKey(source.route)
|
|
1601
|
+
: output.replyTo === undefined;
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1674
1604
|
/**
|
|
1675
1605
|
* A Discord status update edits the stream's message only after that message's
|
|
1676
1606
|
* creation was confirmed. The edit target is persisted with the claim, so a
|
|
@@ -1685,6 +1615,15 @@ export class Store implements StorePort {
|
|
|
1685
1615
|
}
|
|
1686
1616
|
const output = this.output(id);
|
|
1687
1617
|
if (output?.state !== "pending") return false;
|
|
1618
|
+
if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) {
|
|
1619
|
+
// Only the existing immutable answer can be sent. Do not consult live
|
|
1620
|
+
// lane/HEAD ownership or mutate its historical reply/edit destination.
|
|
1621
|
+
if (this.hasLegacyScopeReviews() && this.isSettledLegacyScopeAnswer(output)) {
|
|
1622
|
+
return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'").run(id).changes === 1;
|
|
1623
|
+
}
|
|
1624
|
+
this.db.query("UPDATE outputs SET state = 'failed', error = 'Retired scope workflow; no delivery attempted' WHERE id = ?").run(id);
|
|
1625
|
+
return false;
|
|
1626
|
+
}
|
|
1688
1627
|
if (this.laneRecoveryObsolete(output.sourceId)) {
|
|
1689
1628
|
this.suppressLaneReport(output.sourceId, "Lane recovery report no longer has current owner authority");
|
|
1690
1629
|
return false;
|
|
@@ -1712,13 +1651,22 @@ export class Store implements StorePort {
|
|
|
1712
1651
|
if (output.resultAttachment && state === "pending") {
|
|
1713
1652
|
throw new Error(`A result attachment is never retried: ${id}`);
|
|
1714
1653
|
}
|
|
1654
|
+
const retired = isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId);
|
|
1655
|
+
if (state === "pending" && retired) {
|
|
1656
|
+
throw new Error(`Retired scope workflow output is never retried: ${id}`);
|
|
1657
|
+
}
|
|
1715
1658
|
const retry = state === "pending" && (output.state === "uncertain" || output.state === "failed");
|
|
1716
|
-
|
|
1659
|
+
// A definitively rejected retired send releases its hold, never its retry fence.
|
|
1660
|
+
const reconcile = output.state === "uncertain" && (state === "sent"
|
|
1661
|
+
|| (state === "failed" && retired && remoteId === undefined && output.remoteId === null));
|
|
1717
1662
|
if (output.state !== "sending" && !retry && !reconcile) {
|
|
1718
1663
|
throw new Error(`Invalid output transition ${output.state} -> ${state}: ${id}`);
|
|
1719
1664
|
}
|
|
1720
1665
|
this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
|
|
1721
1666
|
.run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
|
|
1667
|
+
if (state === "sent" && remoteId && output.route.platform === "discord") {
|
|
1668
|
+
this.queueDiscordHeadFollowupLinks(output, remoteId);
|
|
1669
|
+
}
|
|
1722
1670
|
const stream = this.getMeta(`status-stream:${id}`);
|
|
1723
1671
|
if (stream) {
|
|
1724
1672
|
const anchorKey = `status-anchor:${stream}`;
|
|
@@ -1740,6 +1688,35 @@ export class Store implements StorePort {
|
|
|
1740
1688
|
}).immediate();
|
|
1741
1689
|
}
|
|
1742
1690
|
|
|
1691
|
+
private queueDiscordHeadFollowupLinks(output: OutputRecord, remoteId: string): void {
|
|
1692
|
+
const key = `discord-head-followups:${output.id}`;
|
|
1693
|
+
const saved = this.getMeta(key);
|
|
1694
|
+
if (!saved) return;
|
|
1695
|
+
const owner = this.input(output.sourceId);
|
|
1696
|
+
const target = output.replyTo;
|
|
1697
|
+
const guild = output.route.guildId;
|
|
1698
|
+
const channel = output.route.threadId ?? output.route.channelId;
|
|
1699
|
+
const snowflake = /^\d{1,20}$/u;
|
|
1700
|
+
if (owner?.target !== "main" || owner.state !== "done"
|
|
1701
|
+
|| (owner.messageId === null ? !owner.interactionId || target !== undefined : target?.messageId !== owner.messageId)
|
|
1702
|
+
|| !snowflake.test(channel) || guild !== null && !snowflake.test(guild) || !snowflake.test(remoteId)) return;
|
|
1703
|
+
const url = `https://discord.com/channels/${guild ?? "@me"}/${channel}/${remoteId}`;
|
|
1704
|
+
const physical = new Set(owner.messageId === null ? [] : [owner.messageId]);
|
|
1705
|
+
for (const id of JSON.parse(saved) as string[]) {
|
|
1706
|
+
const source = this.input(id);
|
|
1707
|
+
if (source?.target !== "main" || source.state !== "done" || source.generation !== owner.generation
|
|
1708
|
+
|| !source.messageId || !snowflake.test(source.messageId) || physical.has(source.messageId)
|
|
1709
|
+
|| routeKey(source.route) !== routeKey(output.route) || this.ownerSource(id)?.id !== id
|
|
1710
|
+
|| this.getMeta(`steering-owner:${id}`) !== owner.id) continue;
|
|
1711
|
+
physical.add(source.messageId);
|
|
1712
|
+
this.queueOutput({ id: `${output.id}:joined:${id}`, sourceId: id, route: source.route,
|
|
1713
|
+
replyTo: { route: physicalRoute(source.route), messageId: source.messageId, requireExisting: true },
|
|
1714
|
+
text: `이 후속 메시지와 함께 처리한 [HEAD 통합 답변](<${url}>)` });
|
|
1715
|
+
}
|
|
1716
|
+
// Commit the canonical send receipt and its dependent notices together.
|
|
1717
|
+
this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1743
1720
|
createLane(lane: Lane & { model: LaneModel; modelReason: string }, sourceId: string): Lane {
|
|
1744
1721
|
if (!isLaneModel(lane.model) || typeof lane.modelReason !== "string" || !lane.modelReason.trim()
|
|
1745
1722
|
|| (lane.modelPreset !== null && (typeof lane.modelPreset !== "string" || !lane.modelPreset.trim() || !lane.modelPresetSnapshot))
|
|
@@ -1804,10 +1781,6 @@ export class Store implements StorePort {
|
|
|
1804
1781
|
return this.db.transaction(() => {
|
|
1805
1782
|
const lane = this.lane(id);
|
|
1806
1783
|
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
|
-
}
|
|
1811
1784
|
// Explicitly copy the contract whitelist; runtime callers cannot change identity.
|
|
1812
1785
|
for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result"] as const) {
|
|
1813
1786
|
if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
|
|
@@ -1961,25 +1934,17 @@ export class Store implements StorePort {
|
|
|
1961
1934
|
}
|
|
1962
1935
|
if (ownerInputId) {
|
|
1963
1936
|
const owner = this.input(ownerInputId);
|
|
1964
|
-
if (owner?.target !== approval.target || owner.generation !== approval.generation)
|
|
1937
|
+
if (owner?.target !== approval.target || owner.generation !== approval.generation || isRetiredScopeInput(owner.id))
|
|
1965
1938
|
throw new Error(`Approval does not match its topic source: ${approval.id}`);
|
|
1966
1939
|
const reportSource = this.reportApprovalSource(owner.id);
|
|
1967
1940
|
if (reportSource) {
|
|
1968
1941
|
if (routeKey(reportSource.route) !== routeKey(approval.route))
|
|
1969
1942
|
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
|
-
}
|
|
1974
1943
|
} else {
|
|
1975
1944
|
const topic = this.topicDelivery(owner.id);
|
|
1976
1945
|
if (!topic || routeKey(topic.route) !== routeKey(approval.route))
|
|
1977
1946
|
throw new Error(`Approval does not match its topic source: ${approval.id}`);
|
|
1978
1947
|
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
|
-
}
|
|
1983
1948
|
}
|
|
1984
1949
|
} else this.checkTarget(approval.target, approval.route);
|
|
1985
1950
|
const lane = this.lane(approval.target);
|
|
@@ -2001,31 +1966,108 @@ export class Store implements StorePort {
|
|
|
2001
1966
|
AND (?1 IS NULL OR target = ?1) ORDER BY sequence`).all(target ?? null) as ApprovalRow[]).map(toApproval);
|
|
2002
1967
|
}
|
|
2003
1968
|
|
|
1969
|
+
isNativeApprovalHeld(owner: {
|
|
1970
|
+
readonly target: string; readonly generation: number; readonly sessionId: string;
|
|
1971
|
+
readonly input?: { readonly id: string; readonly sessionFile: string };
|
|
1972
|
+
}, approvalId: string): boolean {
|
|
1973
|
+
if (this.getMeta(`native-approval-held:${approvalId}`) !== null
|
|
1974
|
+
|| this.getMeta(`scope-cancel:${owner.sessionId}:${approvalId}`) !== null
|
|
1975
|
+
|| this.getMeta(`retired-scope-dialog:${owner.sessionId}:${approvalId}`) !== null) return true;
|
|
1976
|
+
// A stock UI ID does not identify the original prompt, and resolving the
|
|
1977
|
+
// ledger receipt does not close native UI. Only the current later native
|
|
1978
|
+
// admission can own a new dialog, not a completed turn or a stop receipt.
|
|
1979
|
+
return this.db.query(`SELECT 1 FROM inputs AS retired
|
|
1980
|
+
LEFT JOIN metadata AS previous ON previous.key = ?5 || retired.id
|
|
1981
|
+
LEFT JOIN metadata AS head ON head.key = 'retired-scope-head-session:' || retired.generation AND retired.target = 'main'
|
|
1982
|
+
WHERE retired.target = ?1 AND retired.generation = ?2 AND retired.request_id IS NOT NULL
|
|
1983
|
+
AND retired.state IN ('uncertain','cancelled') AND ${retiredScopeId("retired.id")}
|
|
1984
|
+
AND COALESCE(CASE WHEN json_valid(previous.value) THEN json_extract(previous.value, '$.sessionId') END,
|
|
1985
|
+
head.value, ?4) = ?4
|
|
1986
|
+
AND NOT EXISTS (SELECT 1 FROM approvals WHERE id = ?3)
|
|
1987
|
+
AND NOT EXISTS (
|
|
1988
|
+
SELECT 1 FROM inputs AS newer
|
|
1989
|
+
JOIN metadata AS native ON native.key IN (?5 || newer.id, 'native-goal-resume-owner:' || newer.id)
|
|
1990
|
+
AND json_valid(native.value)
|
|
1991
|
+
WHERE newer.target = retired.target AND newer.generation = retired.generation
|
|
1992
|
+
AND newer.id = ?6 AND newer.sequence > retired.sequence AND newer.state = 'submitted'
|
|
1993
|
+
AND NOT ${retiredScopeId("newer.id")}
|
|
1994
|
+
AND json_extract(native.value, '$.requestId') = newer.request_id
|
|
1995
|
+
AND json_extract(native.value, '$.generation') = newer.generation
|
|
1996
|
+
AND json_extract(native.value, '$.sessionId') = ?4
|
|
1997
|
+
AND json_extract(native.value, '$.sessionFile') = ?7
|
|
1998
|
+
AND json_type(native.value, '$.cursor') IN ('text','null')
|
|
1999
|
+
) LIMIT 1`).get(owner.target, owner.generation, approvalId, owner.sessionId,
|
|
2000
|
+
owner.target === "main" ? "head-native-owner:" : "lane-observation-owner:",
|
|
2001
|
+
owner.input?.id ?? null, owner.input?.sessionFile ?? null) !== null;
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
retiredApprovalDismissals(): string[] {
|
|
2005
|
+
return this.db.query<{ id: string }, []>(`SELECT a.id FROM approvals AS a
|
|
2006
|
+
JOIN metadata AS dismissal ON dismissal.key = 'retired-approval-dismissal:' || a.id
|
|
2007
|
+
WHERE dismissal.value IN ('pending','attempted') ORDER BY a.sequence`).all().map(row => row.id);
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
claimRetiredApprovalDismissal(id: string): Approval | null {
|
|
2011
|
+
return this.db.transaction(() => {
|
|
2012
|
+
const dismissal = `retired-approval-dismissal:${id}`;
|
|
2013
|
+
const phase = this.getMeta(dismissal);
|
|
2014
|
+
const approval = this.approval(id);
|
|
2015
|
+
if (!approval || (phase !== "pending" && phase !== "attempted")) return null;
|
|
2016
|
+
// A previous controller may have lost its local receipt after the
|
|
2017
|
+
// Gateway recorded the remote one. Never use another card's effect or
|
|
2018
|
+
// infer a remote message from an attempted send.
|
|
2019
|
+
let remoteId = approval.remoteId;
|
|
2020
|
+
let uncertainDismissal = false;
|
|
2021
|
+
const dismissals = new Set<string>();
|
|
2022
|
+
if (this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get()) {
|
|
2023
|
+
const effects = this.db.query<{ operation: string; arguments: string; result: string | null }, [string]>(`
|
|
2024
|
+
SELECT operation, arguments, result FROM gateway_effects
|
|
2025
|
+
WHERE operation IN ('showApproval','dismissApproval') AND json_valid(arguments)
|
|
2026
|
+
AND json_extract(arguments, '$[0].id') = ?`).all(id);
|
|
2027
|
+
const messages = new Set(remoteId ? [remoteId] : []);
|
|
2028
|
+
for (const effect of effects) {
|
|
2029
|
+
const [card] = JSON.parse(effect.arguments) as Approval[];
|
|
2030
|
+
if (!card || !isDeepStrictEqual(approvalIdentity(card), approvalIdentity(approval))) continue;
|
|
2031
|
+
const result = effect.result === null ? null : JSON.parse(effect.result) as
|
|
2032
|
+
{ ok?: boolean; certainty?: string; value?: unknown };
|
|
2033
|
+
if (effect.operation === "showApproval") {
|
|
2034
|
+
if (result?.ok === true && typeof result.value === "string" && result.value) messages.add(result.value);
|
|
2035
|
+
} else if (result?.ok === true && card.remoteId) {
|
|
2036
|
+
dismissals.add(card.remoteId);
|
|
2037
|
+
} else if (result?.certainty !== "rejected") {
|
|
2038
|
+
uncertainDismissal = true;
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
if (messages.size !== 1) return null;
|
|
2042
|
+
remoteId = messages.values().next().value ?? null;
|
|
2043
|
+
}
|
|
2044
|
+
if (!remoteId) return null;
|
|
2045
|
+
if (dismissals.has(remoteId)) {
|
|
2046
|
+
this.setMeta(dismissal, "complete");
|
|
2047
|
+
return null;
|
|
2048
|
+
}
|
|
2049
|
+
if (phase === "attempted" || uncertainDismissal || dismissals.size) return null;
|
|
2050
|
+
this.setApprovalMessage(id, remoteId);
|
|
2051
|
+
this.setMeta(dismissal, "attempted");
|
|
2052
|
+
return { ...approval, remoteId };
|
|
2053
|
+
}).immediate();
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
finishRetiredApprovalDismissal(id: string): void {
|
|
2057
|
+
this.db.query("UPDATE metadata SET value = 'complete' WHERE key = ? AND value = 'attempted'")
|
|
2058
|
+
.run(`retired-approval-dismissal:${id}`);
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2004
2061
|
resolveApproval(id: string, generation: number, state: "answered" | "cancelled", resolution?: ApprovalResolution): boolean {
|
|
2005
2062
|
return this.db.transaction(() => {
|
|
2006
2063
|
const approval = this.approval(id);
|
|
2007
2064
|
if (!approval || approval.state !== "pending" || approval.generation !== generation) return false;
|
|
2008
2065
|
const lane = this.lane(approval.target);
|
|
2009
|
-
if (state === "answered" &&
|
|
2010
|
-
|
|
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
|
-
}
|
|
2066
|
+
if (state === "answered" && (this.getMeta(`native-approval-held:${id}`) !== null
|
|
2067
|
+
|| lane && (lane.generation !== generation || lane.workState !== "open"))) return false;
|
|
2020
2068
|
resolveDecision(this, approval, state, resolution);
|
|
2021
|
-
|
|
2069
|
+
return this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
|
|
2022
2070
|
.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;
|
|
2029
2071
|
}).immediate();
|
|
2030
2072
|
}
|
|
2031
2073
|
|
|
@@ -2040,8 +2082,32 @@ export class Store implements StorePort {
|
|
|
2040
2082
|
}
|
|
2041
2083
|
|
|
2042
2084
|
recoverDeliveries(): void {
|
|
2043
|
-
this.db.
|
|
2044
|
-
.
|
|
2085
|
+
this.db.transaction(() => {
|
|
2086
|
+
this.db.query("UPDATE outputs SET state = 'uncertain', error = ? WHERE state = 'sending'")
|
|
2087
|
+
.run("Delivery interrupted before a durable receipt; reconcile before retrying.");
|
|
2088
|
+
if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get()) return;
|
|
2089
|
+
const retired = this.db.query<OutputRow, []>(`SELECT * FROM outputs WHERE state = 'uncertain' AND remote_id IS NULL
|
|
2090
|
+
AND (${retiredScopeId("id")} OR ${retiredScopeId("source_id")})`).all();
|
|
2091
|
+
const attempts = this.db.query<{ output: string; rejected: number }, [string]>(`SELECT
|
|
2092
|
+
json_extract(arguments, '$[0]') AS output,
|
|
2093
|
+
CASE WHEN state = 'complete' AND json_type(result, '$.ok') = 'false'
|
|
2094
|
+
AND json_extract(result, '$.certainty') = 'rejected' THEN 1 ELSE 0 END AS rejected
|
|
2095
|
+
FROM gateway_effects WHERE operation = 'send' AND json_extract(arguments, '$[0].id') = ? LIMIT 2`);
|
|
2096
|
+
for (const row of retired) {
|
|
2097
|
+
const recorded = attempts.all(row.id);
|
|
2098
|
+
const receipt = recorded.length === 1 ? recorded[0] : undefined;
|
|
2099
|
+
if (!receipt?.rejected) continue;
|
|
2100
|
+
const saved: unknown = JSON.parse(receipt.output);
|
|
2101
|
+
if (!saved || typeof saved !== "object" || !("error" in saved)) continue;
|
|
2102
|
+
const { error: _attemptError, ...attempt } = saved;
|
|
2103
|
+
const { error: _storedError, ...output } = toOutput(row);
|
|
2104
|
+
// Legacy sends used random Gateway effect IDs. Reconcile only one
|
|
2105
|
+
// terminal rejection with the same immutable send arguments.
|
|
2106
|
+
if (isDeepStrictEqual(attempt, { ...output, state: "sending" })) {
|
|
2107
|
+
this.finishOutput(row.id, "failed", undefined, "Gateway recorded definitive non-delivery");
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
}).immediate();
|
|
2045
2111
|
}
|
|
2046
2112
|
|
|
2047
2113
|
getMeta(key: string): string | null {
|