omp-superagent 0.1.9 → 0.1.10

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/src/store.ts CHANGED
@@ -24,24 +24,29 @@ 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
- DEFERRED_ROUTING_META, HEAD_MODEL_CONTROL, laneFallbackKey, laneModelPickerRestoreKey, physicalRoute, physicalRouteKey, resolvePickerOption, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
27
+ DEFERRED_ROUTING_META, 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,
29
+ type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope, type ScopeReview, type ScopeReviewNativeProof,
30
30
  } from "./contracts.ts";
31
31
  import type { ApprovalResolution } from "./contracts";
32
32
  import { captureDecision, resolveDecision } from "./decisions";
33
33
  import { isLaneModel, laneModelArgument, sameLaneModel } from "./lane-models";
34
34
  import { laneData, readLaneRows, toLane, type LaneRow } from "./lane-rows";
35
+ import { compareMessageIds } from "./message-order";
35
36
  import { storedWorkflowName, workflowChoice } from "./workflow";
36
- import { laneWaitKey, type LaneReport } from "./lane-report";
37
+ import { laneWaitKey, scopeReviewApproval, type LaneReport } from "./lane-report";
37
38
  import { laneWatchReplySource } from "./lane-watch";
38
- import { isResultAttachmentSnapshot } from "./result-attachment";
39
+ import { isOriginalAttachmentMessage, isResultAttachmentSnapshot } from "./result-attachment";
39
40
  import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "./topic-request";
40
41
  import type { CronUpdate } from "./cron-jobs";
41
42
  import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "./pr-intake-work";
42
43
  import { isPrReviewLane, type ReviewRound } from "./pr-intake-review";
43
44
 
44
45
  const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
46
+ const SCOPE_CORRECTION_PREFIX = `handoff:${SCOPE_REVIEW_PREFIX}`;
47
+ 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.";
48
+ const SCOPE_CORRECTION_NOT_CURRENT = "The scope correction is no longer current. It was not repeated; the existing lane scope is unchanged.";
49
+ const SCOPE_CORRECTION_NO_ANSWER = "The corrective request settled, but the lane returned no final answer.";
45
50
 
46
51
  const SCHEMA = `
47
52
  CREATE TABLE IF NOT EXISTS lanes (
@@ -84,6 +89,17 @@ const SCHEMA = `
84
89
  remote_id TEXT, UNIQUE(target, generation, request_id)
85
90
  );
86
91
  CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
92
+ CREATE TABLE IF NOT EXISTS scope_reviews (
93
+ id TEXT PRIMARY KEY, handoff_id TEXT NOT NULL UNIQUE REFERENCES inputs(id),
94
+ source_id TEXT NOT NULL REFERENCES inputs(id), lane_id TEXT NOT NULL REFERENCES lanes(id),
95
+ generation INTEGER NOT NULL, session_id TEXT NOT NULL, request_id TEXT NOT NULL,
96
+ tool_call_id TEXT, approval_id TEXT REFERENCES approvals(id),
97
+ operator_revision TEXT NOT NULL, lane_revision TEXT NOT NULL,
98
+ state TEXT NOT NULL CHECK(state IN ('candidate','review','granted','closed')),
99
+ correction_id TEXT NOT NULL UNIQUE, correction_requested INTEGER NOT NULL DEFAULT 0
100
+ );
101
+ CREATE INDEX IF NOT EXISTS pending_scope_reviews ON scope_reviews(lane_id)
102
+ WHERE state IN ('review','granted');
87
103
  `;
88
104
 
89
105
  const ADMITTED_MESSAGE_SCOPE = `FROM inputs
@@ -118,6 +134,26 @@ interface OutputRow {
118
134
  error: string | null;
119
135
  }
120
136
  interface ApprovalRow { data: string; state: Approval["state"]; remote_id: string | null }
137
+ interface ScopeReviewRow {
138
+ readonly id: string;
139
+ readonly handoff_id: string;
140
+ readonly source_id: string;
141
+ readonly lane_id: string;
142
+ readonly generation: number;
143
+ readonly session_id: string;
144
+ readonly request_id: string;
145
+ readonly tool_call_id: string | null;
146
+ readonly approval_id: string | null;
147
+ readonly operator_revision: string;
148
+ readonly lane_revision: string;
149
+ readonly state: "candidate" | "review" | "granted" | "closed";
150
+ readonly correction_id: string;
151
+ readonly correction_requested: 0 | 1;
152
+ }
153
+
154
+ class ScopeReviewError extends Error {
155
+ override readonly name = "ScopeReviewError";
156
+ }
121
157
 
122
158
  const toInput = (row: InputRow): InputRecord => {
123
159
  const { workflow, ...input } = JSON.parse(row.data) as Inbound & { workflow?: Omit<WorkflowActivation, "name"> & { name: string } };
@@ -144,13 +180,14 @@ const inboundData = (input: Inbound): Inbound => ({
144
180
  ...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }),
145
181
  ...(input.pickerSelection === undefined ? {} : { pickerSelection: input.pickerSelection }),
146
182
  ...(input.reply === undefined ? {} : { reply: input.reply }),
183
+ ...(input.unresolvedReply === undefined ? {} : { unresolvedReply: input.unresolvedReply }),
147
184
  ...(input.discordContext === undefined ? {} : { discordContext: input.discordContext }),
148
185
  receivedAt: input.receivedAt, attachments: input.attachments,
149
186
  });
150
187
  function inboundIdentity(input: Inbound) {
151
188
  // Derived routing text and independently edited references do not change the
152
189
  // event identity. Keep the first snapshot, including on pre-upgrade replay.
153
- const { reply: _reply, discordContext: _context, routingText: _routingText, ...data } = inboundData(input);
190
+ const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText, ...data } = inboundData(input);
154
191
  return {
155
192
  ...data,
156
193
  // Slack supplies no command timestamp. A transport redelivery has a fresh
@@ -224,6 +261,9 @@ export class Store implements StorePort {
224
261
  db.run(SCHEMA);
225
262
  const laneColumns = db.query<{ name: string }, []>("PRAGMA table_info(lanes)").all();
226
263
  if (!laneColumns.some(column => column.name === "remote")) db.run("ALTER TABLE lanes ADD COLUMN remote TEXT");
264
+ const reviewColumns = db.query<{ name: string }, []>("PRAGMA table_info(scope_reviews)").all();
265
+ if (!reviewColumns.some(column => column.name === "tool_call_id")) db.run("ALTER TABLE scope_reviews ADD COLUMN tool_call_id TEXT");
266
+ if (!reviewColumns.some(column => column.name === "approval_id")) db.run("ALTER TABLE scope_reviews ADD COLUMN approval_id TEXT REFERENCES approvals(id)");
227
267
  const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
228
268
  if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
229
269
  if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
@@ -359,11 +399,188 @@ export class Store implements StorePort {
359
399
  return { lane, failed, original };
360
400
  }
361
401
 
402
+ recordScopeReview(inputId: string, generation: number, sessionId: string, sourceId: string, proof: ScopeReviewNativeProof): boolean {
403
+ return this.db.transaction(() => {
404
+ const handoff = this.input(inputId);
405
+ if (handoff?.state !== "submitted" || !handoff.target || handoff.target === "main" || !handoff.requestId
406
+ || !proof.toolCallId) return false;
407
+ const id = `${SCOPE_REVIEW_PREFIX}${inputId}`;
408
+ const row: ScopeReviewRow = {
409
+ id, handoff_id: inputId, lane_id: handoff.target, source_id: sourceId, generation, session_id: sessionId,
410
+ request_id: handoff.requestId, tool_call_id: proof.toolCallId, approval_id: proof.approvalId ?? null,
411
+ operator_revision: this.laneOperatorRevision(handoff.target),
412
+ lane_revision: this.scopeLaneRevision(handoff.target), state: "candidate",
413
+ correction_id: `handoff:${id}:${handoff.target}`, correction_requested: 0,
414
+ };
415
+ if (!this.scopeReviewBinding(row)) return false;
416
+ return this.db.query(`INSERT OR IGNORE INTO scope_reviews
417
+ (id, handoff_id, source_id, lane_id, generation, session_id, request_id, tool_call_id, approval_id,
418
+ operator_revision, lane_revision, state, correction_id)
419
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'candidate', ?)`)
420
+ .run(id, inputId, sourceId, row.lane_id, generation, sessionId, row.request_id,
421
+ row.tool_call_id, row.approval_id, row.operator_revision, row.lane_revision, row.correction_id).changes === 1;
422
+ }).immediate();
423
+ }
424
+
425
+ scopeReview(reviewId: string): ScopeReview | null {
426
+ const row = this.db.query<ScopeReviewRow, [string]>("SELECT * FROM scope_reviews WHERE id = ?").get(reviewId);
427
+ if (!row || (row.state !== "review" && row.state !== "granted")) return null;
428
+ const review = this.input(reviewId);
429
+ if (review?.target !== "main" || this.getMeta(`activity-source:${review.id}`) !== row.source_id
430
+ || this.getMeta(`user-source:${review.id}`) !== null || review.workflow || review.messageId !== null
431
+ || review.attachments.length || review.reply || review.discordContext || review.pickerSelection
432
+ || review.interactionId !== undefined || review.invocationId !== undefined) return null;
433
+ if (row.state === "review") {
434
+ if (review.state !== "pending" && (review.state !== "submitted" || !review.requestId || !this.soloScopeAdmission(review.id)
435
+ || review.generation !== Number(this.getMeta("main:generation") ?? "0"))) return null;
436
+ } else if (review.state !== "done" || !review.requestId) return null;
437
+ const scope = this.scopeReviewBinding(row);
438
+ if (!scope || routeKey(review.route) !== routeKey(scope.original.route)) return null;
439
+ if (row.state === "granted" && !this.scopeCorrectionInput(row, scope)) return null;
440
+ return scope;
441
+ }
442
+
443
+ requestScopeCorrection(reviewId: string): string {
444
+ return this.db.transaction(() => {
445
+ const scope = this.scopeReview(reviewId);
446
+ if (!scope || this.input(reviewId)?.state !== "submitted" || this.getMeta("head:restart-fence"))
447
+ throw new ScopeReviewError("Scope correction requires the current submitted HEAD review and exact owner request");
448
+ const row = this.db.query<Pick<ScopeReviewRow, "correction_id">, [string]>(
449
+ "UPDATE scope_reviews SET correction_requested = 1 WHERE id = ? AND state = 'review' RETURNING correction_id",
450
+ ).get(reviewId);
451
+ if (!row) throw new ScopeReviewError("Scope review no longer accepts corrective intent");
452
+ return row.correction_id;
453
+ }).immediate();
454
+ }
455
+
456
+ private scopeReviewBinding(row: ScopeReviewRow): ScopeReview | null {
457
+ const handoff = this.input(row.handoff_id);
458
+ const original = this.input(row.source_id);
459
+ const lane = this.lane(row.lane_id);
460
+ if (!handoff || !original || !lane || lane.workState !== "open" || (!lane.route.threadId && !lane.route.topicId)
461
+ || !row.session_id || lane.sessionId !== row.session_id || lane.generation !== row.generation
462
+ || row.operator_revision !== this.laneOperatorRevision(lane.id) || row.lane_revision !== this.scopeLaneRevision(lane.id)
463
+ || this.getMeta("head:restart-fence") || isPrReviewLane(this, lane.id) || this.getMeta(`lane-quota-hold:${lane.id}`)
464
+ || original.state !== "done" || original.target !== null || original.workflow || original.unresolvedReply || !original.text.trim()
465
+ || original.text.trimStart().startsWith("/")
466
+ || original.discordOriginalText !== undefined && original.discordOriginalText.trim() !== original.text.trim()
467
+ || original.interactionId !== undefined || original.invocationId !== undefined || original.pickerSelection
468
+ || !isOriginalAttachmentMessage(original) || this.getMeta(`user-source:${original.id}`) !== "true"
469
+ || this.getMeta(`topic-owner:${original.id}`) !== lane.id
470
+ || this.getMeta(`topic-creator:${original.id}`) !== null || this.getMeta(`topic-revision:${original.id}`) !== null
471
+ || this.getMeta(`handoff-source:${original.id}`) !== null || this.getMeta(`activity-source:${original.id}`) !== null
472
+ || routeKey(original.route) !== routeKey(lane.route) || routeKey(handoff.route) !== routeKey(lane.route)
473
+ || this.laneForRoute(original.route)?.id !== lane.id
474
+ || handoff.id !== `handoff:${original.id}:${lane.id}` || handoff.target !== lane.id || handoff.workflow
475
+ || this.getMeta(`handoff-source:${handoff.id}`) !== original.id
476
+ || handoff.state !== (row.state === "candidate" ? "submitted" : "done")
477
+ || handoff.requestId !== row.request_id || handoff.generation !== row.generation || !this.soloScopeAdmission(handoff.id)) return null;
478
+ if (original.messageId === null || this.firstAdmittedMessage(original.route, original.messageId)?.id !== original.id) return null;
479
+ const native = this.getMeta(`lane-observation-owner:${handoff.id}`);
480
+ if (!native || !this.db.query(`SELECT 1 WHERE json_valid(?1)
481
+ AND json_extract(?1, '$.requestId') = ?2 AND json_extract(?1, '$.sessionId') = ?3
482
+ AND json_extract(?1, '$.generation') = ?4 AND json_extract(?1, '$.sessionFile') = ?5`)
483
+ .get(native, row.request_id, row.session_id, row.generation, lane.sessionFile)) return null;
484
+ const latest = this.latestLaneRun(lane.id)?.id;
485
+ if (latest !== handoff.id && (row.state !== "granted" || latest !== row.correction_id)
486
+ || this.inputs(lane.id).some(input => input.state !== "pending" && input.id !== handoff.id && input.id !== row.correction_id)
487
+ || this.scopeOwnerSuperseded(original, lane.id)) return null;
488
+ // The exception is only the exact approved call that produced this
489
+ // review receipt. All other native cards remain outside review authority.
490
+ if (row.approval_id !== null) {
491
+ const approval = this.approval(row.approval_id);
492
+ if (!row.tool_call_id || approval?.state !== "answered" || approval.target !== lane.id || approval.generation !== row.generation
493
+ || routeKey(approval.route) !== routeKey(original.route)
494
+ || this.getMeta(`topic-approval:${approval.id}`) !== original.id
495
+ || this.getMeta(`scope-review-approved-input:${approval.id}`) !== handoff.id) return null;
496
+ }
497
+ if (this.db.query(`SELECT 1 FROM approvals
498
+ JOIN metadata AS topic ON topic.key = 'topic-approval:' || approvals.id
499
+ WHERE topic.value IN (?1, ?2) AND approvals.id IS NOT ?3 AND NOT EXISTS (
500
+ SELECT 1 FROM metadata WHERE key = 'scope-correction-approval-input:' || approvals.id
501
+ ) LIMIT 1`).get(original.id, handoff.id, row.approval_id)) return null;
502
+ if (this.inputEffects(original, [original.id, handoff.id], () => false)
503
+ .some(effect => effect.state === "uncertain" || effect.state === "sending")) return null;
504
+ return { lane, original, handoff };
505
+ }
506
+
507
+ private soloScopeAdmission(id: string): boolean {
508
+ return this.getMeta(`steering-owner:${id}`) === id && !this.db.query(`SELECT 1 FROM inputs
509
+ JOIN metadata ON metadata.key = 'steering-owner:' || inputs.id
510
+ WHERE inputs.target = (SELECT target FROM inputs WHERE id = ?1)
511
+ AND inputs.generation = (SELECT generation FROM inputs WHERE id = ?1)
512
+ AND inputs.request_id IS NOT NULL AND inputs.id <> ?1 AND metadata.value = ?1 LIMIT 1`).get(id);
513
+ }
514
+
515
+ private scopeOwnerSuperseded(original: InputRecord, laneId: string): boolean {
516
+ const { platform, accountId, authorityId, guildId, channelId, threadId, topicId } = original.route;
517
+ // Retain later owner admissions as a permanent fence, even if they settle
518
+ // without dispatch. Edits and priority controls supersede too.
519
+ if (this.db.query(`SELECT 1 FROM inputs AS newer
520
+ JOIN metadata AS owner ON owner.key = 'user-source:' || newer.id AND owner.value = 'true'
521
+ LEFT JOIN metadata AS topic ON topic.key = 'topic-owner:' || newer.id
522
+ WHERE newer.sequence > (SELECT sequence FROM inputs WHERE id = ?1)
523
+ AND (topic.value = ?2 OR (
524
+ json_extract(newer.data, '$.route.platform') = ?3 AND json_extract(newer.data, '$.route.accountId') = ?4
525
+ AND json_extract(newer.data, '$.route.authorityId') = ?5 AND json_extract(newer.data, '$.route.guildId') IS ?6
526
+ AND json_extract(newer.data, '$.route.channelId') = ?7 AND json_extract(newer.data, '$.route.threadId') IS ?8
527
+ AND json_extract(newer.data, '$.route.topicId') IS ?9
528
+ )) LIMIT 1`).get(original.id, laneId, platform, accountId, authorityId, guildId, channelId, threadId, topicId ?? null)) return true;
529
+ const originalMessageId = original.messageId;
530
+ if (originalMessageId !== null) {
531
+ // Catchup can admit a physically newer original first. Use the exact
532
+ // topic and platform message clock, not an edit ID or arrival time.
533
+ const earlierAdmissions = this.db.query<InputRow, [string, string, string, string, string | null, string | null, string, string | null]>(
534
+ `SELECT inputs.* ${ADMITTED_MESSAGE_SCOPE}
535
+ AND inputs.sequence < (SELECT sequence FROM inputs WHERE id = ?)
536
+ AND json_extract(inputs.data, '$.route.topicId') IS ?`,
537
+ ).iterate(platform, channelId, accountId, authorityId, guildId, threadId, original.id, topicId ?? null);
538
+ for (const row of earlierAdmissions) {
539
+ const source = toInput(row);
540
+ if (source.messageId !== null && compareMessageIds(platform, source.messageId, originalMessageId) === 1
541
+ && isOriginalAttachmentMessage(source)) return true;
542
+ }
543
+ }
544
+ const deferred: readonly Inbound[] = JSON.parse(this.getMeta(DEFERRED_ROUTING_META) ?? "[]");
545
+ if (deferred.some(input => input.id !== original.id && physicalRouteKey(input.route) === physicalRouteKey(original.route))) return true;
546
+ // Gateway can durably admit an input before head routing classifies it.
547
+ if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get()) return false;
548
+ return this.db.query(`SELECT 1 FROM gateway_events INDEXED BY gateway_events_pending
549
+ WHERE delivered_at IS NULL AND json_extract(data, '$.kind') = 'message'
550
+ AND json_extract(data, '$.input.id') <> ?1
551
+ AND NOT EXISTS (SELECT 1 FROM inputs WHERE id = json_extract(gateway_events.data, '$.input.id'))
552
+ AND json_extract(data, '$.input.route.platform') = ?2 AND json_extract(data, '$.input.route.accountId') = ?3
553
+ AND json_extract(data, '$.input.route.authorityId') = ?4 AND json_extract(data, '$.input.route.guildId') IS ?5
554
+ AND json_extract(data, '$.input.route.channelId') = ?6 AND json_extract(data, '$.input.route.threadId') IS ?7
555
+ LIMIT 1`).get(original.id, platform, accountId, authorityId, guildId, channelId, threadId) !== null;
556
+ }
557
+
558
+ private scopeCorrectionInput(row: ScopeReviewRow, scope: ScopeReview): InputRecord | null {
559
+ const input = this.input(row.correction_id);
560
+ if (!input || input.target !== scope.lane.id || input.state !== "pending" && (input.state !== "submitted"
561
+ || !input.requestId || input.generation !== row.generation || !this.soloScopeAdmission(input.id))
562
+ || routeKey(input.route) !== routeKey(scope.lane.route) || input.text !== scope.original.text.trim()
563
+ || input.workflow || input.messageId !== null || input.attachments.length || input.reply || input.discordContext
564
+ || input.interactionId !== undefined || input.invocationId !== undefined || input.pickerSelection
565
+ || this.getMeta(`user-source:${input.id}`) !== null || this.getMeta(`topic-owner:${input.id}`) !== null
566
+ || this.getMeta(`handoff-source:${input.id}`) !== row.id
567
+ || this.getMeta(`report-approval-source:${row.id}`) !== scope.original.id) return null;
568
+ return input;
569
+ }
570
+
571
+ private scopeLaneRevision(id: string): string {
572
+ return this.getMeta(`scope-review-lane-revision:${id}`) ?? "0";
573
+ }
574
+
362
575
  reportApprovalSource(id: string): InputRecord | null {
363
576
  const input = this.input(id);
364
577
  if (!input) return null;
365
578
  const reportId = input.target === "main" ? id : this.getMeta(`handoff-source:${id}`);
366
579
  if (!reportId || this.input(reportId)?.target !== "main") return null;
580
+ if (reportId.startsWith(SCOPE_REVIEW_PREFIX)) {
581
+ const scope = this.scopeReview(reportId);
582
+ return scope && id === `handoff:${reportId}:${scope.lane.id}` && input.state === "submitted" ? scope.original : null;
583
+ }
367
584
  const sourceId = this.getMeta(`report-approval-source:${reportId}`);
368
585
  const original = sourceId === null ? null : this.ownerSource(id);
369
586
  return original?.id === sourceId ? original : null;
@@ -536,15 +753,24 @@ export class Store implements StorePort {
536
753
  }
537
754
 
538
755
  hasPendingLaneResult(target: string): boolean {
756
+ if (this.hasPendingScopeReview(target)) return true;
539
757
  return this.db.query(`SELECT 1 FROM inputs AS run
540
758
  LEFT JOIN inputs AS report ON report.id = 'report:' || run.id
541
759
  LEFT JOIN inputs AS recovered ON recovered.id = 'report:' || run.id || ':done'
542
- LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, run.id) || ':answer'
543
- LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, run.id) || ':answer:done'
544
- WHERE run.target = ? AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
760
+ LEFT JOIN inputs AS scope ON scope.id = ?2 || run.id
761
+ LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer'
762
+ LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer:done'
763
+ WHERE run.target = ?1 AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
545
764
  AND (COALESCE(recovered.state, report.state) IN ('pending','submitted','uncertain')
546
765
  OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain'))
547
- LIMIT 1`).get(target) !== null;
766
+ LIMIT 1`).get(target, SCOPE_REVIEW_PREFIX) !== null;
767
+ }
768
+
769
+ hasPendingScopeReview(target: string): boolean {
770
+ const rows = this.db.query<Pick<ScopeReviewRow, "id">, [string]>(
771
+ "SELECT id FROM scope_reviews WHERE lane_id = ? AND state IN ('review','granted')",
772
+ ).all(target);
773
+ return rows.some(row => this.scopeReview(row.id) !== null);
548
774
  }
549
775
 
550
776
  hasPendingLanePlacement(target: string): boolean {
@@ -557,7 +783,8 @@ export class Store implements StorePort {
557
783
  hasHeadRecoveryInput(): boolean {
558
784
  return this.db.query(`SELECT 1 FROM inputs
559
785
  JOIN metadata ON metadata.key = 'head-native-owner:' || inputs.id AND metadata.value <> ''
560
- WHERE inputs.target = 'main' AND inputs.state = 'uncertain' LIMIT 1`).get() !== null;
786
+ WHERE inputs.target = 'main' AND inputs.state = 'uncertain'
787
+ AND NOT EXISTS (SELECT 1 FROM scope_reviews WHERE scope_reviews.id = inputs.id) LIMIT 1`).get() !== null;
561
788
  }
562
789
 
563
790
  kickoffHold(target: string): KickoffHold | null {
@@ -744,6 +971,17 @@ export class Store implements StorePort {
744
971
  return this.db.transaction(() => {
745
972
  const input = this.input(id);
746
973
  if (!input || input.state !== "pending" || input.target === null) return false;
974
+ if (id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) {
975
+ const reviewId = input.target === "main" ? id : this.getMeta(`handoff-source:${id}`);
976
+ const scope = reviewId && this.scopeReview(reviewId);
977
+ if (!scope || this.getMeta(`steering-owner:${id}`) !== id || (input.target === "main"
978
+ ? id !== reviewId || generation !== Number(this.getMeta("main:generation") ?? "0")
979
+ : id !== `handoff:${reviewId}:${scope.lane.id}` || generation !== scope.lane.generation)
980
+ || this.getMeta("head:restart-fence")) {
981
+ this.settle(id, "cancelled");
982
+ return false;
983
+ }
984
+ }
747
985
  const progress = this.getMeta(`progress-source:${id}`);
748
986
  if (progress && !this.progressOpen(JSON.parse(progress))) {
749
987
  this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(id);
@@ -849,7 +1087,7 @@ export class Store implements StorePort {
849
1087
  }
850
1088
 
851
1089
  progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace = false): boolean {
852
- if (!text.trim()) return false;
1090
+ if (!text.trim() || id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) return false;
853
1091
  return this.db.transaction(() => {
854
1092
  const context = { inputId: id, generation, sessionId };
855
1093
  if (!this.progressOpen(context)) return false;
@@ -982,6 +1220,69 @@ export class Store implements StorePort {
982
1220
  }).immediate();
983
1221
  }
984
1222
 
1223
+ /** Called only inside settle: one transaction owns the state transition, output and next receipt. */
1224
+ private settleScopeReview(input: InputRecord, state: "done" | "uncertain" | "cancelled", settlement?: SettlementOutput): boolean {
1225
+ const id = input.id;
1226
+ const eligible = input.state === "submitted" && state === "done" && settlement?.scopeReviewEligible === true
1227
+ && settlement.laneFailure === undefined && !settlement.picker && !this.getMeta("head:restart-fence");
1228
+ const shut = this.db.query("UPDATE scope_reviews SET state = 'closed', correction_requested = 0 WHERE id = ?");
1229
+ if (id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) {
1230
+ const row = id.startsWith(SCOPE_REVIEW_PREFIX)
1231
+ ? this.db.query<ScopeReviewRow, [string]>("SELECT * FROM scope_reviews WHERE id = ?").get(id)
1232
+ : this.db.query<ScopeReviewRow, [string]>("SELECT * FROM scope_reviews WHERE correction_id = ?").get(id);
1233
+ if (!row) return true; // Reserved internal identities cannot use ordinary report routing.
1234
+ const scope = this.scopeReview(row.id);
1235
+ if (id === row.id && row.state === "review" && eligible && scope && row.correction_requested === 1
1236
+ && !this.input(row.correction_id)) {
1237
+ this.insertInput({
1238
+ id: row.correction_id, route: scope.lane.route, messageId: null, receivedAt: scope.original.receivedAt,
1239
+ text: scope.original.text.trim(), attachments: [],
1240
+ }, scope.lane.id, {
1241
+ [`handoff-source:${row.correction_id}`]: id,
1242
+ [`report-approval-source:${id}`]: scope.original.id,
1243
+ }, null);
1244
+ this.db.query("UPDATE scope_reviews SET state = 'granted', correction_requested = 0 WHERE id = ?").run(id);
1245
+ return true; // No HEAD final when the correction was actually admitted.
1246
+ }
1247
+ const correction = id === row.correction_id;
1248
+ const deliver = row.state === (correction ? "granted" : "review");
1249
+ shut.run(row.id);
1250
+ if (deliver && input.state !== "uncertain") {
1251
+ const original = this.input(row.source_id);
1252
+ if (!original || this.getMeta(`user-source:${original.id}`) !== "true" || routeKey(original.route) !== routeKey(input.route)) return true;
1253
+ const answer = settlement?.text.trim();
1254
+ const text = correction
1255
+ ? answer || (state === "done" ? SCOPE_CORRECTION_NO_ANSWER : SCOPE_CORRECTION_NOT_CURRENT)
1256
+ : eligible && scope && row.correction_requested === 0 && answer && answer.length <= 1200 ? answer : SCOPE_REVIEW_NOT_GRANTED;
1257
+ this.queueOutput({ id: settlement?.id ?? `${id}:answer`, text, sourceId: original.id, route: original.route });
1258
+ }
1259
+ return true;
1260
+ }
1261
+ const row = this.db.query<ScopeReviewRow, [string]>(
1262
+ "SELECT * FROM scope_reviews WHERE handoff_id = ? AND state = 'candidate'",
1263
+ ).get(id);
1264
+ if (!row) return false;
1265
+ const scope = eligible ? this.scopeReviewBinding(row) : null;
1266
+ if (!scope || this.input(row.id)) {
1267
+ shut.run(row.id);
1268
+ // Preserve ordinary answers and failure routing. A completed native
1269
+ // turn with no answer still owes a bounded result at its original source.
1270
+ if (input.state !== "submitted" || state !== "done" || !settlement || settlement.laneFailure !== undefined
1271
+ || settlement.picker || settlement.text.trim()) return false;
1272
+ const original = this.input(row.source_id);
1273
+ if (!original || this.getMeta(`user-source:${original.id}`) !== "true"
1274
+ || routeKey(original.route) !== routeKey(input.route)) return false;
1275
+ this.queueOutput({ id: settlement.id, text: SCOPE_REVIEW_NOT_GRANTED, sourceId: original.id, route: original.route });
1276
+ return true;
1277
+ }
1278
+ this.insertInput({
1279
+ id: row.id, route: scope.original.route, messageId: null, receivedAt: scope.original.receivedAt,
1280
+ text: "Internal review of the independently verified original owner request.", attachments: [],
1281
+ }, "main", { [`activity-source:${row.id}`]: scope.original.id }, null);
1282
+ this.db.query("UPDATE scope_reviews SET state = 'review' WHERE id = ?").run(row.id);
1283
+ return true;
1284
+ }
1285
+
985
1286
  settle(id: string, state: "done" | "uncertain" | "cancelled", settlement?: SettlementOutput, headModel?: HeadModelChange, editInPlace = false): boolean {
986
1287
  return this.db.transaction(() => {
987
1288
  const input = this.input(id);
@@ -999,6 +1300,14 @@ export class Store implements StorePort {
999
1300
  if (input.state === state && (state !== "uncertain" || !newQuota)) return false;
1000
1301
  const pending = this.getMeta(`progress-pending:${id}`);
1001
1302
  if (pending) this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(pending);
1303
+ if (this.settleScopeReview(input, state, settlement)) {
1304
+ if (newQuota && input.target && id.startsWith(SCOPE_CORRECTION_PREFIX)) {
1305
+ this.setMeta(quotaKey, "true");
1306
+ this.setMeta(`lane-quota-hold:${input.target}`, id);
1307
+ }
1308
+ this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
1309
+ return true;
1310
+ }
1002
1311
  const reportId = `report:${id}`;
1003
1312
  if (input.state === "uncertain" && (newQuota || state !== "uncertain")
1004
1313
  && this.getMeta(`lane-recovery-input:${reportId}`) === id
@@ -1125,6 +1434,10 @@ export class Store implements StorePort {
1125
1434
  const input = this.requireInput(inputId);
1126
1435
  const related = [inputId, ...this.inputs().filter(candidate =>
1127
1436
  this.getMeta(`handoff-source:${candidate.id}`) === inputId).map(candidate => candidate.id)];
1437
+ return this.inputEffects(input, related, id => this.approval(id)?.target === "main");
1438
+ }
1439
+
1440
+ private inputEffects(input: InputRecord, related: readonly string[], ownsApproval: (id: string) => boolean): HeadRecoveryEffect[] {
1128
1441
  const outputs = (this.db.query("SELECT id,source_id,state FROM outputs ORDER BY sequence").all() as
1129
1442
  Array<{ id: string; source_id: string; state: string }>).filter(row => related.includes(row.source_id));
1130
1443
  const effects: HeadRecoveryEffect[] = outputs.map(row => ({ id: row.id, kind: "output", state: row.state }));
@@ -1144,7 +1457,7 @@ export class Store implements StorePort {
1144
1457
  const relevant = related.includes(row.source ?? "") || outputs.some(output => output.id === row.target)
1145
1458
  || row.operation === "createThread" && input.messageId !== null && row.message === input.messageId
1146
1459
  || (row.operation === "showApproval" || row.operation === "dismissApproval")
1147
- && this.approval(row.target ?? "")?.target === "main";
1460
+ && row.target !== null && ownsApproval(row.target);
1148
1461
  if (relevant) effects.push({ id: row.id, kind: row.operation,
1149
1462
  state: row.state === "attempted" || row.certainty === "uncertain" || row.ok === null ? "uncertain"
1150
1463
  : row.ok === 0 ? "failed" : "sent" });
@@ -1158,6 +1471,7 @@ export class Store implements StorePort {
1158
1471
  const input = this.input(attempt.inputId);
1159
1472
  if (attempt.state !== "prepared" || this.getMeta("head:recovery-active")
1160
1473
  || this.getMeta(`head:recovery:${attempt.inputId}`) || input?.target !== "main" || input.state !== "uncertain"
1474
+ || input.id.startsWith(SCOPE_REVIEW_PREFIX)
1161
1475
  || input.requestId !== attempt.requestId || input.generation !== attempt.generation
1162
1476
  || this.getMeta("head:stop-boundary") !== attempt.stopBoundary) return false;
1163
1477
  this.setMeta(`head:recovery:${attempt.inputId}`, JSON.stringify(attempt));
@@ -1285,6 +1599,20 @@ export class Store implements StorePort {
1285
1599
  }).immediate();
1286
1600
  }
1287
1601
 
1602
+ recordRestartCheckpointFailure(expectedFence: string, stopBoundary: string | null, failedFence: string,
1603
+ output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">): boolean {
1604
+ return this.db.transaction(() => {
1605
+ // The Rust Gateway writes the stop boundary through its own connection.
1606
+ // Do not reserve the only result ID if that operator stop already won.
1607
+ if (this.getMeta("head:restart-fence") !== expectedFence
1608
+ || this.getMeta("gateway:operator-stop") !== stopBoundary) return false;
1609
+ this.setMeta(`head:restart:${output.sourceId}`, failedFence);
1610
+ this.setMeta("head:restart-fence", failedFence);
1611
+ if (!this.output(output.id)) this.queueOutput(output);
1612
+ return true;
1613
+ }).immediate();
1614
+ }
1615
+
1288
1616
  recordHeadHoldNotice(blockerId: string, output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
1289
1617
  return this.db.transaction(() => {
1290
1618
  const marker = `head:hold-notice:${blockerId}`;
@@ -1452,6 +1780,10 @@ export class Store implements StorePort {
1452
1780
  return this.db.transaction(() => {
1453
1781
  const lane = this.lane(id);
1454
1782
  if (!lane || lane.generation !== generation) return false;
1783
+ if ((patch.workState !== undefined && patch.workState !== lane.workState)
1784
+ || (patch.sessionId !== undefined && patch.sessionId !== lane.sessionId)) {
1785
+ this.setMeta(`scope-review-lane-revision:${id}`, String(BigInt(this.scopeLaneRevision(id)) + 1n));
1786
+ }
1455
1787
  // Explicitly copy the contract whitelist; runtime callers cannot change identity.
1456
1788
  for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result"] as const) {
1457
1789
  if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
@@ -1461,6 +1793,18 @@ export class Store implements StorePort {
1461
1793
  }).immediate();
1462
1794
  }
1463
1795
 
1796
+ retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath">): boolean {
1797
+ return this.db.transaction(() => {
1798
+ const lane = this.lane(expected.id);
1799
+ if (!lane || lane.remote || expected.pid === null || lane.generation !== expected.generation
1800
+ || lane.pid !== expected.pid || lane.sessionId !== expected.sessionId || lane.socketPath !== expected.socketPath) return false;
1801
+ lane.pid = null;
1802
+ if (lane.runtimeState !== "unloaded") lane.runtimeState = "interrupted";
1803
+ return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
1804
+ .run(laneData(lane), lane.id, lane.generation).changes === 1;
1805
+ }).immediate();
1806
+ }
1807
+
1464
1808
  private sentLaneModelPicker(source: InputRecord) {
1465
1809
  const selection = source.pickerSelection;
1466
1810
  if (source.route.platform !== "discord" || selection?.target !== "lane" || selection.confirmed !== undefined
@@ -1599,11 +1943,19 @@ export class Store implements StorePort {
1599
1943
  if (reportSource) {
1600
1944
  if (routeKey(reportSource.route) !== routeKey(approval.route))
1601
1945
  throw new Error(`Approval does not match its original report source: ${approval.id}`);
1946
+ if (owner.id.startsWith(SCOPE_CORRECTION_PREFIX)) {
1947
+ this.setMeta(`topic-approval:${approval.id}`, reportSource.id);
1948
+ this.setMeta(`scope-correction-approval-input:${approval.id}`, owner.id);
1949
+ }
1602
1950
  } else {
1603
1951
  const topic = this.topicDelivery(owner.id);
1604
1952
  if (!topic || routeKey(topic.route) !== routeKey(approval.route))
1605
1953
  throw new Error(`Approval does not match its topic source: ${approval.id}`);
1606
1954
  this.setMeta(`topic-approval:${approval.id}`, topic.source.id);
1955
+ if (owner.state === "submitted" && owner.requestId && owner.id === `handoff:${topic.source.id}:${approval.target}`
1956
+ && scopeReviewApproval(approval.request)) {
1957
+ this.setMeta(`scope-review-approval-input:${approval.id}`, owner.id);
1958
+ }
1607
1959
  }
1608
1960
  } else this.checkTarget(approval.target, approval.route);
1609
1961
  const lane = this.lane(approval.target);
@@ -1631,9 +1983,25 @@ export class Store implements StorePort {
1631
1983
  if (!approval || approval.state !== "pending" || approval.generation !== generation) return false;
1632
1984
  const lane = this.lane(approval.target);
1633
1985
  if (state === "answered" && lane && (lane.generation !== generation || lane.workState !== "open")) return false;
1986
+ const correction = this.getMeta(`scope-correction-approval-input:${approval.id}`);
1987
+ if (correction && state === "answered" && !this.reportApprovalSource(correction)) {
1988
+ const response = resolution?.response;
1989
+ const request = approval.request;
1990
+ const denied = isDeepStrictEqual(response, { cancelled: true })
1991
+ || request.method === "confirm" && isDeepStrictEqual(response, { confirmed: false })
1992
+ || request.method === "select" && Array.isArray(request.options) && request.options.includes("Deny")
1993
+ && isDeepStrictEqual(response, { value: "Deny" });
1994
+ if (!denied || resolution?.headSelection) return false;
1995
+ }
1634
1996
  resolveDecision(this, approval, state, resolution);
1635
- return this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
1997
+ const resolved = this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
1636
1998
  .run(state, id, generation).changes === 1;
1999
+ if (resolved && state === "answered" && resolution?.headSelection === undefined
2000
+ && resolution?.response && scopeReviewApproval(approval.request, resolution.response)) {
2001
+ const inputId = this.getMeta(`scope-review-approval-input:${id}`);
2002
+ if (inputId) this.setMeta(`scope-review-approved-input:${id}`, inputId);
2003
+ }
2004
+ return resolved;
1637
2005
  }).immediate();
1638
2006
  }
1639
2007