omp-superagent 0.1.13 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/DESIGN.md +8 -5
  2. package/THIRD_PARTY_NOTICES.md +6 -0
  3. package/assets/architecture-dark.svg +4 -4
  4. package/assets/architecture.ko-dark.svg +4 -4
  5. package/assets/architecture.ko.svg +4 -4
  6. package/assets/architecture.mmd +5 -5
  7. package/assets/architecture.svg +4 -4
  8. package/config.example.json +1 -0
  9. package/docs/OPERATIONS.en.md +80 -23
  10. package/docs/OPERATIONS.md +73 -18
  11. package/docs/design/execution.md +180 -43
  12. package/docs/design/messaging.md +62 -10
  13. package/docs/releases/0.1.15.md +13 -0
  14. package/docs/releases/0.1.16.md +9 -0
  15. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  16. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  17. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  18. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  19. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  20. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  21. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  22. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  23. package/package.json +6 -3
  24. package/scripts/prepare-worker-memory.ts +37 -0
  25. package/skills/head/SKILL.md +29 -47
  26. package/skills/head/references/routing.md +35 -16
  27. package/skills/head/references/supervision.md +10 -14
  28. package/skills/lane/SKILL.md +14 -16
  29. package/skills/lane/references/workflow.md +14 -27
  30. package/src/cli.ts +56 -56
  31. package/src/config/config.ts +14 -0
  32. package/src/contracts.ts +38 -30
  33. package/src/cron/cron-jobs.ts +4 -3
  34. package/src/cron/cron-pr-intake.ts +1 -2
  35. package/src/extension.ts +69 -24
  36. package/src/gateway/gateway-client.ts +24 -15
  37. package/src/group/group-runner.ts +3 -2
  38. package/src/group-runner-extension.ts +7 -3
  39. package/src/host-extension.ts +109 -2
  40. package/src/host-sdk-helper.ts +6 -1
  41. package/src/lane/decision-tool.ts +2 -3
  42. package/src/lane/lane-report.ts +8 -30
  43. package/src/lane/lane-rows.ts +1 -1
  44. package/src/lane/workflow.ts +44 -3
  45. package/src/lane-extension.ts +5 -46
  46. package/src/messaging/discord-context.ts +8 -6
  47. package/src/messaging/discord-work-thread.ts +36 -0
  48. package/src/omp/host-protocol.ts +4 -3
  49. package/src/omp/host.ts +24 -7
  50. package/src/omp/managed-super.ts +43 -27
  51. package/src/omp/native-sessions.ts +12 -0
  52. package/src/omp/worker-memory-import.ts +410 -0
  53. package/src/omp/worker-memory-sdk.ts +8 -0
  54. package/src/operator/setup.ts +8 -13
  55. package/src/pr/pr-github-schema.ts +9 -0
  56. package/src/pr/pr-github.ts +6 -2
  57. package/src/pr/pr-intake-automation.ts +11 -8
  58. package/src/pr/pr-intake-fix.ts +2 -5
  59. package/src/pr/pr-intake-review.ts +7 -7
  60. package/src/routing/topic-history.ts +2 -2
  61. package/src/runtime/controller.ts +720 -468
  62. package/src/runtime/head-recovery.ts +7 -7
  63. package/src/runtime/head-superstack.ts +83 -0
  64. package/src/runtime/result-attachments.ts +3 -1
  65. package/src/runtime/worker-memory.ts +156 -0
  66. package/src/storage/deferred-routing.ts +1 -7
  67. package/src/storage/store.ts +465 -372
  68. package/src/worker/worker-host.ts +3 -2
  69. package/src/worker/worker-ledger.ts +20 -11
  70. package/src/worker/worker-memory-page.ts +83 -0
  71. package/src/worker/worker-memory-proofs.ts +260 -0
  72. package/src/worker/worker-memory-source.ts +305 -0
  73. package/src/worker/worker-memory-storage.ts +130 -0
  74. package/src/worker/worker-profile.ts +2 -0
  75. package/src/worker/worker-repository.ts +92 -7
  76. package/src/worker/worker-request.ts +1 -0
  77. package/src/worker/worker-service.ts +25 -8
  78. package/src/worker/worker-wire.ts +20 -6
@@ -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, SCOPE_REVIEW_PREFIX, laneFallbackKey, laneModelPickerRestoreKey, physicalRoute, physicalRouteKey, resolvePickerOption, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
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, type ScopeReview, type ScopeReviewNativeProof,
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,10 @@ 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, scopeReviewApproval, type LaneReport } from "../lane/lane-report";
37
+ import { laneWaitKey, type LaneReport } from "../lane/lane-report";
38
38
  import { laneWatchReplySource } from "../lane/lane-watch";
39
- import { isOriginalAttachmentMessage, isResultAttachmentSnapshot } from "../messaging/result-attachment";
39
+ import { discordWorkThreadOwnerKey, recordedDiscordWorkThreadSource } from "../messaging/discord-work-thread";
40
+ import { isResultAttachmentSnapshot } from "../messaging/result-attachment";
40
41
  import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
41
42
  import type { CronUpdate } from "../cron/cron-jobs";
42
43
  import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "../pr/pr-intake-work";
@@ -44,10 +45,8 @@ import { isPrReviewLane, type ReviewRound } from "../pr/pr-intake-review";
44
45
  import { DeferredRoutingQueue, type DeferredChoiceRow } from "./deferred-routing";
45
46
 
46
47
  const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
47
- const SCOPE_CORRECTION_PREFIX = `handoff:${SCOPE_REVIEW_PREFIX}`;
48
- const SCOPE_REVIEW_NOT_GRANTED = "Scope correction was not authorized. The existing lane scope is unchanged. If needed, send a new, explicit request in this topic.";
49
- const SCOPE_CORRECTION_NOT_CURRENT = "The scope correction is no longer current. It was not repeated; the existing lane scope is unchanged.";
50
- const SCOPE_CORRECTION_NO_ANSWER = "The corrective request settled, but the lane returned no final answer.";
48
+ const retiredScopeId = (column: "id" | "source_id" | "retired.id" | "newer.id") =>
49
+ `(${column} GLOB 'scope-review:*' OR ${column} GLOB 'handoff:scope-review:*')`;
51
50
 
52
51
  const SCHEMA = `
53
52
  CREATE TABLE IF NOT EXISTS lanes (
@@ -90,17 +89,6 @@ const SCHEMA = `
90
89
  remote_id TEXT, UNIQUE(target, generation, request_id)
91
90
  );
92
91
  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
92
  `;
105
93
 
106
94
  const ADMITTED_MESSAGE_SCOPE = `FROM inputs
@@ -135,26 +123,6 @@ interface OutputRow {
135
123
  error: string | null;
136
124
  }
137
125
  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
126
 
159
127
  const toInput = (row: InputRow): InputRecord => {
160
128
  const { workflow, ...input } = JSON.parse(row.data) as Inbound & { workflow?: Omit<WorkflowActivation, "name"> & { name: string } };
@@ -273,9 +241,6 @@ export class Store implements StorePort {
273
241
  db.run(SCHEMA);
274
242
  const laneColumns = db.query<{ name: string }, []>("PRAGMA table_info(lanes)").all();
275
243
  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
244
  const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
280
245
  if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
281
246
  if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
@@ -294,6 +259,8 @@ export class Store implements StorePort {
294
259
  this.deferredRouting = new DeferredRoutingQueue(db, reconcileInboundRedelivery);
295
260
  this.db = db;
296
261
  this.writerLock = lock;
262
+ this.retireScopeRecords();
263
+ this.retireScopeApprovals();
297
264
  } catch (error) {
298
265
  db?.close(true);
299
266
  lock?.close(true);
@@ -301,6 +268,93 @@ export class Store implements StorePort {
301
268
  }
302
269
  }
303
270
 
271
+ private retireScopeRecords(): void {
272
+ this.db.transaction(() => {
273
+ if (this.getMeta("migration:retire-scope-review") === "true") return;
274
+ // Keep native admissions and delivery receipts. Pending synthetic work
275
+ // never ran; an admission or send without a final receipt is uncertain.
276
+ this.db.run(`UPDATE inputs SET state = CASE state WHEN 'pending' THEN 'cancelled' ELSE 'uncertain' END
277
+ WHERE state IN ('pending','submitted') AND ${retiredScopeId("id")}`);
278
+ this.retireScopeOutputs();
279
+ if (this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'scope_reviews'").get()) {
280
+ this.db.run("UPDATE scope_reviews SET state = 'closed', correction_requested = 0 WHERE state <> 'closed' OR correction_requested <> 0");
281
+ }
282
+ const active = this.getMeta("main:active-lane-recovery");
283
+ if (active && isRetiredScopeInput(active)) this.setMeta("main:active-lane-recovery", "");
284
+ // Legacy HEAD reviews did not record a per-prompt native owner.
285
+ const headSession = this.getMeta("main:sessionId");
286
+ const headGeneration = Number(this.getMeta("main:generation") ?? "0");
287
+ if (headSession && this.db.query(`SELECT 1 FROM inputs WHERE target = 'main' AND generation = ?
288
+ AND request_id IS NOT NULL AND state IN ('uncertain','cancelled') AND ${retiredScopeId("id")} LIMIT 1`)
289
+ .get(headGeneration)) this.setMeta(`retired-scope-head-session:${headGeneration}`, headSession);
290
+
291
+ this.setMeta("migration:retire-scope-review", "true");
292
+ }).immediate();
293
+ }
294
+
295
+ private retireScopeApprovals(): void {
296
+ this.db.transaction(() => {
297
+ if (this.getMeta("migration:retire-scope-approvals") === "true") return;
298
+ // Before 3e03dd1, HEAD never stored its scope-review input on the
299
+ // card. A submitted review could create any dialog on its original
300
+ // route. A sibling route or generation rules it out; an existing
301
+ // approval row, method or native UI ID does not.
302
+ const headReviews = this.db.query<InputRow & { sequence: number }, []>(`SELECT data,target,state,request_id,generation,sequence
303
+ FROM inputs WHERE target = 'main' AND request_id IS NOT NULL AND state IN ('uncertain','cancelled')
304
+ AND ${retiredScopeId("id")} ORDER BY sequence`).all();
305
+ const lastReview = new Map(headReviews.map(row => [
306
+ JSON.stringify([row.generation, routeKey(toInput(row).route)]), row.sequence,
307
+ ]));
308
+ // scope-review-approval-input was also stamped on ordinary topic
309
+ // selects. Only the HEAD and correction markers prove retirement.
310
+ const approvals = this.db.query<ApprovalRow, []>(`SELECT approvals.* FROM approvals WHERE EXISTS (
311
+ SELECT 1 FROM metadata WHERE key IN (
312
+ 'scope-head-approval-input:' || approvals.id,
313
+ 'scope-correction-approval-input:' || approvals.id,
314
+ 'native-approval-held:' || approvals.id
315
+ )) OR (target = 'main' AND generation IN (SELECT generation FROM inputs
316
+ WHERE target = 'main' AND request_id IS NOT NULL AND state IN ('uncertain','cancelled')
317
+ AND ${retiredScopeId("id")}))`).all();
318
+ for (const row of approvals) {
319
+ const approval = toApproval(row);
320
+ const marked = this.getMeta(`scope-head-approval-input:${approval.id}`) !== null
321
+ || this.getMeta(`scope-correction-approval-input:${approval.id}`) !== null
322
+ || this.getMeta(`native-approval-held:${approval.id}`) !== null;
323
+ if (!marked) {
324
+ const sequence = lastReview.get(JSON.stringify([approval.generation, routeKey(approval.route)]));
325
+ if (sequence === undefined || this.hasLaterHeadDecisionOwner(approval, sequence)) continue;
326
+ }
327
+ if (approval.state === "pending") {
328
+ this.resolveApproval(approval.id, approval.generation, "cancelled", { reason: "Retired scope workflow; no native response sent" });
329
+ }
330
+ this.setMeta(`native-approval-held:${approval.id}`, "true");
331
+ this.setMeta(`retired-approval-dismissal:${approval.id}`, "pending");
332
+ }
333
+ this.setMeta("migration:retire-scope-approvals", "true");
334
+ }).immediate();
335
+ }
336
+
337
+ private hasLaterHeadDecisionOwner(approval: Approval, retiredSequence: number): boolean {
338
+ const decision = approval.decision;
339
+ // This source is embedded in a tracked decision, unlike a generic
340
+ // confirmation. An original owner source admitted after every possible
341
+ // legacy review cannot be that review's original source.
342
+ if (!decision?.sourceId || this.getMeta(`user-source:${decision.sourceId}`) !== "true") return false;
343
+ const row = this.db.query<InputRow, [string, number, number, string]>(`SELECT inputs.data,target,state,request_id,generation
344
+ FROM inputs JOIN metadata AS native ON native.key = 'head-native-owner:' || inputs.id
345
+ AND json_valid(native.value)
346
+ WHERE inputs.id = ?1 AND sequence > ?2 AND target = 'main' AND generation = ?3
347
+ AND state IN ('submitted','done','uncertain')
348
+ AND json_extract(native.value, '$.requestId') = request_id
349
+ AND json_extract(native.value, '$.generation') = generation
350
+ AND json_extract(native.value, '$.sessionId') = ?4
351
+ AND json_type(native.value, '$.sessionFile') = 'text'
352
+ AND length(json_extract(native.value, '$.sessionFile')) > 0
353
+ AND json_type(native.value, '$.cursor') IN ('text','null')`)
354
+ .get(decision.sourceId, retiredSequence, approval.generation, decision.sessionId);
355
+ return row !== null && !isRetiredScopeInput(decision.sourceId) && routeKey(toInput(row).route) === routeKey(approval.route);
356
+ }
357
+
304
358
  receive(input: Inbound, target: string | null, metadata: Readonly<Record<string, string>> = {}, workflow: WorkflowActivation | null = null): boolean {
305
359
  if (input.discordOriginalText !== undefined && (input.route.platform !== "discord" || input.messageId === null
306
360
  || input.interactionId !== undefined || typeof input.discordOriginalText !== "string")) {
@@ -358,6 +412,7 @@ export class Store implements StorePort {
358
412
  }
359
413
  return false; // A replay never changes its current assignment or state.
360
414
  }
415
+ if (isRetiredScopeInput(input.id)) throw new Error(`Retired scope workflow input: ${input.id}`);
361
416
  if (workflow !== null) {
362
417
  workflowChoice({ name: workflow.name, reason: workflow.reason });
363
418
  if (workflow.provenance === "user") {
@@ -388,11 +443,12 @@ export class Store implements StorePort {
388
443
 
389
444
  ownerSource(id: string): InputRecord | null {
390
445
  let source = this.input(id);
391
- while (source && this.getMeta(`user-source:${source.id}`) !== "true") {
446
+ while (source && !isRetiredScopeInput(source.id)) {
447
+ if (this.getMeta(`user-source:${source.id}`) === "true") return source;
392
448
  const linked = this.getMeta(`handoff-source:${source.id}`) ?? this.getMeta(`activity-source:${source.id}`);
393
449
  source = linked ? this.input(linked) : null;
394
450
  }
395
- return source;
451
+ return null;
396
452
  }
397
453
 
398
454
  laneRecoveryScope(reportId: string): LaneRecoveryScope | null {
@@ -412,187 +468,29 @@ export class Store implements StorePort {
412
468
  return { lane, failed, original };
413
469
  }
414
470
 
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
- }
471
+ private scopedWorkSource(input: InputRecord): { sourceId: string; owner: InputRecord } | null {
472
+ const ownerId = this.getMeta(discordWorkThreadOwnerKey(input.id));
473
+ if (ownerId === null) return null;
474
+ const sourceId = this.getMeta(`handoff-source:${input.id}`);
475
+ const source = sourceId && this.ownerSource(sourceId);
476
+ const placement = recordedDiscordWorkThreadSource(this, input.route);
477
+ if (!sourceId || !source || source.id !== ownerId || !placement
478
+ || routeKey(physicalRoute(source.route)) !== routeKey(placement)
479
+ || !input.target || input.target === "main" || this.laneForRoute(input.route)?.id !== input.target
480
+ || (input.id !== `handoff:${sourceId}:lane` && input.id !== `handoff:${sourceId}:${input.target}`
481
+ && (input.id !== `resume:${sourceId}:${input.target}` || this.getMeta(`native-goal-resume-owner:${input.id}`) === null))) {
482
+ throw new Error(`Invalid scoped Discord work-thread binding: ${input.id}`);
556
483
  }
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";
484
+ return { sourceId, owner: source };
585
485
  }
586
486
 
587
487
  reportApprovalSource(id: string): InputRecord | null {
588
488
  const input = this.input(id);
589
- if (!input) return null;
489
+ if (!input || isRetiredScopeInput(id)) return null;
490
+ const scoped = this.scopedWorkSource(input);
491
+ if (scoped) return scoped.owner;
590
492
  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
- }
493
+ if (!reportId || isRetiredScopeInput(reportId) || this.input(reportId)?.target !== "main") return null;
596
494
  const sourceId = this.getMeta(`report-approval-source:${reportId}`);
597
495
  const original = sourceId === null ? null : this.ownerSource(id);
598
496
  return original?.id === sourceId ? original : null;
@@ -601,11 +499,14 @@ export class Store implements StorePort {
601
499
  private topicOwner(input: InputRecord): InputRecord | null {
602
500
  if (!input.target || input.target === "main") return null;
603
501
  let source: InputRecord | null = input;
604
- while (source && this.getMeta(`user-source:${source.id}`) !== "true") {
502
+ while (source && !isRetiredScopeInput(source.id)) {
503
+ if (this.getMeta(`user-source:${source.id}`) === "true") {
504
+ return this.getMeta(`topic-owner:${source.id}`) === input.target ? source : null;
505
+ }
605
506
  const linked: string | null = this.getMeta(`handoff-source:${source.id}`);
606
507
  source = linked ? this.input(linked) : null;
607
508
  }
608
- return source && this.getMeta(`topic-owner:${source.id}`) === input.target ? source : null;
509
+ return null;
609
510
  }
610
511
 
611
512
  topicDelivery(id: string) {
@@ -760,24 +661,20 @@ export class Store implements StorePort {
760
661
  }
761
662
 
762
663
  hasPendingLaneResult(target: string): boolean {
763
- if (this.hasPendingScopeReview(target)) return true;
664
+ if (this.hasLegacyScopeReviews() && this.db.query(`SELECT 1 FROM scope_reviews AS review
665
+ JOIN outputs ON outputs.id IN (review.id || ':answer', review.correction_id || ':answer')
666
+ WHERE review.lane_id = ? AND outputs.state IN ('pending','sending','uncertain') LIMIT 1`).get(target)) return true;
764
667
  return this.db.query(`SELECT 1 FROM inputs AS run
765
668
  LEFT JOIN inputs AS report ON report.id = 'report:' || run.id
766
669
  LEFT JOIN inputs AS recovered ON recovered.id = 'report:' || run.id || ':done'
767
- LEFT JOIN inputs AS scope ON scope.id = ?2 || run.id
768
- LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer'
769
- LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, scope.id, run.id) || ':answer:done'
670
+ LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, run.id) || ':answer'
671
+ LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, run.id) || ':answer:done'
770
672
  WHERE run.target = ?1 AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
771
673
  AND (COALESCE(recovered.state, report.state) IN ('pending','submitted','uncertain')
772
- OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain'))
773
- LIMIT 1`).get(target, SCOPE_REVIEW_PREFIX) !== null;
774
- }
775
-
776
- hasPendingScopeReview(target: string): boolean {
777
- const rows = this.db.query<Pick<ScopeReviewRow, "id">, [string]>(
778
- "SELECT id FROM scope_reviews WHERE lane_id = ? AND state IN ('review','granted')",
779
- ).all(target);
780
- return rows.some(row => this.scopeReview(row.id) !== null);
674
+ OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain')
675
+ -- A retired review cannot run, but its interrupted send still holds this lane.
676
+ OR EXISTS (SELECT 1 FROM outputs WHERE id = 'scope-review:' || run.id || ':answer' AND state = 'uncertain'))
677
+ LIMIT 1`).get(target) !== null;
781
678
  }
782
679
 
783
680
  hasPendingLanePlacement(target: string): boolean {
@@ -787,11 +684,36 @@ export class Store implements StorePort {
787
684
  LIMIT 1`).get(target) !== null;
788
685
  }
789
686
 
687
+ hasWorkerMemoryHold(target: string): boolean {
688
+ return this.db.query(`SELECT 1 WHERE
689
+ EXISTS (SELECT 1 FROM inputs WHERE (target IS NULL OR target IN ('main', ?1)) AND ${ACTIVE_INPUTS}) OR
690
+ EXISTS (SELECT 1 FROM approvals WHERE target IN ('main', ?1) AND state = 'pending')`).get(target) !== null
691
+ || this.hasPendingLaneResult(target);
692
+ }
693
+
694
+ tryWorkerMemoryMeta(keys: string | readonly string[], value: string): boolean {
695
+ const batch = typeof keys === "string" ? [keys] : keys;
696
+ if (!batch.every(key => key.startsWith("worker-memory:"))) throw new Error("Invalid worker memory receipt key");
697
+ const policy = this.db.query<{ timeout: number }, []>("PRAGMA busy_timeout").get();
698
+ if (!policy || this.db.inTransaction) return false;
699
+ this.db.run("PRAGMA busy_timeout = 0");
700
+ try {
701
+ // One autocommit for the entire page. A concurrent ingress writer
702
+ // cannot reserve only a suffix/prefix of its native fact IDs.
703
+ this.db.query(`INSERT INTO metadata(key,value) SELECT value, ?2 FROM json_each(?1) WHERE true
704
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(JSON.stringify(batch), value);
705
+ return true;
706
+ } catch (error) {
707
+ if (error instanceof SQLiteError && [5, 6].includes(error.errno & 255)) return false;
708
+ throw error;
709
+ } finally { this.db.run(`PRAGMA busy_timeout = ${policy.timeout}`); }
710
+ }
711
+
790
712
  hasHeadRecoveryInput(): boolean {
791
713
  return this.db.query(`SELECT 1 FROM inputs
792
714
  JOIN metadata ON metadata.key = 'head-native-owner:' || inputs.id AND metadata.value <> ''
793
715
  WHERE inputs.target = 'main' AND inputs.state = 'uncertain'
794
- AND NOT EXISTS (SELECT 1 FROM scope_reviews WHERE scope_reviews.id = inputs.id) LIMIT 1`).get() !== null;
716
+ AND NOT ${retiredScopeId("id")} LIMIT 1`).get() !== null;
795
717
  }
796
718
 
797
719
  kickoffHold(target: string): KickoffHold | null {
@@ -818,6 +740,25 @@ export class Store implements StorePort {
818
740
  ).all(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId, messageId).map(toInput);
819
741
  }
820
742
 
743
+ isLateTopicOriginal(source: InputRecord): boolean {
744
+ const { messageId, route } = source;
745
+ if (messageId === null) return false;
746
+ // Normally this is the newest physical message. A higher cursor alone is
747
+ // not proof: it may belong to another logical topic or a later admission.
748
+ const cursor = this.getMeta(`cursor:${physicalRouteKey(route)}`);
749
+ if (cursor === messageId && this.getMeta(`topic-revision:${source.id}`) === null) return false;
750
+ const rows = this.db.query<{ messageId: string }, [string, string, string, string, string | null, string | null, string | null, string]>(
751
+ `SELECT json_extract(inputs.data, '$.messageId') AS messageId ${ADMITTED_MESSAGE_SCOPE}
752
+ AND json_extract(inputs.data, '$.route.topicId') IS ? AND inputs.sequence < (SELECT sequence FROM inputs WHERE id = ?)
753
+ ORDER BY inputs.sequence DESC`,
754
+ ).iterate(route.platform, route.channelId, route.accountId, route.authorityId, route.guildId, route.threadId, route.topicId ?? null, source.id);
755
+ for (const earlier of rows) {
756
+ const order = compareMessageIds(route.platform, earlier.messageId, messageId);
757
+ if (order === 1 || order === 0) return true;
758
+ }
759
+ return false;
760
+ }
761
+
821
762
  /** Recognize a misplaced choice without exposing another thread's question or granting it a vote. */
822
763
  isDiscordWorkspaceQuestion(route: Route, messageId: string): boolean {
823
764
  if (route.platform !== "discord") return false;
@@ -977,18 +918,7 @@ export class Store implements StorePort {
977
918
  submit(id: string, requestId: string, generation: number): boolean {
978
919
  return this.db.transaction(() => {
979
920
  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
- }
921
+ if (!input || input.state !== "pending" || input.target === null || isRetiredScopeInput(id)) return false;
992
922
  const progress = this.getMeta(`progress-source:${id}`);
993
923
  if (progress && !this.progressOpen(JSON.parse(progress))) {
994
924
  this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(id);
@@ -1020,12 +950,35 @@ export class Store implements StorePort {
1020
950
  }).immediate();
1021
951
  }
1022
952
 
953
+ submitGoalResume(input: Inbound, target: string, sourceId: string, owner: Parameters<StorePort["submitGoalResume"]>[3],
954
+ priorWorkState?: Lane["workState"]): InputRecord {
955
+ return this.db.transaction(() => {
956
+ if (target !== "main") {
957
+ const lane = this.lane(target);
958
+ if (!lane || lane.workState !== priorWorkState || lane.workState === "cancelled" || lane.sessionId !== owner.sessionId
959
+ || lane.generation !== owner.generation || !this.updateLane(target, owner.generation, {
960
+ workState: "open", runtimeState: "running", lastActivityAt: Date.now(),
961
+ })) throw new Error("The original lane changed before goal resume");
962
+ }
963
+ // Separate from prompt ownership: an interrupted goal resume must never replay as a prompt.
964
+ if (!this.receive(input, target, {
965
+ [`handoff-source:${input.id}`]: sourceId,
966
+ [`native-goal-resume-owner:${input.id}`]: JSON.stringify(owner),
967
+ ...(owner.scopedWorkOwnerId === undefined ? {} : { [discordWorkThreadOwnerKey(input.id)]: owner.scopedWorkOwnerId }),
968
+ })) throw new Error("Native goal resume was not admitted");
969
+ if (owner.scopedWorkOwnerId !== undefined) this.scopedWorkSource(this.requireInput(input.id));
970
+ if (!this.submit(input.id, owner.requestId, owner.generation)) throw new Error("Native goal resume was not admitted");
971
+ return this.requireInput(input.id);
972
+ }).immediate();
973
+ }
974
+
1023
975
  private progressOpen(context: { inputId: string; generation: number; sessionId: string }): boolean {
1024
976
  const input = this.input(context.inputId);
1025
- if (!input || input.state !== "submitted" || input.generation !== context.generation || this.laneRecoveryObsolete(input.id)) return false;
977
+ if (!input || input.state !== "submitted" || input.generation !== context.generation
978
+ || isRetiredScopeInput(input.id) || this.laneRecoveryObsolete(input.id)) return false;
1026
979
  const sourceId = this.getMeta(`handoff-source:${input.id}`);
1027
980
  const source = sourceId ? this.input(sourceId) : input;
1028
- if (!source || source.state === "cancelled" || source.state === "uncertain") return false;
981
+ if (!source || isRetiredScopeInput(source.id) || source.state === "cancelled" || source.state === "uncertain") return false;
1029
982
  if (input.target === "main") {
1030
983
  const parent = this.getMeta(`progress-source:${input.id}`);
1031
984
  return (!parent || this.progressOpen(JSON.parse(parent)))
@@ -1094,7 +1047,7 @@ export class Store implements StorePort {
1094
1047
  }
1095
1048
 
1096
1049
  progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace = false): boolean {
1097
- if (!text.trim() || id.startsWith(SCOPE_REVIEW_PREFIX) || id.startsWith(SCOPE_CORRECTION_PREFIX)) return false;
1050
+ if (!text.trim()) return false;
1098
1051
  return this.db.transaction(() => {
1099
1052
  const context = { inputId: id, generation, sessionId };
1100
1053
  if (!this.progressOpen(context)) return false;
@@ -1227,73 +1180,16 @@ export class Store implements StorePort {
1227
1180
  }).immediate();
1228
1181
  }
1229
1182
 
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
1183
  settle(id: string, state: "done" | "uncertain" | "cancelled", settlement?: SettlementOutput, headModel?: HeadModelChange, editInPlace = false): boolean {
1294
1184
  return this.db.transaction(() => {
1295
1185
  const input = this.input(id);
1296
1186
  if (!input || input.state === "done" || input.state === "cancelled") return false;
1187
+ if (isRetiredScopeInput(id)) {
1188
+ // Explicit resolution may close a held receipt, but it cannot turn
1189
+ // retired work into a successful result or ordinary delivery.
1190
+ if (state !== "cancelled") return false;
1191
+ return this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ?").run(id).changes === 1;
1192
+ }
1297
1193
  const progress = this.getMeta(`progress-source:${id}`);
1298
1194
  const output = settlement && (!progress || this.progressOpen(JSON.parse(progress))) && !this.laneRecoveryObsolete(id)
1299
1195
  ? { id: settlement.id, text: settlement.text, picker: settlement.picker } : undefined;
@@ -1307,14 +1203,6 @@ export class Store implements StorePort {
1307
1203
  if (input.state === state && (state !== "uncertain" || !newQuota)) return false;
1308
1204
  const pending = this.getMeta(`progress-pending:${id}`);
1309
1205
  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
1206
  const reportId = `report:${id}`;
1319
1207
  if (input.state === "uncertain" && (newQuota || state !== "uncertain")
1320
1208
  && this.getMeta(`lane-recovery-input:${reportId}`) === id
@@ -1390,8 +1278,11 @@ export class Store implements StorePort {
1390
1278
  } else {
1391
1279
  this.queueOutput({ ...output, sourceId: id, route: input.route });
1392
1280
  }
1393
- } else {
1394
- this.queueOutput({ ...output, sourceId: id, route: input.route });
1281
+ } else if (this.queueOutput({ ...output, sourceId: id, route: input.route })
1282
+ && settlement?.discordHeadFollowups?.length && state === "done" && input.state === "submitted"
1283
+ && input.target === "main" && input.route.platform === "discord" && output.id === `${id}:answer`
1284
+ && !output.picker && output.text.trim() && this.ownerSource(id)?.id === id) {
1285
+ this.setMeta(`discord-head-followups:${output.id}`, JSON.stringify(settlement.discordHeadFollowups));
1395
1286
  }
1396
1287
  }
1397
1288
  this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
@@ -1439,16 +1330,15 @@ export class Store implements StorePort {
1439
1330
 
1440
1331
  headRecoveryEffects(inputId: string): HeadRecoveryEffect[] {
1441
1332
  const input = this.requireInput(inputId);
1442
- const related = [inputId, ...this.inputs().filter(candidate =>
1443
- this.getMeta(`handoff-source:${candidate.id}`) === inputId).map(candidate => candidate.id)];
1444
- return this.inputEffects(input, related, id => this.approval(id)?.target === "main");
1445
- }
1446
-
1447
- private inputEffects(input: InputRecord, related: readonly string[], ownsApproval: (id: string) => boolean): HeadRecoveryEffect[] {
1333
+ const related = new Set([inputId]);
1334
+ for (const candidate of this.inputs()) {
1335
+ if (this.getMeta(`handoff-source:${candidate.id}`) === inputId) related.add(candidate.id);
1336
+ }
1448
1337
  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.includes(row.source_id));
1338
+ Array<{ id: string; source_id: string; state: string }>).filter(row => related.has(row.source_id));
1450
1339
  const effects: HeadRecoveryEffect[] = outputs.map(row => ({ id: row.id, kind: "output", state: row.state }));
1451
1340
  if (this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='gateway_effects'").get()) {
1341
+ const outputIds = new Set(outputs.map(row => row.id));
1452
1342
  // Never select arguments/results into a model-visible snapshot. The SQL
1453
1343
  // projection reads only identity and delivery certainty, not credentials.
1454
1344
  const rows = this.db.query(`SELECT id,operation,state,
@@ -1461,10 +1351,10 @@ export class Store implements StorePort {
1461
1351
  Array<{ id: string; operation: string; state: string; source: string | null; target: string | null;
1462
1352
  message: string | null; certainty: string | null; ok: number | null }>;
1463
1353
  for (const row of rows) {
1464
- const relevant = related.includes(row.source ?? "") || outputs.some(output => output.id === row.target)
1354
+ const relevant = related.has(row.source ?? "") || (row.target !== null && outputIds.has(row.target))
1465
1355
  || row.operation === "createThread" && input.messageId !== null && row.message === input.messageId
1466
1356
  || (row.operation === "showApproval" || row.operation === "dismissApproval")
1467
- && row.target !== null && ownsApproval(row.target);
1357
+ && row.target !== null && this.approval(row.target)?.target === "main";
1468
1358
  if (relevant) effects.push({ id: row.id, kind: row.operation,
1469
1359
  state: row.state === "attempted" || row.certainty === "uncertain" || row.ok === null ? "uncertain"
1470
1360
  : row.ok === 0 ? "failed" : "sent" });
@@ -1478,7 +1368,7 @@ export class Store implements StorePort {
1478
1368
  const input = this.input(attempt.inputId);
1479
1369
  if (attempt.state !== "prepared" || this.getMeta("head:recovery-active")
1480
1370
  || this.getMeta(`head:recovery:${attempt.inputId}`) || input?.target !== "main" || input.state !== "uncertain"
1481
- || input.id.startsWith(SCOPE_REVIEW_PREFIX)
1371
+ || isRetiredScopeInput(input.id)
1482
1372
  || input.requestId !== attempt.requestId || input.generation !== attempt.generation
1483
1373
  || this.getMeta("head:stop-boundary") !== attempt.stopBoundary) return false;
1484
1374
  this.setMeta(`head:recovery:${attempt.inputId}`, JSON.stringify(attempt));
@@ -1490,7 +1380,7 @@ export class Store implements StorePort {
1490
1380
  commitHeadRecovery(expected: HeadRecoveryAttempt, decided: HeadRecoveryAttempt): boolean {
1491
1381
  return this.db.transaction(() => {
1492
1382
  const input = this.input(expected.inputId);
1493
- if (this.getMeta("head:recovery-active") !== expected.inputId
1383
+ if (isRetiredScopeInput(expected.inputId) || this.getMeta("head:recovery-active") !== expected.inputId
1494
1384
  || this.getMeta(`head:recovery:${expected.inputId}`) !== JSON.stringify(expected)
1495
1385
  || decided.decision?.decision === "release" && this.getMeta("head:stop-boundary") !== expected.stopBoundary
1496
1386
  || input?.target !== "main" || input.state !== "uncertain"
@@ -1498,8 +1388,7 @@ export class Store implements StorePort {
1498
1388
  || decided.attemptId !== expected.attemptId || decided.inputId !== expected.inputId
1499
1389
  || !decided.decision || !["decided", "settled"].includes(decided.state)) return false;
1500
1390
  if (decided.decision.decision === "release") {
1501
- if (!decided.outcome || this.headRecoveryEffects(input.id).some(effect =>
1502
- !["sent", "complete", "failed"].includes(effect.state))) return false;
1391
+ if (!decided.outcome || !headRecoveryEffectsSettled(this.headRecoveryEffects(input.id))) return false;
1503
1392
  if (decided.state === "settled") this.settle(input.id, decided.outcome, { id: `${input.id}:recovery:${expected.attemptId}`,
1504
1393
  text: decided.outcome === "done"
1505
1394
  ? "원래 세션의 정확한 요청 접수 기록과 마지막 실행 근거로 native 처리 종료를 확인했습니다. 사용자 작업의 완료·수락 기준 충족을 주장하지 않으며 원래 작업을 다시 실행하지 않았습니다."
@@ -1515,6 +1404,11 @@ export class Store implements StorePort {
1515
1404
  }
1516
1405
 
1517
1406
  laneReplyRoute(input: InputRecord, source: InputRecord): Route {
1407
+ const scoped = this.scopedWorkSource(input);
1408
+ if (scoped) {
1409
+ if (scoped.sourceId !== source.id) throw new Error(`Invalid scoped Discord reply source: ${input.id}`);
1410
+ return input.route;
1411
+ }
1518
1412
  const handoffReply = this.getMeta(`handoff-reply:${input.id}`);
1519
1413
  if (handoffReply !== null) {
1520
1414
  const { route } = input;
@@ -1547,6 +1441,7 @@ export class Store implements StorePort {
1547
1441
  }
1548
1442
 
1549
1443
  queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
1444
+ if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) return false;
1550
1445
  if (output.status && (output.route.platform !== "discord" || output.picker || output.resultAttachment)) {
1551
1446
  throw new Error(`Status delivery requires a plain Discord message: ${output.id}`);
1552
1447
  }
@@ -1559,6 +1454,7 @@ export class Store implements StorePort {
1559
1454
  || !isDeepStrictEqual(existing.resultAttachment, output.resultAttachment)
1560
1455
  || output.replyTo !== undefined && (!existing.replyTo
1561
1456
  || existing.replyTo.messageId !== output.replyTo.messageId
1457
+ || existing.replyTo.requireExisting !== output.replyTo.requireExisting
1562
1458
  || physicalRouteKey(existing.replyTo.route) !== physicalRouteKey(output.replyTo.route))) {
1563
1459
  throw new Error(`Output identity conflict: ${output.id}`);
1564
1460
  }
@@ -1595,7 +1491,8 @@ export class Store implements StorePort {
1595
1491
  const replyOrigin = original ?? laneWatchReplySource(this, source, output.id);
1596
1492
  const replyTo = replyOrigin?.route.platform === "discord" && replyOrigin.messageId
1597
1493
  && physicalRouteKey(replyOrigin.route) === physicalRouteKey(output.route)
1598
- ? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId } : undefined;
1494
+ ? { route: physicalRoute(replyOrigin.route), messageId: replyOrigin.messageId,
1495
+ ...(output.replyTo?.requireExisting ? { requireExisting: true } : {}) } : undefined;
1599
1496
  if (output.replyTo !== undefined && (!replyTo || output.replyTo.messageId !== replyTo.messageId
1600
1497
  || physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
1601
1498
  throw new Error(`Output reply differs from its source: ${output.id}`);
@@ -1671,6 +1568,66 @@ export class Store implements StorePort {
1671
1568
  EXISTS (SELECT 1 FROM outputs WHERE state IN ('pending','sending','uncertain'))`).get() !== null;
1672
1569
  }
1673
1570
 
1571
+ private hasLegacyScopeReviews(): boolean {
1572
+ return this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'scope_reviews'").get() !== null;
1573
+ }
1574
+
1575
+ private retireScopeOutputs(): void {
1576
+ const scope = `(${retiredScopeId("id")} OR ${retiredScopeId("source_id")})`;
1577
+ this.db.run(`UPDATE outputs SET state = 'uncertain',
1578
+ error = 'Retired scope workflow; delivery interrupted before a durable receipt'
1579
+ WHERE state = 'sending' AND ${scope}`);
1580
+ const pending = this.db.query<OutputRow, []>(`SELECT * FROM outputs WHERE state = 'pending' AND ${scope}`).all();
1581
+ const hasReviews = pending.length > 0 && this.hasLegacyScopeReviews();
1582
+ const fail = this.db.query(`UPDATE outputs SET state = 'failed',
1583
+ error = 'Retired scope workflow; no delivery attempted' WHERE id = ?`);
1584
+ for (const row of pending) {
1585
+ if (!hasReviews || !this.isSettledLegacyScopeAnswer(toOutput(row))) fail.run(row.id);
1586
+ }
1587
+ }
1588
+
1589
+ private isSettledLegacyScopeAnswer(output: OutputRecord): boolean {
1590
+ // The old settlement transaction closed the review, queued the final
1591
+ // answer using source_id, and marked the synthetic admission done.
1592
+ if (!output.id.endsWith(":answer")) return false;
1593
+ const resultInputId = output.id.slice(0, -":answer".length);
1594
+ const review = this.db.query<{
1595
+ id: string; correction_id: string; handoff_id: string; lane_id: string; generation: number; request_id: string;
1596
+ }, [string, string]>(`SELECT id, correction_id, handoff_id, lane_id, generation, request_id
1597
+ FROM scope_reviews WHERE state = 'closed' AND correction_requested = 0 AND source_id = ?1
1598
+ AND (?2 = id OR ?2 = correction_id)`).get(output.sourceId, resultInputId);
1599
+ if (!review || review.id !== `scope-review:${review.handoff_id}`
1600
+ || review.handoff_id !== `handoff:${output.sourceId}:${review.lane_id}`
1601
+ || review.correction_id !== `handoff:${review.id}:${review.lane_id}`
1602
+ || output.remoteId !== null || output.editOf || output.status || output.picker || output.resultAttachment
1603
+ || !output.text.trim()) return false;
1604
+ const source = this.input(output.sourceId);
1605
+ const handoff = this.input(review.handoff_id);
1606
+ const reviewed = this.input(review.id);
1607
+ if (!source?.messageId || source.target !== null || source.state !== "done"
1608
+ || isRetiredScopeInput(source.id) || this.getMeta(`user-source:${source.id}`) !== "true"
1609
+ || this.getMeta(`topic-owner:${source.id}`) !== review.lane_id
1610
+ || handoff?.target !== review.lane_id || handoff.state !== "done"
1611
+ || !handoff.requestId || handoff.requestId !== review.request_id || handoff.generation !== review.generation
1612
+ || this.getMeta(`handoff-source:${handoff.id}`) !== source.id
1613
+ || reviewed?.target !== "main" || reviewed.state !== "done" || !reviewed.requestId || reviewed.generation === null
1614
+ || this.getMeta(`activity-source:${reviewed.id}`) !== source.id) return false;
1615
+ const route = routeKey(source.route);
1616
+ if (routeKey(handoff.route) !== route || routeKey(reviewed.route) !== route || routeKey(output.route) !== route) return false;
1617
+ if (resultInputId === review.correction_id) {
1618
+ const correction = this.input(review.correction_id);
1619
+ if (correction?.target !== review.lane_id || correction.state !== "done" || !correction.requestId
1620
+ || correction.generation !== review.generation || routeKey(correction.route) !== route
1621
+ || this.getMeta(`handoff-source:${correction.id}`) !== reviewed.id
1622
+ || this.getMeta(`report-approval-source:${reviewed.id}`) !== source.id) return false;
1623
+ } else if (this.input(review.correction_id)) {
1624
+ return false; // The old review did not queue an answer when it granted a correction.
1625
+ }
1626
+ return source.route.platform === "discord"
1627
+ ? output.replyTo?.messageId === source.messageId && routeKey(output.replyTo.route) === physicalRouteKey(source.route)
1628
+ : output.replyTo === undefined;
1629
+ }
1630
+
1674
1631
  /**
1675
1632
  * A Discord status update edits the stream's message only after that message's
1676
1633
  * creation was confirmed. The edit target is persisted with the claim, so a
@@ -1685,6 +1642,15 @@ export class Store implements StorePort {
1685
1642
  }
1686
1643
  const output = this.output(id);
1687
1644
  if (output?.state !== "pending") return false;
1645
+ if (isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId)) {
1646
+ // Only the existing immutable answer can be sent. Do not consult live
1647
+ // lane/HEAD ownership or mutate its historical reply/edit destination.
1648
+ if (this.hasLegacyScopeReviews() && this.isSettledLegacyScopeAnswer(output)) {
1649
+ return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'").run(id).changes === 1;
1650
+ }
1651
+ this.db.query("UPDATE outputs SET state = 'failed', error = 'Retired scope workflow; no delivery attempted' WHERE id = ?").run(id);
1652
+ return false;
1653
+ }
1688
1654
  if (this.laneRecoveryObsolete(output.sourceId)) {
1689
1655
  this.suppressLaneReport(output.sourceId, "Lane recovery report no longer has current owner authority");
1690
1656
  return false;
@@ -1712,13 +1678,22 @@ export class Store implements StorePort {
1712
1678
  if (output.resultAttachment && state === "pending") {
1713
1679
  throw new Error(`A result attachment is never retried: ${id}`);
1714
1680
  }
1681
+ const retired = isRetiredScopeInput(output.id) || isRetiredScopeInput(output.sourceId);
1682
+ if (state === "pending" && retired) {
1683
+ throw new Error(`Retired scope workflow output is never retried: ${id}`);
1684
+ }
1715
1685
  const retry = state === "pending" && (output.state === "uncertain" || output.state === "failed");
1716
- const reconcile = output.state === "uncertain" && state === "sent";
1686
+ // A definitively rejected retired send releases its hold, never its retry fence.
1687
+ const reconcile = output.state === "uncertain" && (state === "sent"
1688
+ || (state === "failed" && retired && remoteId === undefined && output.remoteId === null));
1717
1689
  if (output.state !== "sending" && !retry && !reconcile) {
1718
1690
  throw new Error(`Invalid output transition ${output.state} -> ${state}: ${id}`);
1719
1691
  }
1720
1692
  this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
1721
1693
  .run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
1694
+ if (state === "sent" && remoteId && output.route.platform === "discord") {
1695
+ this.queueDiscordHeadFollowupLinks(output, remoteId);
1696
+ }
1722
1697
  const stream = this.getMeta(`status-stream:${id}`);
1723
1698
  if (stream) {
1724
1699
  const anchorKey = `status-anchor:${stream}`;
@@ -1740,6 +1715,35 @@ export class Store implements StorePort {
1740
1715
  }).immediate();
1741
1716
  }
1742
1717
 
1718
+ private queueDiscordHeadFollowupLinks(output: OutputRecord, remoteId: string): void {
1719
+ const key = `discord-head-followups:${output.id}`;
1720
+ const saved = this.getMeta(key);
1721
+ if (!saved) return;
1722
+ const owner = this.input(output.sourceId);
1723
+ const target = output.replyTo;
1724
+ const guild = output.route.guildId;
1725
+ const channel = output.route.threadId ?? output.route.channelId;
1726
+ const snowflake = /^\d{1,20}$/u;
1727
+ if (owner?.target !== "main" || owner.state !== "done"
1728
+ || (owner.messageId === null ? !owner.interactionId || target !== undefined : target?.messageId !== owner.messageId)
1729
+ || !snowflake.test(channel) || guild !== null && !snowflake.test(guild) || !snowflake.test(remoteId)) return;
1730
+ const url = `https://discord.com/channels/${guild ?? "@me"}/${channel}/${remoteId}`;
1731
+ const physical = new Set(owner.messageId === null ? [] : [owner.messageId]);
1732
+ for (const id of JSON.parse(saved) as string[]) {
1733
+ const source = this.input(id);
1734
+ if (source?.target !== "main" || source.state !== "done" || source.generation !== owner.generation
1735
+ || !source.messageId || !snowflake.test(source.messageId) || physical.has(source.messageId)
1736
+ || routeKey(source.route) !== routeKey(output.route) || this.ownerSource(id)?.id !== id
1737
+ || this.getMeta(`steering-owner:${id}`) !== owner.id) continue;
1738
+ physical.add(source.messageId);
1739
+ this.queueOutput({ id: `${output.id}:joined:${id}`, sourceId: id, route: source.route,
1740
+ replyTo: { route: physicalRoute(source.route), messageId: source.messageId, requireExisting: true },
1741
+ text: `이 후속 메시지와 함께 처리한 [HEAD 통합 답변](<${url}>)` });
1742
+ }
1743
+ // Commit the canonical send receipt and its dependent notices together.
1744
+ this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
1745
+ }
1746
+
1743
1747
  createLane(lane: Lane & { model: LaneModel; modelReason: string }, sourceId: string): Lane {
1744
1748
  if (!isLaneModel(lane.model) || typeof lane.modelReason !== "string" || !lane.modelReason.trim()
1745
1749
  || (lane.modelPreset !== null && (typeof lane.modelPreset !== "string" || !lane.modelPreset.trim() || !lane.modelPresetSnapshot))
@@ -1804,10 +1808,6 @@ export class Store implements StorePort {
1804
1808
  return this.db.transaction(() => {
1805
1809
  const lane = this.lane(id);
1806
1810
  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
1811
  // Explicitly copy the contract whitelist; runtime callers cannot change identity.
1812
1812
  for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result"] as const) {
1813
1813
  if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
@@ -1961,25 +1961,17 @@ export class Store implements StorePort {
1961
1961
  }
1962
1962
  if (ownerInputId) {
1963
1963
  const owner = this.input(ownerInputId);
1964
- if (owner?.target !== approval.target || owner.generation !== approval.generation)
1964
+ if (owner?.target !== approval.target || owner.generation !== approval.generation || isRetiredScopeInput(owner.id))
1965
1965
  throw new Error(`Approval does not match its topic source: ${approval.id}`);
1966
1966
  const reportSource = this.reportApprovalSource(owner.id);
1967
1967
  if (reportSource) {
1968
1968
  if (routeKey(reportSource.route) !== routeKey(approval.route))
1969
1969
  throw new Error(`Approval does not match its original report source: ${approval.id}`);
1970
- if (owner.id.startsWith(SCOPE_CORRECTION_PREFIX)) {
1971
- this.setMeta(`topic-approval:${approval.id}`, reportSource.id);
1972
- this.setMeta(`scope-correction-approval-input:${approval.id}`, owner.id);
1973
- }
1974
1970
  } else {
1975
1971
  const topic = this.topicDelivery(owner.id);
1976
1972
  if (!topic || routeKey(topic.route) !== routeKey(approval.route))
1977
1973
  throw new Error(`Approval does not match its topic source: ${approval.id}`);
1978
1974
  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
1975
  }
1984
1976
  } else this.checkTarget(approval.target, approval.route);
1985
1977
  const lane = this.lane(approval.target);
@@ -2001,31 +1993,108 @@ export class Store implements StorePort {
2001
1993
  AND (?1 IS NULL OR target = ?1) ORDER BY sequence`).all(target ?? null) as ApprovalRow[]).map(toApproval);
2002
1994
  }
2003
1995
 
1996
+ isNativeApprovalHeld(owner: {
1997
+ readonly target: string; readonly generation: number; readonly sessionId: string;
1998
+ readonly input?: { readonly id: string; readonly sessionFile: string };
1999
+ }, approvalId: string): boolean {
2000
+ if (this.getMeta(`native-approval-held:${approvalId}`) !== null
2001
+ || this.getMeta(`scope-cancel:${owner.sessionId}:${approvalId}`) !== null
2002
+ || this.getMeta(`retired-scope-dialog:${owner.sessionId}:${approvalId}`) !== null) return true;
2003
+ // A stock UI ID does not identify the original prompt, and resolving the
2004
+ // ledger receipt does not close native UI. Only the current later native
2005
+ // admission can own a new dialog, not a completed turn or a stop receipt.
2006
+ return this.db.query(`SELECT 1 FROM inputs AS retired
2007
+ LEFT JOIN metadata AS previous ON previous.key = ?5 || retired.id
2008
+ LEFT JOIN metadata AS head ON head.key = 'retired-scope-head-session:' || retired.generation AND retired.target = 'main'
2009
+ WHERE retired.target = ?1 AND retired.generation = ?2 AND retired.request_id IS NOT NULL
2010
+ AND retired.state IN ('uncertain','cancelled') AND ${retiredScopeId("retired.id")}
2011
+ AND COALESCE(CASE WHEN json_valid(previous.value) THEN json_extract(previous.value, '$.sessionId') END,
2012
+ head.value, ?4) = ?4
2013
+ AND NOT EXISTS (SELECT 1 FROM approvals WHERE id = ?3)
2014
+ AND NOT EXISTS (
2015
+ SELECT 1 FROM inputs AS newer
2016
+ JOIN metadata AS native ON native.key IN (?5 || newer.id, 'native-goal-resume-owner:' || newer.id)
2017
+ AND json_valid(native.value)
2018
+ WHERE newer.target = retired.target AND newer.generation = retired.generation
2019
+ AND newer.id = ?6 AND newer.sequence > retired.sequence AND newer.state = 'submitted'
2020
+ AND NOT ${retiredScopeId("newer.id")}
2021
+ AND json_extract(native.value, '$.requestId') = newer.request_id
2022
+ AND json_extract(native.value, '$.generation') = newer.generation
2023
+ AND json_extract(native.value, '$.sessionId') = ?4
2024
+ AND json_extract(native.value, '$.sessionFile') = ?7
2025
+ AND json_type(native.value, '$.cursor') IN ('text','null')
2026
+ ) LIMIT 1`).get(owner.target, owner.generation, approvalId, owner.sessionId,
2027
+ owner.target === "main" ? "head-native-owner:" : "lane-observation-owner:",
2028
+ owner.input?.id ?? null, owner.input?.sessionFile ?? null) !== null;
2029
+ }
2030
+
2031
+ retiredApprovalDismissals(): string[] {
2032
+ return this.db.query<{ id: string }, []>(`SELECT a.id FROM approvals AS a
2033
+ JOIN metadata AS dismissal ON dismissal.key = 'retired-approval-dismissal:' || a.id
2034
+ WHERE dismissal.value IN ('pending','attempted') ORDER BY a.sequence`).all().map(row => row.id);
2035
+ }
2036
+
2037
+ claimRetiredApprovalDismissal(id: string): Approval | null {
2038
+ return this.db.transaction(() => {
2039
+ const dismissal = `retired-approval-dismissal:${id}`;
2040
+ const phase = this.getMeta(dismissal);
2041
+ const approval = this.approval(id);
2042
+ if (!approval || (phase !== "pending" && phase !== "attempted")) return null;
2043
+ // A previous controller may have lost its local receipt after the
2044
+ // Gateway recorded the remote one. Never use another card's effect or
2045
+ // infer a remote message from an attempted send.
2046
+ let remoteId = approval.remoteId;
2047
+ let uncertainDismissal = false;
2048
+ const dismissals = new Set<string>();
2049
+ if (this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get()) {
2050
+ const effects = this.db.query<{ operation: string; arguments: string; result: string | null }, [string]>(`
2051
+ SELECT operation, arguments, result FROM gateway_effects
2052
+ WHERE operation IN ('showApproval','dismissApproval') AND json_valid(arguments)
2053
+ AND json_extract(arguments, '$[0].id') = ?`).all(id);
2054
+ const messages = new Set(remoteId ? [remoteId] : []);
2055
+ for (const effect of effects) {
2056
+ const [card] = JSON.parse(effect.arguments) as Approval[];
2057
+ if (!card || !isDeepStrictEqual(approvalIdentity(card), approvalIdentity(approval))) continue;
2058
+ const result = effect.result === null ? null : JSON.parse(effect.result) as
2059
+ { ok?: boolean; certainty?: string; value?: unknown };
2060
+ if (effect.operation === "showApproval") {
2061
+ if (result?.ok === true && typeof result.value === "string" && result.value) messages.add(result.value);
2062
+ } else if (result?.ok === true && card.remoteId) {
2063
+ dismissals.add(card.remoteId);
2064
+ } else if (result?.certainty !== "rejected") {
2065
+ uncertainDismissal = true;
2066
+ }
2067
+ }
2068
+ if (messages.size !== 1) return null;
2069
+ remoteId = messages.values().next().value ?? null;
2070
+ }
2071
+ if (!remoteId) return null;
2072
+ if (dismissals.has(remoteId)) {
2073
+ this.setMeta(dismissal, "complete");
2074
+ return null;
2075
+ }
2076
+ if (phase === "attempted" || uncertainDismissal || dismissals.size) return null;
2077
+ this.setApprovalMessage(id, remoteId);
2078
+ this.setMeta(dismissal, "attempted");
2079
+ return { ...approval, remoteId };
2080
+ }).immediate();
2081
+ }
2082
+
2083
+ finishRetiredApprovalDismissal(id: string): void {
2084
+ this.db.query("UPDATE metadata SET value = 'complete' WHERE key = ? AND value = 'attempted'")
2085
+ .run(`retired-approval-dismissal:${id}`);
2086
+ }
2087
+
2004
2088
  resolveApproval(id: string, generation: number, state: "answered" | "cancelled", resolution?: ApprovalResolution): boolean {
2005
2089
  return this.db.transaction(() => {
2006
2090
  const approval = this.approval(id);
2007
2091
  if (!approval || approval.state !== "pending" || approval.generation !== generation) return false;
2008
2092
  const lane = this.lane(approval.target);
2009
- if (state === "answered" && lane && (lane.generation !== generation || lane.workState !== "open")) return false;
2010
- const correction = this.getMeta(`scope-correction-approval-input:${approval.id}`);
2011
- if (correction && state === "answered" && !this.reportApprovalSource(correction)) {
2012
- const response = resolution?.response;
2013
- const request = approval.request;
2014
- const denied = isDeepStrictEqual(response, { cancelled: true })
2015
- || request.method === "confirm" && isDeepStrictEqual(response, { confirmed: false })
2016
- || request.method === "select" && Array.isArray(request.options) && request.options.includes("Deny")
2017
- && isDeepStrictEqual(response, { value: "Deny" });
2018
- if (!denied || resolution?.headSelection) return false;
2019
- }
2093
+ if (state === "answered" && (this.getMeta(`native-approval-held:${id}`) !== null
2094
+ || lane && (lane.generation !== generation || lane.workState !== "open"))) return false;
2020
2095
  resolveDecision(this, approval, state, resolution);
2021
- const resolved = this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
2096
+ return this.db.query("UPDATE approvals SET state = ? WHERE id = ? AND generation = ? AND state = 'pending'")
2022
2097
  .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
2098
  }).immediate();
2030
2099
  }
2031
2100
 
@@ -2040,8 +2109,32 @@ export class Store implements StorePort {
2040
2109
  }
2041
2110
 
2042
2111
  recoverDeliveries(): void {
2043
- this.db.query("UPDATE outputs SET state = 'uncertain', error = ? WHERE state = 'sending'")
2044
- .run("Delivery interrupted before a durable receipt; reconcile before retrying.");
2112
+ this.db.transaction(() => {
2113
+ this.db.query("UPDATE outputs SET state = 'uncertain', error = ? WHERE state = 'sending'")
2114
+ .run("Delivery interrupted before a durable receipt; reconcile before retrying.");
2115
+ if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_effects'").get()) return;
2116
+ const retired = this.db.query<OutputRow, []>(`SELECT * FROM outputs WHERE state = 'uncertain' AND remote_id IS NULL
2117
+ AND (${retiredScopeId("id")} OR ${retiredScopeId("source_id")})`).all();
2118
+ const attempts = this.db.query<{ output: string; rejected: number }, [string]>(`SELECT
2119
+ json_extract(arguments, '$[0]') AS output,
2120
+ CASE WHEN state = 'complete' AND json_type(result, '$.ok') = 'false'
2121
+ AND json_extract(result, '$.certainty') = 'rejected' THEN 1 ELSE 0 END AS rejected
2122
+ FROM gateway_effects WHERE operation = 'send' AND json_extract(arguments, '$[0].id') = ? LIMIT 2`);
2123
+ for (const row of retired) {
2124
+ const recorded = attempts.all(row.id);
2125
+ const receipt = recorded.length === 1 ? recorded[0] : undefined;
2126
+ if (!receipt?.rejected) continue;
2127
+ const saved: unknown = JSON.parse(receipt.output);
2128
+ if (!saved || typeof saved !== "object" || !("error" in saved)) continue;
2129
+ const { error: _attemptError, ...attempt } = saved;
2130
+ const { error: _storedError, ...output } = toOutput(row);
2131
+ // Legacy sends used random Gateway effect IDs. Reconcile only one
2132
+ // terminal rejection with the same immutable send arguments.
2133
+ if (isDeepStrictEqual(attempt, { ...output, state: "sending" })) {
2134
+ this.finishOutput(row.id, "failed", undefined, "Gateway recorded definitive non-delivery");
2135
+ }
2136
+ }
2137
+ }).immediate();
2045
2138
  }
2046
2139
 
2047
2140
  getMeta(key: string): string | null {