omp-superagent 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/DESIGN.md +21 -14
  2. package/README.ko.md +33 -15
  3. package/README.md +35 -14
  4. package/THIRD_PARTY_NOTICES.md +3 -3
  5. package/config.example.json +2 -1
  6. package/docs/OPERATIONS.md +232 -74
  7. package/docs/design/execution.md +54 -10
  8. package/docs/design/messaging.md +177 -43
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.8.md +21 -0
  11. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  13. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  17. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  19. package/package.json +8 -8
  20. package/scripts/ci.ts +3 -3
  21. package/scripts/test-omp.sh +2 -1
  22. package/src/cli.ts +3 -0
  23. package/src/config.ts +5 -0
  24. package/src/contracts.ts +26 -5
  25. package/src/cron-jobs.ts +443 -19
  26. package/src/cron-pr-intake.ts +257 -0
  27. package/src/discord-markdown.ts +350 -123
  28. package/src/extension.ts +9 -1
  29. package/src/head-quota.ts +80 -0
  30. package/src/head-recovery.ts +40 -1
  31. package/src/host-extension.ts +120 -4
  32. package/src/host-protocol.ts +11 -0
  33. package/src/host-sdk-helper.ts +105 -10
  34. package/src/host.ts +111 -29
  35. package/src/installed-omp.ts +116 -4
  36. package/src/managed-ulw.ts +137 -24
  37. package/src/messenger-command-catalog.json +1 -1
  38. package/src/native-presets.ts +32 -5
  39. package/src/omp-usage.ts +254 -36
  40. package/src/pr-github.ts +4 -2
  41. package/src/pr-intake-automation.ts +316 -0
  42. package/src/pr-intake-comment.ts +226 -0
  43. package/src/pr-intake-fix.ts +233 -0
  44. package/src/pr-intake-github.ts +480 -0
  45. package/src/pr-intake-material.ts +230 -0
  46. package/src/pr-intake-mode.ts +59 -0
  47. package/src/pr-intake-review.ts +397 -0
  48. package/src/pr-intake-tree.ts +69 -0
  49. package/src/pr-intake-work.ts +29 -0
  50. package/src/runtime.ts +1504 -192
  51. package/src/store.ts +249 -49
  52. package/src/topic-history.ts +30 -17
package/src/store.ts CHANGED
@@ -24,7 +24,7 @@ import { existsSync, mkdirSync, realpathSync } from "node:fs";
24
24
  import { basename, dirname, join, resolve } from "node:path";
25
25
  import { isDeepStrictEqual } from "node:util";
26
26
  import {
27
- HEAD_MODEL_CONTROL, physicalRoute, physicalRouteKey, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
27
+ DEFERRED_ROUTING_META, HEAD_MODEL_CONTROL, physicalRoute, physicalRouteKey, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
28
28
  type ActiveInputState, type KickoffHold, type OutputRecord, type Route, type StorePort, type WorkflowActivation,
29
29
  type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect,
30
30
  } from "./contracts.ts";
@@ -37,6 +37,8 @@ import { laneWaitKey, type LaneReport } from "./lane-report";
37
37
  import { laneWatchReplySource } from "./lane-watch";
38
38
  import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "./topic-request";
39
39
  import type { CronUpdate } from "./cron-jobs";
40
+ import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "./pr-intake-work";
41
+ import type { ReviewRound } from "./pr-intake-review";
40
42
 
41
43
  const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
42
44
 
@@ -56,6 +58,8 @@ const SCHEMA = `
56
58
  CREATE INDEX IF NOT EXISTS inputs_active_order ON inputs(sequence) WHERE ${ACTIVE_INPUTS};
57
59
  CREATE INDEX IF NOT EXISTS inputs_target_active_order ON inputs(target, sequence) WHERE ${ACTIVE_INPUTS};
58
60
  CREATE INDEX IF NOT EXISTS inputs_state_active_order ON inputs(state, sequence) WHERE ${ACTIVE_INPUTS};
61
+ CREATE INDEX IF NOT EXISTS inputs_lane_run_order ON inputs(target, sequence)
62
+ WHERE request_id IS NOT NULL AND target <> 'main';
59
63
  CREATE INDEX IF NOT EXISTS inputs_message_id ON inputs(json_extract(data, '$.messageId'))
60
64
  WHERE json_type(data, '$.messageId') = 'text';
61
65
  CREATE TABLE IF NOT EXISTS lane_sources (
@@ -64,10 +68,11 @@ const SCHEMA = `
64
68
  );
65
69
  CREATE TABLE IF NOT EXISTS outputs (
66
70
  sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
67
- source_id TEXT NOT NULL, route TEXT NOT NULL, text TEXT NOT NULL,
71
+ source_id TEXT NOT NULL, route TEXT NOT NULL, physical_route TEXT, text TEXT NOT NULL,
68
72
  state TEXT NOT NULL DEFAULT 'pending'
69
73
  CHECK(state IN ('pending','sending','sent','uncertain','failed')),
70
- remote_id TEXT, error TEXT, reply_to TEXT, picker TEXT, result_attachment TEXT
74
+ remote_id TEXT, error TEXT, reply_to TEXT, picker TEXT, result_attachment TEXT, edit_of TEXT,
75
+ status INTEGER NOT NULL DEFAULT 0
71
76
  );
72
77
  CREATE INDEX IF NOT EXISTS outputs_queue ON outputs(state, sequence);
73
78
  CREATE INDEX IF NOT EXISTS outputs_sent_message ON outputs(remote_id) WHERE state = 'sent' AND remote_id IS NOT NULL;
@@ -104,6 +109,8 @@ interface OutputRow {
104
109
  reply_to: string | null;
105
110
  picker: string | null;
106
111
  result_attachment: string | null;
112
+ edit_of: string | null;
113
+ status: number;
107
114
  text: string;
108
115
  state: OutputRecord["state"];
109
116
  remote_id: string | null;
@@ -119,6 +126,8 @@ const toInput = (row: InputRow): InputRecord => {
119
126
  const toOutput = (row: OutputRow): OutputRecord => ({
120
127
  id: row.id, sourceId: row.source_id, route: JSON.parse(row.route) as Route,
121
128
  ...(row.reply_to === null ? {} : { replyTo: JSON.parse(row.reply_to) as NonNullable<OutputRecord["replyTo"]> }),
129
+ ...(row.edit_of === null ? {} : { editOf: JSON.parse(row.edit_of) as NonNullable<OutputRecord["editOf"]> }),
130
+ ...(row.status ? { status: true } : {}),
122
131
  ...(row.picker === null ? {} : { picker: JSON.parse(row.picker) as NonNullable<OutputRecord["picker"]> }),
123
132
  ...(row.result_attachment === null ? {} : { resultAttachment: JSON.parse(row.result_attachment) as NonNullable<OutputRecord["resultAttachment"]> }),
124
133
  text: row.text, state: row.state, remoteId: row.remote_id, error: row.error,
@@ -164,6 +173,21 @@ function inboundIdentity(input: Inbound) {
164
173
  }).sort((left, right) => left.id.localeCompare(right.id)),
165
174
  };
166
175
  }
176
+
177
+ /** Verify immutable inbound identity and return updated attachment URLs if refreshed, or null when unchanged. */
178
+ export function reconcileInboundRedelivery(existing: Inbound, incoming: Inbound): Inbound | null {
179
+ if (isDeepStrictEqual(inboundData(existing), inboundData(incoming))) return null;
180
+ if (!isDeepStrictEqual(inboundIdentity(existing), inboundIdentity(incoming))) {
181
+ throw new Error(`Inbound identity conflict: ${incoming.id}`);
182
+ }
183
+ const urls = new Map(incoming.attachments.map(file => [file.id, file.url]));
184
+ const attachments = existing.attachments.map(file => {
185
+ const url = urls.get(file.id)!;
186
+ return file.url === url ? file : { ...file, url };
187
+ });
188
+ if (!attachments.some((file, index) => file !== existing.attachments[index])) return null;
189
+ return { ...existing, attachments };
190
+ }
167
191
  const approvalIdentity = (approval: Approval) => ({
168
192
  id: approval.id, target: approval.target, generation: approval.generation,
169
193
  requestId: approval.requestId, route: approval.route, request: approval.request,
@@ -203,6 +227,17 @@ export class Store implements StorePort {
203
227
  if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
204
228
  if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
205
229
  if (!outputColumns.some(column => column.name === "result_attachment")) db.run("ALTER TABLE outputs ADD COLUMN result_attachment TEXT");
230
+ if (!outputColumns.some(column => column.name === "edit_of")) db.run("ALTER TABLE outputs ADD COLUMN edit_of TEXT");
231
+ if (!outputColumns.some(column => column.name === "status")) db.run("ALTER TABLE outputs ADD COLUMN status INTEGER NOT NULL DEFAULT 0");
232
+ if (!outputColumns.some(column => column.name === "physical_route")) db.run("ALTER TABLE outputs ADD COLUMN physical_route TEXT");
233
+ db.run("CREATE INDEX IF NOT EXISTS outputs_route_queue ON outputs(state, physical_route, sequence)");
234
+ const missingPhysical = db.query<{ id: string; route: string }, []>("SELECT id, route FROM outputs WHERE physical_route IS NULL").all();
235
+ if (missingPhysical.length) {
236
+ const update = db.query("UPDATE outputs SET physical_route = ? WHERE id = ?");
237
+ db.transaction(() => {
238
+ for (const row of missingPhysical) update.run(physicalRouteKey(JSON.parse(row.route) as Route), row.id);
239
+ })();
240
+ }
206
241
  this.db = db;
207
242
  this.writerLock = lock;
208
243
  } catch (error) {
@@ -227,26 +262,43 @@ export class Store implements StorePort {
227
262
  || (input.messageId === null ? input.interactionId === undefined && !slackInvocation : typeof input.messageId !== "string" || !input.messageId.length)) {
228
263
  throw new Error("Inbound event requires a real message ID, Discord interaction snowflake, scoped Slack invocation, or valid picker selection");
229
264
  }
265
+ return this.insertInput(input, target, metadata, workflow);
266
+ }
267
+
268
+ receivePrWork(input: Inbound, target: string | null, r: ReviewRound): boolean {
269
+ const parent = { ...input.route, threadId: null };
270
+ const offer = this.output(`cron-pr:offer:${r.repository}:${r.number}`);
271
+ if (!r.automation || input.route.platform !== "discord" || !input.route.guildId || input.route.topicId !== undefined
272
+ || input.messageId !== null || input.interactionId !== undefined || input.invocationId !== undefined
273
+ || input.pickerSelection || input.attachments.length || input.discordOriginalText !== undefined || input.reply
274
+ || this.getMeta(`user-source:${input.id}`) !== null || r.automation.anchor !== input.route.threadId
275
+ || r.source !== intakeWorkId(r.job, r.number, r.automation.revision, r.head)
276
+ || !offer || offer.state !== "sent" || offer.remoteId !== r.automation.anchor || routeKey(offer.route) !== routeKey(parent)
277
+ || this.getMeta(intakeThreadKey(r.job, r.number)) !== r.automation.anchor)
278
+ throw new Error("Static PR work requires the exact noninteractive receipt and confirmed bot starter.");
279
+ const scope = `pr-review:${r.job}:${r.number}`;
280
+ if (input.id === r.source && target === null)
281
+ return this.insertInput(input, target, { [scope]: JSON.stringify(r), [`pr-review-lane:${r.laneId}`]: scope,
282
+ [`topic-owner:${r.source}`]: r.laneId }, null);
283
+ const source = this.input(r.source);
284
+ if (input.id !== r.inputId || (target !== null && target !== r.laneId) || source?.target !== null
285
+ || source.state !== "pending" || routeKey(source.route) !== routeKey(input.route)
286
+ || this.getMeta(scope) !== JSON.stringify(r) || this.getMeta(`pr-review-lane:${r.laneId}`) !== scope)
287
+ throw new Error("Static PR lane handoff does not match its registered controller receipt.");
288
+ return this.insertInput(input, target, { [`handoff-source:${input.id}`]: r.source }, null);
289
+ }
290
+
291
+ private insertInput(input: Inbound, target: string | null, metadata: Readonly<Record<string, string>>, workflow: WorkflowActivation | null): boolean {
230
292
  return this.db.transaction(() => {
231
293
  const existing = this.input(input.id);
232
294
  if (existing) {
233
295
  if (!isDeepStrictEqual(existing.workflow, workflow)) throw new Error(`Workflow identity conflict: ${input.id}`);
234
- if (isDeepStrictEqual(inboundData(existing), inboundData(input))) return false;
235
- if (!isDeepStrictEqual(inboundIdentity(existing), inboundIdentity(input))) {
236
- throw new Error(`Inbound identity conflict: ${input.id}`);
237
- }
238
- if (existing.state === "pending") {
239
- const urls = new Map(input.attachments.map(file => [file.id, file.url]));
240
- const attachments = existing.attachments.map(file => {
241
- const url = urls.get(file.id)!;
242
- return file.url === url ? file : { ...file, url };
243
- });
244
- if (attachments.some((file, index) => file !== existing.attachments[index])) {
245
- // Refresh only URLs. In particular, do not rewrite the original
246
- // activation in a pre-rename input as a side effect of redelivery.
247
- this.db.query("UPDATE inputs SET data = json_set(data, '$.attachments', json(?)) WHERE id = ? AND state = 'pending'")
248
- .run(JSON.stringify(attachments), input.id);
249
- }
296
+ const refreshed = reconcileInboundRedelivery(existing, input);
297
+ if (existing.state === "pending" && refreshed) {
298
+ // Refresh only URLs. In particular, do not rewrite the original
299
+ // activation in a pre-rename input as a side effect of redelivery.
300
+ this.db.query("UPDATE inputs SET data = json_set(data, '$.attachments', json(?)) WHERE id = ? AND state = 'pending'")
301
+ .run(JSON.stringify(refreshed.attachments), input.id);
250
302
  }
251
303
  return false; // A replay never changes its current assignment or state.
252
304
  }
@@ -343,14 +395,21 @@ export class Store implements StorePort {
343
395
  hasPendingTopicChoice(input: InputRecord, deadline: number): boolean {
344
396
  const { platform, accountId, authorityId, guildId, channelId, threadId } = input.route;
345
397
  if (platform !== "discord" || guildId === null || threadId === null) return false;
398
+ // An input already ACKed to Gateway but still awaiting deferred topic routing
399
+ // has no head receipt yet either; it fences the choice like a pending ledger row.
400
+ const deferred = (JSON.parse(this.getMeta(DEFERRED_ROUTING_META) ?? "[]") as Inbound[]).filter(item => !item.pickerSelection
401
+ && (typeof item.messageId === "string" || typeof item.interactionId === "string")
402
+ && Number.isSafeInteger(item.receivedAt) && item.receivedAt >= input.receivedAt && item.receivedAt <= deadline
403
+ && item.id !== input.id && physicalRouteKey(item.route) === physicalRouteKey(input.route))
404
+ .map(item => ({ id: item.id, text: item.text, messageId: item.messageId, replyId: item.reply?.messageId ?? null, authoredAt: item.receivedAt }));
346
405
  // Gateway creates the shared ingress ledger; standalone Store use has none.
347
- if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get()) return false;
406
+ const ledger = this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get() !== null;
348
407
  const questionId = `${input.id}:workspace`;
349
408
  const choices: readonly { readonly cwd: string }[] = JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]");
350
409
  // The Gateway pending index skips delivered history, including terminal rejections.
351
410
  // Unresolved rows stay pending. The durable insert, not its wall-clock timestamp,
352
411
  // fences a timely-authored choice even when transport-delayed.
353
- const rows = this.db.query<{
412
+ const rows = ledger ? this.db.query<{
354
413
  readonly id: string; readonly text: string; readonly messageId: string | null;
355
414
  readonly replyId: string | null; readonly authoredAt: number;
356
415
  }, [number, number, string, string, string, string, string, string, string]>(`
@@ -373,8 +432,9 @@ export class Store implements StorePort {
373
432
  AND json_extract(data, '$.input.route.guildId') = ?
374
433
  AND json_extract(data, '$.input.route.channelId') = ?
375
434
  AND json_extract(data, '$.input.route.threadId') = ?
376
- `).iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId);
377
- for (const row of rows) {
435
+ `) : null;
436
+ const pending = rows?.iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId) ?? [];
437
+ for (const row of [...deferred, ...pending]) {
378
438
  if (row.messageId !== null && row.id.startsWith(`discord:${accountId}:${row.messageId}:edit:`)) continue;
379
439
  const questionReply = row.replyId !== null && this.sentOutputForMessage(input.route, row.replyId)?.id === questionId;
380
440
  const scopedReply = questionReply || row.replyId !== null && row.replyId === input.messageId;
@@ -428,6 +488,42 @@ export class Store implements StorePort {
428
488
  return this.db.query("SELECT 1 FROM inputs WHERE target = ? AND state = ? LIMIT 1").get(target, state) !== null;
429
489
  }
430
490
 
491
+ latestLaneRun(target: string): InputRecord | null {
492
+ const admitted = this.getMeta(`lane-latest-run:${target}`);
493
+ if (admitted) return this.input(admitted);
494
+ // Exclude joined inputs because they have no separate answer. A legacy
495
+ // goal resume could overtake an older queued input in the same generation.
496
+ const row = this.db.query<InputRow, [string]>(`SELECT latest.* FROM (SELECT inputs.* FROM inputs
497
+ LEFT JOIN metadata ON metadata.key = 'steering-owner:' || inputs.id
498
+ WHERE inputs.target = ? AND inputs.target <> 'main' AND inputs.request_id IS NOT NULL
499
+ AND (metadata.value IS NULL OR metadata.value = inputs.id)
500
+ ORDER BY inputs.sequence DESC LIMIT 1) AS latest
501
+ WHERE latest.id NOT LIKE 'resume:%' OR NOT EXISTS (
502
+ SELECT 1 FROM inputs AS earlier WHERE earlier.target = latest.target
503
+ AND earlier.generation = latest.generation AND earlier.request_id IS NOT NULL
504
+ AND earlier.sequence < latest.sequence)`).get(target);
505
+ return row ? toInput(row) : null;
506
+ }
507
+
508
+ hasPendingLaneResult(target: string): boolean {
509
+ return this.db.query(`SELECT 1 FROM inputs AS run
510
+ LEFT JOIN inputs AS report ON report.id = 'report:' || run.id
511
+ LEFT JOIN inputs AS recovered ON recovered.id = 'report:' || run.id || ':done'
512
+ LEFT JOIN outputs AS answer ON answer.id = COALESCE(recovered.id, report.id, run.id) || ':answer'
513
+ LEFT JOIN outputs AS final ON final.id = COALESCE(recovered.id, report.id, run.id) || ':answer:done'
514
+ WHERE run.target = ? AND run.target <> 'main' AND run.request_id IS NOT NULL AND run.state = 'done'
515
+ AND (COALESCE(recovered.state, report.state) IN ('pending','submitted','uncertain')
516
+ OR COALESCE(final.state, answer.state) IN ('pending','sending','uncertain'))
517
+ LIMIT 1`).get(target) !== null;
518
+ }
519
+
520
+ hasPendingLanePlacement(target: string): boolean {
521
+ return this.db.query(`SELECT 1 FROM inputs
522
+ JOIN metadata ON metadata.key = 'topic-owner:' || inputs.id
523
+ WHERE inputs.target IS NULL AND inputs.state IN ('pending','uncertain') AND metadata.value = ?
524
+ LIMIT 1`).get(target) !== null;
525
+ }
526
+
431
527
  hasHeadRecoveryInput(): boolean {
432
528
  return this.db.query(`SELECT 1 FROM inputs
433
529
  JOIN metadata ON metadata.key = 'head-native-owner:' || inputs.id AND metadata.value <> ''
@@ -480,7 +576,9 @@ export class Store implements StorePort {
480
576
  const rows = this.db.query<OutputRow, [string, string | null]>(
481
577
  "SELECT * FROM outputs WHERE (state = 'sent' AND remote_id = ?) OR id = ?",
482
578
  ).all(messageId, part);
483
- return rows.map(toOutput).filter(output => physicalRouteKey(output.route) === physicalRouteKey(route));
579
+ // An in-place status edit shares its message with the output that created it.
580
+ return rows.map(toOutput).filter(output => physicalRouteKey(output.route) === physicalRouteKey(route)
581
+ && output.editOf?.messageId !== messageId);
484
582
  }
485
583
 
486
584
  repliedParentTopic(route: Route, messageId: string): Lane | "unverified" | null {
@@ -624,8 +722,26 @@ export class Store implements StorePort {
624
722
  if (!Number.isSafeInteger(generation) || generation < 0) throw new Error("Invalid generation");
625
723
  const lane = this.lane(input.target);
626
724
  if (lane && (lane.generation !== generation || lane.workState !== "open")) return false;
627
- return this.db.query(`UPDATE inputs SET state = 'submitted', request_id = ?, generation = ?
725
+ const submitted = this.db.query(`UPDATE inputs SET state = 'submitted', request_id = ?, generation = ?
628
726
  WHERE id = ? AND state = 'pending'`).run(requestId, generation, id).changes === 1;
727
+ const ownerId = submitted && lane ? this.getMeta(`steering-owner:${id}`) : null;
728
+ if (ownerId && ownerId !== id) {
729
+ const topic = this.topicDelivery(id);
730
+ if (topic && !this.topicDelivery(ownerId)) {
731
+ const owner = this.input(ownerId);
732
+ const source = owner && this.ownerSource(owner.id);
733
+ if (!owner || !source || owner.state !== "submitted" || owner.target !== input.target || owner.generation !== generation
734
+ || routeKey(owner.route) !== routeKey(input.route) || routeKey(this.laneReplyRoute(owner, source)) !== routeKey(topic.route)) {
735
+ throw new Error(`Steering reply route differs from the current lane run: ${id}`);
736
+ }
737
+ // A later lane_start of the manager source must not redirect this cohort.
738
+ this.setMeta(`steering-topic-reply:${owner.id}`, JSON.stringify(topic.route));
739
+ }
740
+ }
741
+ if (submitted && lane?.route.platform === "discord" && lane.route.guildId && lane.route.threadId) {
742
+ if (ownerId === null || ownerId === id) this.setMeta(`lane-latest-run:${lane.id}`, id);
743
+ }
744
+ return submitted;
629
745
  }).immediate();
630
746
  }
631
747
 
@@ -645,19 +761,50 @@ export class Store implements StorePort {
645
761
  return !!lane && lane.workState === "open" && lane.generation === context.generation && lane.sessionId === context.sessionId;
646
762
  }
647
763
 
648
- progress(id: string, generation: number, sessionId: string, eventId: string, text: string): boolean {
764
+ private progressStream(id: string): string {
765
+ let current = id;
766
+ const seen = new Set<string>([current]);
767
+ while (true) {
768
+ const parent = this.getMeta(`progress-source:${current}`);
769
+ if (!parent) return current;
770
+ const { inputId } = JSON.parse(parent) as { inputId: string };
771
+ if (seen.has(inputId)) return current;
772
+ seen.add(inputId);
773
+ current = inputId;
774
+ }
775
+ }
776
+
777
+ /**
778
+ * When opted in on Discord (`editInPlace`), nonterminal progress uses one
779
+ * `⏳` status message edited in place. Each update stays its own immutable
780
+ * output; `claimOutput` decides whether it edits that message. By default (or
781
+ * on other platforms), every update posts as an ordinary new message.
782
+ */
783
+ private queueStatus(
784
+ output: Pick<OutputRecord, "id" | "sourceId" | "route" | "text">,
785
+ stream: string,
786
+ editInPlace = false,
787
+ ): boolean {
788
+ if (!editInPlace || output.route.platform !== "discord") return this.queueOutput(output);
789
+ this.setMeta(`status-stream:${output.id}`, stream);
790
+ const text = /^(?:`{3,}|~{3,})/.test(output.text.trimStart()) ? `⏳\n${output.text}` : `⏳ ${output.text}`;
791
+ return this.queueOutput({ ...output, text, status: true });
792
+ }
793
+
794
+ progress(id: string, generation: number, sessionId: string, eventId: string, text: string, editInPlace = false): boolean {
649
795
  if (!text.trim()) return false;
650
796
  return this.db.transaction(() => {
651
797
  const context = { inputId: id, generation, sessionId };
652
798
  if (!this.progressOpen(context)) return false;
653
799
  const input = this.requireInput(id);
800
+ if (unattendedSource(this, input)) return false; // Static review has one final answer, not a HEAD progress prompt.
654
801
  const receiptId = `progress:${id}:${eventId}`;
655
802
  const seen = `progress-seen:${receiptId}`;
656
803
  if (this.getMeta(seen)) return false;
657
804
  this.setMeta(seen, "true");
658
805
  if (input.target === "main") {
659
806
  this.setMeta(`progress-output:${receiptId}`, JSON.stringify(context));
660
- return this.queueOutput({ id: receiptId, sourceId: id, route: input.route, text });
807
+ return this.queueStatus({ id: receiptId, sourceId: id, route: input.route, text }, this.progressStream(id), editInPlace);
661
808
  }
662
809
  const topic = this.topicDelivery(id);
663
810
  if (topic) {
@@ -668,7 +815,7 @@ export class Store implements StorePort {
668
815
  .run("Nonterminal progress superseded", previous);
669
816
  this.setMeta(pendingKey, receiptId);
670
817
  this.setMeta(`progress-output:${receiptId}`, JSON.stringify(context));
671
- return this.queueOutput({ id: receiptId, sourceId: topic.outputSourceId, route: topic.route, text });
818
+ return this.queueStatus({ id: receiptId, sourceId: topic.outputSourceId, route: topic.route, text }, id, editInPlace);
672
819
  }
673
820
  const lane = this.requireLane(input.target!);
674
821
  const sourceId = this.getMeta(`handoff-source:${id}`);
@@ -677,7 +824,7 @@ export class Store implements StorePort {
677
824
  const previous = this.getMeta(pendingKey);
678
825
  if (previous) this.db.query("UPDATE inputs SET state = 'cancelled' WHERE id = ? AND state = 'pending'").run(previous);
679
826
  this.receive({
680
- id: receiptId, route: this.deliveryRoute(source), messageId: source.messageId,
827
+ id: receiptId, route: this.laneReplyRoute(input, source), messageId: source.messageId,
681
828
  receivedAt: source.receivedAt, attachments: [],
682
829
  ...(source.interactionId === undefined ? {} : { interactionId: source.interactionId }),
683
830
  ...(source.invocationId === undefined ? {} : { invocationId: source.invocationId }),
@@ -778,7 +925,7 @@ export class Store implements StorePort {
778
925
  }).immediate();
779
926
  }
780
927
 
781
- settle(id: string, state: "done" | "uncertain" | "cancelled", output?: Pick<OutputRecord, "id" | "text" | "picker">, headModel?: HeadModelChange): boolean {
928
+ settle(id: string, state: "done" | "uncertain" | "cancelled", output?: Pick<OutputRecord, "id" | "text" | "picker">, headModel?: HeadModelChange, editInPlace = false): boolean {
782
929
  return this.db.transaction(() => {
783
930
  const input = this.input(id);
784
931
  if (!input || input.state === "done" || input.state === "cancelled" || input.state === state) return false;
@@ -787,8 +934,12 @@ export class Store implements StorePort {
787
934
  const progress = this.getMeta(`progress-source:${id}`);
788
935
  if (progress && !this.progressOpen(JSON.parse(progress))) output = undefined;
789
936
  // An uncertain request can only be resolved explicitly, never resubmitted.
790
- const topic = output && this.topicDelivery(id);
791
- if (output && topic) {
937
+ const reviewSource = unattendedSource(this, input);
938
+ const topic = output && !reviewSource && this.topicDelivery(id);
939
+ if (reviewSource) {
940
+ if (output?.text.trim() && hasIntakeReplyRoute(this, input, reviewSource))
941
+ this.queueOutput({ ...output, sourceId: input.id, route: input.route });
942
+ } else if (output && topic) {
792
943
  if (output.text.trim() && (topic.source.id === id
793
944
  || topic.source.state !== "cancelled" && topic.source.state !== "uncertain")) {
794
945
  this.queueOutput({
@@ -804,7 +955,7 @@ export class Store implements StorePort {
804
955
  const receiptId = input.state === "uncertain" ? `${reportId}:${state}` : reportId;
805
956
  this.receive({
806
957
  id: receiptId,
807
- route: this.deliveryRoute(source), messageId: source.messageId, receivedAt: source.receivedAt, attachments: [],
958
+ route: this.laneReplyRoute(input, source), messageId: source.messageId, receivedAt: source.receivedAt, attachments: [],
808
959
  ...(source.interactionId === undefined ? {} : { interactionId: source.interactionId }),
809
960
  ...(source.invocationId === undefined ? {} : { invocationId: source.invocationId }),
810
961
  text: [
@@ -816,8 +967,16 @@ export class Store implements StorePort {
816
967
  ].join("\n\n"),
817
968
  }, "main", { [`activity-source:${receiptId}`]: source.id });
818
969
  } else if (output) {
819
- if (progress) this.setMeta(`progress-output:${output.id}`, progress);
820
- this.queueOutput({ ...output, sourceId: id, route: input.route });
970
+ if (progress) {
971
+ this.setMeta(`progress-output:${output.id}`, progress);
972
+ if (!output.picker) {
973
+ this.queueStatus({ ...output, sourceId: id, route: input.route }, this.progressStream(id), editInPlace);
974
+ } else {
975
+ this.queueOutput({ ...output, sourceId: id, route: input.route });
976
+ }
977
+ } else {
978
+ this.queueOutput({ ...output, sourceId: id, route: input.route });
979
+ }
821
980
  }
822
981
  this.db.query("UPDATE inputs SET state = ? WHERE id = ?").run(state, id);
823
982
  if (headModel && state === "done" && input.state === "submitted" && input.target === "main") {
@@ -934,6 +1093,11 @@ export class Store implements StorePort {
934
1093
  }).immediate();
935
1094
  }
936
1095
 
1096
+ laneReplyRoute(input: InputRecord, source: InputRecord): Route {
1097
+ const pinned = this.getMeta(`steering-topic-reply:${input.id}`);
1098
+ return pinned ? JSON.parse(pinned) : this.deliveryRoute(source);
1099
+ }
1100
+
937
1101
  private deliveryRoute(source: InputRecord, expectedLane?: string | null): Route {
938
1102
  const stored = this.getMeta(`head-delivery:${source.id}`);
939
1103
  if (!stored) return source.route;
@@ -948,12 +1112,16 @@ export class Store implements StorePort {
948
1112
  return decision.destination;
949
1113
  }
950
1114
 
951
- queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error">): boolean {
1115
+ queueOutput(output: Omit<OutputRecord, "state" | "remoteId" | "error" | "editOf">): boolean {
1116
+ if (output.status && (output.route.platform !== "discord" || output.picker || output.resultAttachment)) {
1117
+ throw new Error(`Status delivery requires a plain Discord message: ${output.id}`);
1118
+ }
952
1119
  return this.db.transaction(() => {
953
1120
  const existing = this.output(output.id);
954
1121
  if (existing) {
955
1122
  if (existing.sourceId !== output.sourceId || routeKey(existing.route) !== routeKey(output.route)
956
- || existing.text !== output.text || !isDeepStrictEqual(existing.picker, output.picker)
1123
+ || existing.text !== output.text || Boolean(existing.status) !== Boolean(output.status)
1124
+ || !isDeepStrictEqual(existing.picker, output.picker)
957
1125
  || !isDeepStrictEqual(existing.resultAttachment, output.resultAttachment)
958
1126
  || output.replyTo !== undefined && (!existing.replyTo
959
1127
  || existing.replyTo.messageId !== output.replyTo.messageId
@@ -995,13 +1163,17 @@ export class Store implements StorePort {
995
1163
  || physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
996
1164
  throw new Error(`Output reply differs from its source: ${output.id}`);
997
1165
  }
998
- return this.db.query("INSERT INTO outputs(id, source_id, route, text, reply_to, picker, result_attachment) VALUES (?, ?, ?, ?, ?, ?, ?)")
999
- .run(output.id, output.sourceId, JSON.stringify(output.route), output.text, replyTo ? JSON.stringify(replyTo) : null,
1000
- output.picker ? JSON.stringify(output.picker) : null, attachment ? JSON.stringify(attachment) : null).changes === 1;
1166
+ return this.db.query("INSERT INTO outputs(id, source_id, route, physical_route, text, reply_to, picker, result_attachment, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
1167
+ .run(output.id, output.sourceId, JSON.stringify(output.route), physicalRouteKey(output.route), output.text, replyTo ? JSON.stringify(replyTo) : null,
1168
+ output.picker ? JSON.stringify(output.picker) : null, attachment ? JSON.stringify(attachment) : null, output.status ? 1 : 0).changes === 1;
1001
1169
  }).immediate();
1002
1170
  }
1003
1171
 
1004
- outputs(): OutputRecord[] {
1172
+ outputs(physicalRoute?: string): OutputRecord[] {
1173
+ if (physicalRoute !== undefined) {
1174
+ return (this.db.query("SELECT * FROM outputs WHERE state = 'pending' AND physical_route = ? ORDER BY sequence")
1175
+ .all(physicalRoute) as OutputRow[]).map(toOutput);
1176
+ }
1005
1177
  return (this.db.query("SELECT * FROM outputs WHERE state = 'pending' ORDER BY sequence")
1006
1178
  .all() as OutputRow[]).map(toOutput);
1007
1179
  }
@@ -1013,14 +1185,30 @@ export class Store implements StorePort {
1013
1185
  (inputs.target IS NULL OR inputs.target = 'main') LIMIT 1`).get() !== null;
1014
1186
  }
1015
1187
 
1016
- claimOutput(id: string): boolean {
1017
- const progress = this.getMeta(`progress-output:${id}`);
1018
- if (progress && !this.progressOpen(JSON.parse(progress))) {
1019
- this.db.query("UPDATE outputs SET state = 'failed', error = 'Nonterminal progress superseded or no longer authorized' WHERE id = ? AND state = 'pending'").run(id);
1020
- return false;
1021
- }
1022
- return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'")
1023
- .run(id).changes === 1;
1188
+ /**
1189
+ * A Discord status update edits the stream's message only after that message's
1190
+ * creation was confirmed. The edit target is persisted with the claim, so a
1191
+ * redelivery of this output keeps the same physical message.
1192
+ */
1193
+ claimOutput(id: string, editInPlace = false): boolean {
1194
+ return this.db.transaction(() => {
1195
+ const progress = this.getMeta(`progress-output:${id}`);
1196
+ if (progress && !this.progressOpen(JSON.parse(progress))) {
1197
+ this.db.query("UPDATE outputs SET state = 'failed', error = 'Nonterminal progress superseded or no longer authorized' WHERE id = ? AND state = 'pending'").run(id);
1198
+ return false;
1199
+ }
1200
+ const output = this.output(id);
1201
+ if (output?.state !== "pending") return false;
1202
+ const stream = editInPlace ? this.getMeta(`status-stream:${id}`) : null;
1203
+ const anchorId = stream && !output.editOf ? this.getMeta(`status-anchor:${stream}`) : null;
1204
+ const anchor = anchorId ? this.output(anchorId) : null;
1205
+ if (anchor?.state === "sent" && anchor.remoteId && physicalRouteKey(anchor.route) === physicalRouteKey(output.route)) {
1206
+ this.db.query("UPDATE outputs SET edit_of = ? WHERE id = ?")
1207
+ .run(JSON.stringify({ route: physicalRoute(output.route), messageId: anchor.remoteId }), id);
1208
+ }
1209
+ return this.db.query("UPDATE outputs SET state = 'sending' WHERE id = ? AND state = 'pending'")
1210
+ .run(id).changes === 1;
1211
+ }).immediate();
1024
1212
  }
1025
1213
 
1026
1214
  finishOutput(id: string, state: "sent" | "uncertain" | "failed" | "pending", remoteId?: string, error?: string): void {
@@ -1041,6 +1229,18 @@ export class Store implements StorePort {
1041
1229
  }
1042
1230
  this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
1043
1231
  .run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
1232
+ const stream = this.getMeta(`status-stream:${id}`);
1233
+ if (stream) {
1234
+ const anchorKey = `status-anchor:${stream}`;
1235
+ const anchor = this.getMeta(anchorKey);
1236
+ // Only a confirmed new post becomes the message later updates edit;
1237
+ // an uncertain post never does. A rejected edit (for example, the
1238
+ // owner deleted the message) releases it so the next update posts anew.
1239
+ if (state === "sent" && !output.editOf && !anchor) this.setMeta(anchorKey, id);
1240
+ if (state === "failed" && output.editOf && anchor && this.output(anchor)?.remoteId === output.editOf.messageId) {
1241
+ this.db.query("DELETE FROM metadata WHERE key = ?").run(anchorKey);
1242
+ }
1243
+ }
1044
1244
  // Start the owner's response window with the durable question receipt,
1045
1245
  // never with input admission or an unconfirmed send attempt.
1046
1246
  if (state === "sent" && id === `${output.sourceId}:workspace`
@@ -346,23 +346,35 @@ function promptText(content: unknown): string {
346
346
  return text;
347
347
  }
348
348
 
349
+ export const joinedTopicProvenance = "Input provenance: bound owner topic reply.";
350
+
349
351
  /** OMP journals the RPC completion ID; the fenced request identifies its input. */
350
352
  function journalRequest(raw: string, lane: Lane) {
351
- const headers = [...raw.matchAll(/^(`{3,})superagent-runtime-context\nRequest ID: ([^\r\n]{1,512})\n/gm)]
352
- .sort((a, b) => b[1].length - a[1].length);
353
+ const headers = [...raw.matchAll(/^(`{3,})superagent-runtime-context\nRequest ID: ([^\r\n]{1,512})\n/gm)];
354
+ if (!headers.length) return;
355
+ // Ordinary prompts start with the controller header. Pasted task text after
356
+ // its closing fence cannot replace it or make it ambiguous.
357
+ const leading = headers[0]?.index === 0;
358
+ if (!leading) headers.sort((a, b) => b[1].length - a[1].length);
353
359
  const header = headers[0];
354
- if (!header || headers[1]?.[1].length === header[1].length) return;
355
- const scope = raw.slice(header.index + header[0].length, header.index + header[0].length + 4096).split("\n", 12);
356
- if (scope.includes(`Independent lane ${lane.id}; cwd: ${lane.cwd}`)) {
357
- // Same request identity used by runtime's prompt submission, excluding generation.
358
- const inputId = header[2];
359
- const closing = `\n${header[1]}`;
360
- const manager = scope.includes("Delivery mode: manager handoff.");
361
- const fencedManager = manager && header.index === 0 && raw.endsWith(closing)
362
- && !raw.slice(header[0].length, -closing.length).includes(header[1]);
363
- const topicReply = scope.includes("Delivery mode: topic reply.");
364
- return { inputId, digest: createHash("sha256").update(inputId).digest("hex").slice(0, 24), manager, fencedManager, topicReply };
365
- }
360
+ if (!header || !leading && headers[1]?.[1].length === header[1].length) return false;
361
+ const body = raw.slice(header.index + header[0].length);
362
+ const closing = `\n${header[1]}`;
363
+ const closeBeforeText = body.indexOf(`${closing}\n`);
364
+ const end = closeBeforeText >= 0 ? closeBeforeText : body.endsWith(closing) ? body.length - closing.length : -1;
365
+ if (end < 0) return false;
366
+ const scope = body.slice(0, Math.min(end, 4096)).split("\n", 12);
367
+ const laneIndex = scope.indexOf(`Independent lane ${lane.id}; cwd: ${lane.cwd}`);
368
+ if (laneIndex < 0) return false;
369
+ // Same request identity used by runtime's prompt submission, excluding generation.
370
+ const inputId = header[2];
371
+ const delivery = scope[laneIndex + 1];
372
+ const manager = delivery === "Delivery mode: manager handoff.";
373
+ const topicReply = delivery === "Delivery mode: topic reply.";
374
+ if (!manager && !topicReply) return false;
375
+ const fencedManager = manager && leading && closeBeforeText < 0 && !body.slice(0, end).includes(header[1]);
376
+ const joinedTopic = manager && scope[laneIndex + 2] === joinedTopicProvenance && scope[laneIndex + 3]?.startsWith("Brief: ");
377
+ return { inputId, digest: createHash("sha256").update(inputId).digest("hex").slice(0, 24), manager, fencedManager, topicReply, joinedTopic };
366
378
  }
367
379
 
368
380
  function journalReceipt(data: unknown, lane: Lane) {
@@ -461,7 +473,7 @@ type TopicQuery = {
461
473
  type TopicSelection = { readonly anchors: ReadonlySet<string> } | { readonly entryId: string };
462
474
  type JournalQuery = TopicQuery & { readonly selection: TopicSelection };
463
475
  /** Resolve durable owner prose only after verifying its route and the exact completion. */
464
- type OwnerOpening = (lane: Lane, inputId: string, mode: "manager" | "topic",
476
+ type OwnerOpening = (lane: Lane, inputId: string, mode: "manager" | "topic" | "joined-topic",
465
477
  hasCompletion: (requestId: string) => boolean) => Promise<{ readonly text: string; readonly requestId: string } | null>;
466
478
 
467
479
  function topicQuery(text: string, receivedAt: number): TopicQuery | null {
@@ -502,13 +514,14 @@ async function matchJournal(entries: readonly SessionEntry[], lane: Lane, query:
502
514
  if (user.synthetic === true || user.parentIrc || user.attribution === "agent") continue;
503
515
  const raw = promptText(user.content);
504
516
  const request = journalRequest(raw, lane);
517
+ if (request === false) continue;
505
518
  // A manager fence can contain generated instructions and quotes. Use
506
519
  // only the independent original source, never the fenced task bytes.
507
520
  // Telegram's formatting entities are not recoverable from native text.
508
521
  // Workflow envelopes may put raw instructions before or after the fence;
509
522
  // recognizing manager delivery must not depend on the entire turn being fenced.
510
- if (request?.manager && !request.fencedManager) continue;
511
- const mode = request?.manager ? "manager" : lane.route.platform === "telegram" ? "topic" : null;
523
+ if (request?.manager && !request.fencedManager && !request.joinedTopic) continue;
524
+ const mode = request?.joinedTopic ? "joined-topic" : request?.manager ? "manager" : lane.route.platform === "telegram" ? "topic" : null;
512
525
  let ownerText: string;
513
526
  let ownerRequestId: string | undefined;
514
527
  if (mode !== null) {