omp-superagent 0.1.5 → 0.1.6

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 (57) hide show
  1. package/DESIGN.md +62 -8
  2. package/README.ko.md +22 -14
  3. package/README.md +36 -22
  4. package/config.example.json +1 -0
  5. package/docs/OPERATIONS.md +180 -42
  6. package/docs/design/execution.md +20 -7
  7. package/docs/design/messaging.md +131 -11
  8. package/docs/releases/0.1.6.md +21 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +7 -2
  19. package/skills/head/references/model-selection.md +4 -4
  20. package/skills/head/references/routing.md +9 -4
  21. package/skills/head/references/supervision.md +4 -3
  22. package/skills/lane/SKILL.md +19 -13
  23. package/skills/lane/references/workflow.md +19 -11
  24. package/src/board.ts +7 -2
  25. package/src/cli.ts +22 -6
  26. package/src/config.ts +26 -3
  27. package/src/contracts.ts +20 -2
  28. package/src/decision-tool.ts +1 -1
  29. package/src/extension.ts +40 -2
  30. package/src/gateway-client.ts +22 -1
  31. package/src/gateway-config.ts +4 -4
  32. package/src/gateway-restart-env.ts +7 -2
  33. package/src/gateway-wire.ts +8 -0
  34. package/src/group-access.ts +222 -0
  35. package/src/group-policy.ts +117 -0
  36. package/src/group-runner-extension.ts +153 -0
  37. package/src/group-runner.ts +284 -0
  38. package/src/head-rotation.ts +88 -0
  39. package/src/host-extension.ts +52 -3
  40. package/src/host-protocol.ts +1 -0
  41. package/src/host-sdk-helper.ts +7 -0
  42. package/src/host-superkit.ts +26 -0
  43. package/src/host.ts +5 -1
  44. package/src/lane-extension.ts +6 -3
  45. package/src/managed-memory-helper.ts +22 -0
  46. package/src/managed-memory.ts +100 -0
  47. package/src/managed-ulw.ts +16 -20
  48. package/src/messenger-command-catalog.json +3 -2
  49. package/src/native-launch-profile.ts +16 -0
  50. package/src/native-settings.ts +9 -3
  51. package/src/result-attachment.ts +211 -0
  52. package/src/runtime.ts +1109 -157
  53. package/src/setup-memory.ts +15 -33
  54. package/src/setup.ts +24 -22
  55. package/src/store.ts +214 -13
  56. package/src/topic-history.ts +430 -0
  57. package/src/topic-request.ts +88 -0
@@ -1,39 +1,21 @@
1
- type MemoryPreferenceResult =
2
- | { status: "enabled" | "shadowed" | "not-saved"; agentDir: string; source: string }
3
- | { status: "failed" };
1
+ import type { Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
2
+ import { canEnableGlobalMemory, effectiveMnemopi, type MnemopiReport, type MnemopiStatus } from "./managed-memory";
4
3
 
5
- /** Called only after setup's configuration and credentials have been published. */
6
- export async function saveMnemopiPreference(cwd: string): Promise<MemoryPreferenceResult> {
4
+ /** Only after explicit global consent and successful setup publication. */
5
+ export async function saveMnemopiPreference(settings: Settings, expected: MnemopiStatus): Promise<MnemopiReport> {
7
6
  try {
8
- // Do not import the package entry point, a memory backend, or a model runtime.
9
- // Native settings transitively load native dotenv, so even these config-only
10
- // imports must stay behind credential acquisition and final publication.
11
- const [{ Settings }, { cfgMemoryBackend }, { editNativeGlobalConfig }] = await Promise.all([
12
- import("@oh-my-pi/pi-coding-agent/config/settings"),
13
- import("@oh-my-pi/pi-coding-agent/memory-backend/settings"),
14
- import("./native-settings"),
15
- ]);
16
- // Config-only persistence must not open agent.db, migrate authentication,
17
- // quarantine malformed startup config, or initialize the global singleton.
18
- const settings = await Settings.loadReadOnly({ cwd });
19
- await editNativeGlobalConfig(settings, [{ path: "memory.backend", value: "mnemopi" }]);
20
-
21
- // A concurrent edit may be preserved instead of applying our stale write.
22
- // A fresh, read-only instance is authoritative, not the writer's staged value.
23
- const actual = await Settings.loadReadOnly({ cwd, agentDir: settings.getAgentDir() });
24
- let persisted: unknown = actual.getGlobalSettings();
25
- for (const segment of cfgMemoryBackend.segments) {
26
- persisted = persisted && typeof persisted === "object" && Object.hasOwn(persisted, segment)
27
- ? (persisted as Record<string, unknown>)[segment] : undefined;
7
+ const current = await effectiveMnemopi(settings);
8
+ if (!canEnableGlobalMemory(current) || !Bun.deepEquals(current, expected)) {
9
+ return { memory: current, updated: false };
28
10
  }
29
- const source = actual.getProvenance(cfgMemoryBackend);
30
- return {
31
- status: persisted !== "mnemopi" ? "not-saved" : cfgMemoryBackend.get(actual) === "mnemopi" ? "enabled" : "shadowed",
32
- agentDir: actual.getAgentDir(), source,
33
- };
11
+ const { editNativeGlobalConfig, readNativeSettings } = await import("./native-settings");
12
+ const [updated] = await editNativeGlobalConfig(settings, [{ path: "memory.backend", value: "mnemopi" }],
13
+ async actual => Bun.deepEquals(await effectiveMnemopi(actual), expected));
14
+ // The native writer preserves concurrent settings. Report what the new process
15
+ // will resolve, not the user's consent or a transient staged value.
16
+ return { memory: await effectiveMnemopi(await readNativeSettings(settings)), updated: updated === true };
34
17
  } catch {
35
- // Native diagnostics can contain config values. Never echo a caught error or
36
- // undo setup publication / unrelated native writes to compensate for failure.
37
- return { status: "failed" };
18
+ // Native parse or lock errors can contain private settings.
19
+ return { memory: { status: "unknown" }, updated: false };
38
20
  }
39
21
  }
package/src/setup.ts CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  assertCredentialsUnchanged, readCredentialFile, serializeCredentials, stagePrivateFile,
13
13
  validateCredential, writeCredentials,
14
14
  } from "./credentials";
15
- import { saveMnemopiPreference } from "./setup-memory";
15
+ import { applyConsentedMnemopi, canEnableGlobalMemory, inspectManagedMnemopi, memoryBlockReason } from "./managed-memory";
16
16
  import { inspectNativeJudge } from "./setup-judge";
17
17
 
18
18
  const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -172,13 +172,12 @@ export async function setup(configPath: string): Promise<void> {
172
172
  const previousCredentials = readCredentialFile(path);
173
173
  let config: Config;
174
174
  let text: string | undefined;
175
- let recommendMemory = false;
176
175
  if (previousConfig) {
177
176
  let value: unknown;
178
177
  try { value = JSON.parse(previousConfig.toString("utf8")); }
179
178
  catch { throw new Error("Existing configuration is not valid JSON; it was not modified"); }
180
179
  config = parseConfig(value, path);
181
- console.log("Existing configuration preserved; only its configured credentials will be prompted.");
180
+ console.log("Existing configuration preserved; setup will check its configured credentials and native memory.");
182
181
  } else {
183
182
  ({ config, text } = await newConfig(terminal, path));
184
183
  }
@@ -207,13 +206,18 @@ export async function setup(configPath: string): Promise<void> {
207
206
  }
208
207
  serializeCredentials(values); // Prove lossless encoding before any persistent write.
209
208
  if (replacing) await terminal.confirm("Replace existing credential values?");
210
- if (!previousConfig) {
211
- console.log("Recommended: native OMP Mnemopi memory persists across conversations (project-scoped by default).");
212
- console.log("This saves OMP's global memory.backend preference only; existing memory options stay unchanged.");
209
+ const initialMemory = await inspectManagedMnemopi(config);
210
+ let memoryConsent: Parameters<typeof applyConsentedMnemopi>[1] | undefined;
211
+ if (canEnableGlobalMemory(initialMemory)) {
212
+ console.log("Managed sessions require native OMP Mnemopi memory, which persists across conversations (project-scoped by default).");
213
+ console.log(`This would change OMP's global memory.backend preference for ${initialMemory.agentDir}; existing memory options stay unchanged.`);
213
214
  console.log("Depending on existing native settings, later memory use may process conversations with models and download models.");
214
215
  console.log("Setup does not start memory or OMP; it activates on later OMP startup. Running OMP instances may apply native settings reloads.");
215
- recommendMemory = /^y(es)?$/i.test((await terminal.ask("Enable native Mnemopi memory after saving setup? [y/N]: ")).trim());
216
- if (!recommendMemory) console.log("Native memory settings will not be changed.");
216
+ if (/^y(es)?$/i.test((await terminal.ask("Enable native Mnemopi memory after saving setup? [y/N]: ")).trim())) {
217
+ memoryConsent = initialMemory;
218
+ } else {
219
+ console.log("Native memory settings will not be changed.");
220
+ }
217
221
  }
218
222
  console.log(`Configuration: ${path}\nPrivate credentials: ${path}.env`);
219
223
  const profilePlatforms = (["discord", "telegram"] as const).filter(platform => config[platform]);
@@ -248,19 +252,16 @@ export async function setup(configPath: string): Promise<void> {
248
252
  }
249
253
  terminal.saved = true;
250
254
  console.log(`Saved configuration: ${path}\nPrivate credentials: ${path}.env (0600)`);
251
- if (recommendMemory) {
252
- const memory = await saveMnemopiPreference(config.headCwd);
253
- if (memory.status === "failed") {
254
- console.log("Setup saved, but native Mnemopi could not be saved or verified; memory activation is not confirmed. No service was started by setup.");
255
- } else if (memory.status === "not-saved") {
256
- console.log("Setup saved, but native persistence did not retain memory.backend=mnemopi; Mnemopi was not enabled by setup. Concurrent native settings were preserved.");
257
- } else if (memory.status === "shadowed") {
258
- console.log(`Saved native memory.backend=mnemopi in OMP agent settings: ${memory.agentDir}`);
259
- console.log(`Mnemopi is not effective for the head workspace (${memory.source} settings take precedence); those settings were preserved. No service was started by setup.`);
260
- } else {
261
- console.log(`Saved native memory.backend=mnemopi in OMP agent settings: ${memory.agentDir}`);
262
- console.log("Mnemopi is configured for the head workspace on later OMP startup; no service was started by setup.");
263
- }
255
+ terminal.check();
256
+ const { memory, updated } = memoryConsent ? await applyConsentedMnemopi(config, memoryConsent)
257
+ : { memory: await inspectManagedMnemopi(config), updated: false };
258
+ terminal.check();
259
+ if (updated) console.log("Saved native memory.backend=mnemopi in OMP agent settings.");
260
+ if (memory.status === "enabled") {
261
+ console.log(`Mnemopi is configured for the head workspace (${memory.source} settings); no service was started by setup.`);
262
+ } else {
263
+ console.log(`Setup saved but is incomplete. ${memoryBlockReason(memory)} No service was started by setup.`);
264
+ process.exitCode = 1;
264
265
  }
265
266
  if (createdConfig) {
266
267
  const judge = await inspectNativeJudge(config.headCwd);
@@ -292,7 +293,8 @@ export async function setup(configPath: string): Promise<void> {
292
293
  console.log(`Slack app icon file: ${join(root, "assets", "superagent-avatar.jpg")}`);
293
294
  }
294
295
  const cli = `${shellQuote(process.execPath)} --no-env-file ${shellQuote(join(root, "src", "cli.ts"))}`;
295
- console.log(`Next: ${cli} doctor --config ${shellQuote(path)}\nStart explicitly: ${cli} start --config ${shellQuote(path)}`);
296
+ console.log(`Next: ${cli} doctor --config ${shellQuote(path)}`);
297
+ if (memory.status === "enabled") console.log(`Start explicitly: ${cli} start --config ${shellQuote(path)}`);
296
298
  } finally {
297
299
  try { if (configTemporary) unlinkSync(configTemporary); }
298
300
  finally { await terminal.close(); }
package/src/store.ts CHANGED
@@ -34,6 +34,7 @@ import { isLaneModel, laneModelArgument, sameLaneModel } from "./lane-models";
34
34
  import { readLaneRows, toLane } from "./lane-rows";
35
35
  import { workflowChoice } from "./workflow";
36
36
  import { laneWaitKey, type LaneReport } from "./lane-report";
37
+ import { existingWorkspace, TOPIC_CHOICE_WAIT_MS, topicRequest } from "./topic-request";
37
38
  import type { CronUpdate } from "./cron-jobs";
38
39
 
39
40
  const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
@@ -65,9 +66,10 @@ const SCHEMA = `
65
66
  source_id TEXT NOT NULL, route TEXT NOT NULL, text TEXT NOT NULL,
66
67
  state TEXT NOT NULL DEFAULT 'pending'
67
68
  CHECK(state IN ('pending','sending','sent','uncertain','failed')),
68
- remote_id TEXT, error TEXT, reply_to TEXT, picker TEXT
69
+ remote_id TEXT, error TEXT, reply_to TEXT, picker TEXT, result_attachment TEXT
69
70
  );
70
71
  CREATE INDEX IF NOT EXISTS outputs_queue ON outputs(state, sequence);
72
+ CREATE INDEX IF NOT EXISTS outputs_sent_message ON outputs(remote_id) WHERE state = 'sent' AND remote_id IS NOT NULL;
71
73
  CREATE TABLE IF NOT EXISTS approvals (
72
74
  sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
73
75
  target TEXT NOT NULL, generation INTEGER NOT NULL, request_id TEXT NOT NULL, data TEXT NOT NULL,
@@ -100,6 +102,7 @@ interface OutputRow {
100
102
  route: string;
101
103
  reply_to: string | null;
102
104
  picker: string | null;
105
+ result_attachment: string | null;
103
106
  text: string;
104
107
  state: OutputRecord["state"];
105
108
  remote_id: string | null;
@@ -116,6 +119,7 @@ const toOutput = (row: OutputRow): OutputRecord => ({
116
119
  id: row.id, sourceId: row.source_id, route: JSON.parse(row.route) as Route,
117
120
  ...(row.reply_to === null ? {} : { replyTo: JSON.parse(row.reply_to) as NonNullable<OutputRecord["replyTo"]> }),
118
121
  ...(row.picker === null ? {} : { picker: JSON.parse(row.picker) as NonNullable<OutputRecord["picker"]> }),
122
+ ...(row.result_attachment === null ? {} : { resultAttachment: JSON.parse(row.result_attachment) as NonNullable<OutputRecord["resultAttachment"]> }),
119
123
  text: row.text, state: row.state, remoteId: row.remote_id, error: row.error,
120
124
  });
121
125
  const toApproval = (row: ApprovalRow): Approval => ({
@@ -193,6 +197,7 @@ export class Store implements StorePort {
193
197
  const outputColumns = db.query("PRAGMA table_info(outputs)").all() as Array<{ name: string }>;
194
198
  if (!outputColumns.some(column => column.name === "reply_to")) db.run("ALTER TABLE outputs ADD COLUMN reply_to TEXT");
195
199
  if (!outputColumns.some(column => column.name === "picker")) db.run("ALTER TABLE outputs ADD COLUMN picker TEXT");
200
+ if (!outputColumns.some(column => column.name === "result_attachment")) db.run("ALTER TABLE outputs ADD COLUMN result_attachment TEXT");
196
201
  this.db = db;
197
202
  this.writerLock = lock;
198
203
  } catch (error) {
@@ -237,7 +242,8 @@ export class Store implements StorePort {
237
242
  if (workflow !== null) {
238
243
  workflowChoice({ name: workflow.name, reason: workflow.reason });
239
244
  if (workflow.provenance === "user") {
240
- if (workflow.sourceId !== input.id || metadata[`user-source:${input.id}`] !== "true" || target !== "main") {
245
+ if (workflow.sourceId !== input.id || metadata[`user-source:${input.id}`] !== "true"
246
+ || !(target === "main" || target === null && metadata[`topic-owner:${input.id}`])) {
241
247
  throw new Error("User workflow requires original authorized head intake");
242
248
  }
243
249
  } else if (workflow.provenance === "head") {
@@ -270,6 +276,112 @@ export class Store implements StorePort {
270
276
  return source;
271
277
  }
272
278
 
279
+ private topicOwner(input: InputRecord): InputRecord | null {
280
+ if (!input.target || input.target === "main") return null;
281
+ let source: InputRecord | null = input;
282
+ while (source && this.getMeta(`user-source:${source.id}`) !== "true") {
283
+ const linked: string | null = this.getMeta(`handoff-source:${source.id}`);
284
+ source = linked ? this.input(linked) : null;
285
+ }
286
+ return source && this.getMeta(`topic-owner:${source.id}`) === input.target ? source : null;
287
+ }
288
+
289
+ topicDelivery(id: string) {
290
+ const input = this.input(id);
291
+ const source = input && this.topicOwner(input);
292
+ if (!input || !source) return null;
293
+ const revisionOf = this.getMeta(`topic-revision:${source.id}`);
294
+ const original = revisionOf === null ? source : source.messageId === null ? null : this.firstAdmittedMessage(source.route, source.messageId);
295
+ if (!original || revisionOf !== null && (original.id !== revisionOf || original.id === source.id
296
+ || routeKey(original.route) !== routeKey(source.route) || this.getMeta(`topic-owner:${original.id}`) !== input.target)) {
297
+ throw new Error(`Invalid topic revision ancestry: ${source.id}`);
298
+ }
299
+ const route = this.deliveryRoute(original, input.target);
300
+ // Preserve the original identity on its own route. A selected work thread
301
+ // uses its exact handoff (which still links to the original owner source).
302
+ const outputSourceId = routeKey(route) === routeKey(source.route) ? source.id : input.id;
303
+ if (outputSourceId === input.id && routeKey(route) !== routeKey(input.route)) {
304
+ throw new Error(`Topic delivery route differs from its handoff: ${input.id}`);
305
+ }
306
+ return { source, route, outputSourceId };
307
+ }
308
+
309
+ hasTopicAdmission(target: string, generation: number): boolean {
310
+ const rows = this.db.query<InputRow, [string, number]>(
311
+ "SELECT * FROM inputs WHERE target = ? AND generation = ? AND request_id IS NOT NULL",
312
+ ).iterate(target, generation);
313
+ for (const row of rows) if (this.topicOwner(toInput(row))) return true;
314
+ return false;
315
+ }
316
+
317
+ hasPendingTopicChoice(input: InputRecord, deadline: number): boolean {
318
+ const { platform, accountId, authorityId, guildId, channelId, threadId } = input.route;
319
+ if (platform !== "discord" || guildId === null || threadId === null) return false;
320
+ // Gateway creates the shared ingress ledger; standalone Store use has none.
321
+ if (!this.db.query("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'gateway_events'").get()) return false;
322
+ const questionId = `${input.id}:workspace`;
323
+ const choices: readonly { readonly cwd: string }[] = JSON.parse(this.getMeta(`topic-history:${input.id}`) ?? "[]");
324
+ // The Gateway pending index skips delivered history, including terminal rejections.
325
+ // Unresolved rows stay pending. The durable insert, not its wall-clock timestamp,
326
+ // fences a timely-authored choice even when transport-delayed.
327
+ const rows = this.db.query<{
328
+ readonly id: string; readonly text: string; readonly messageId: string | null;
329
+ readonly replyId: string | null; readonly authoredAt: number;
330
+ }, [number, number, string, string, string, string, string, string, string]>(`
331
+ SELECT json_extract(data, '$.input.id') AS id,
332
+ json_extract(data, '$.input.text') AS text,
333
+ json_extract(data, '$.input.messageId') AS messageId,
334
+ json_extract(data, '$.input.reply.messageId') AS replyId,
335
+ json_extract(data, '$.input.receivedAt') AS authoredAt
336
+ FROM gateway_events INDEXED BY gateway_events_pending WHERE delivered_at IS NULL
337
+ AND json_extract(data, '$.kind') = 'message'
338
+ AND json_type(data, '$.input.pickerSelection') IS NULL
339
+ AND (json_type(data, '$.input.messageId') = 'text'
340
+ OR json_type(data, '$.input.interactionId') = 'text')
341
+ AND json_type(data, '$.input.receivedAt') = 'integer'
342
+ AND json_extract(data, '$.input.receivedAt') BETWEEN ? AND ?
343
+ AND json_extract(data, '$.input.id') <> ?
344
+ AND json_extract(data, '$.input.route.platform') = ?
345
+ AND json_extract(data, '$.input.route.accountId') = ?
346
+ AND json_extract(data, '$.input.route.authorityId') = ?
347
+ AND json_extract(data, '$.input.route.guildId') = ?
348
+ AND json_extract(data, '$.input.route.channelId') = ?
349
+ AND json_extract(data, '$.input.route.threadId') = ?
350
+ `).iterate(input.receivedAt, deadline, input.id, platform, accountId, authorityId, guildId, channelId, threadId);
351
+ for (const row of rows) {
352
+ if (row.messageId !== null && row.id.startsWith(`discord:${accountId}:${row.messageId}:edit:`)) continue;
353
+ const questionReply = row.replyId !== null && this.sentOutputForMessage(input.route, row.replyId)?.id === questionId;
354
+ const scopedReply = questionReply || row.replyId !== null && row.replyId === input.messageId;
355
+ if (!questionReply && row.authoredAt < deadline - TOPIC_CHOICE_WAIT_MS) continue;
356
+ const text = row.text.trim();
357
+ if (text === "/stop") return true;
358
+ if (row.messageId === null || row.replyId !== null && !scopedReply || /^\/new(?:\s|$)/.test(text)) continue;
359
+ if (/^[1-9]\d*$/.test(text)) return true;
360
+ const request = topicRequest(text);
361
+ if (request.cwd === null ? !scopedReply : request.text.trim()) continue;
362
+ const cwd = existingWorkspace(request.cwd ?? text);
363
+ if (choices.some(ref => cwd !== null ? ref.cwd === cwd
364
+ : request.cwd === null && basename(ref.cwd).toLowerCase() === text.toLowerCase())) return true;
365
+ }
366
+ return false;
367
+ }
368
+
369
+ tryAutoTopicChoice(input: InputRecord, deadline: number, pin: string): boolean {
370
+ return this.db.transaction(() => {
371
+ const current = this.input(input.id);
372
+ const automatic = `topic-choice-auto:${input.id}`;
373
+ // Gateway admission also acquires a write lock on this database. No timely
374
+ // answer can commit between our last ledger read and saving the fallback.
375
+ if (!Number.isSafeInteger(deadline) || Date.now() < deadline
376
+ || current?.state !== "pending" || current.target !== null || routeKey(current.route) !== routeKey(input.route)
377
+ || this.getMeta(`topic-choice-deadline:${input.id}`) !== String(deadline)
378
+ || this.getMeta(`topic-previous:${input.id}`) !== null || this.getMeta(automatic) !== null
379
+ || this.hasPendingTopicChoice(current, deadline)) return false;
380
+ this.setMeta(automatic, pin);
381
+ return true;
382
+ }).immediate();
383
+ }
384
+
273
385
  inputs(target?: string, state?: ActiveInputState): InputRecord[] {
274
386
  const scope = [ACTIVE_INPUTS];
275
387
  const bindings: string[] = [];
@@ -314,6 +426,33 @@ export class Store implements StorePort {
314
426
  return row ? toInput(row) : null;
315
427
  }
316
428
 
429
+ sentOutputForMessage(route: Route, messageId: string): OutputRecord | null {
430
+ const part = route.platform === "discord" ? this.getMeta(`discord:output-part:${messageId}`) : null;
431
+ const rows = this.db.query<OutputRow, [string, string | null]>(
432
+ "SELECT * FROM outputs WHERE state = 'sent' AND (remote_id = ? OR id = ?)",
433
+ ).all(messageId, part);
434
+ const scoped = rows.map(toOutput).filter(output => physicalRouteKey(output.route) === physicalRouteKey(route));
435
+ return scoped.length === 1 ? scoped[0]! : null;
436
+ }
437
+
438
+ repliedTopicWorkspace(route: Route, messageId: string): string | null {
439
+ const original = this.firstAdmittedMessage(route, messageId);
440
+ const output = this.sentOutputForMessage(route, messageId);
441
+ const source = output && this.ownerSource(output.sourceId);
442
+ const sourceIds = new Set([original?.id, source?.id]);
443
+ const workspaces = new Set<string>();
444
+ for (const id of sourceIds) {
445
+ if (!id) continue;
446
+ const owner = this.getMeta(`topic-owner:${id}`);
447
+ if (!owner) continue;
448
+ const creation = this.getMeta(`topic-creator:${id}`);
449
+ if (this.input(`handoff:${id}:${creation ? "lane" : owner}`)?.target !== owner) continue;
450
+ const lane = this.lane(owner);
451
+ if (lane) workspaces.add(lane.cwd);
452
+ }
453
+ return workspaces.size === 1 ? [...workspaces][0]! : null;
454
+ }
455
+
317
456
  *admittedMessageIds(route: Route): Iterable<string> {
318
457
  const rows = this.db.query<{ messageId: string }, [string, string, string, string, string | null, string | null]>(
319
458
  `SELECT json_extract(inputs.data, '$.messageId') AS messageId ${ADMITTED_MESSAGE_SCOPE}
@@ -381,6 +520,17 @@ export class Store implements StorePort {
381
520
  this.setMeta(`progress-output:${receiptId}`, JSON.stringify(context));
382
521
  return this.queueOutput({ id: receiptId, sourceId: id, route: input.route, text });
383
522
  }
523
+ const topic = this.topicDelivery(id);
524
+ if (topic) {
525
+ if (topic.source.state === "cancelled" || topic.source.state === "uncertain") return false;
526
+ const pendingKey = `topic-progress-pending:${id}`;
527
+ const previous = this.getMeta(pendingKey);
528
+ if (previous) this.db.query("UPDATE outputs SET state = 'failed', error = ? WHERE id = ? AND state = 'pending'")
529
+ .run("Nonterminal progress superseded", previous);
530
+ this.setMeta(pendingKey, receiptId);
531
+ this.setMeta(`progress-output:${receiptId}`, JSON.stringify(context));
532
+ return this.queueOutput({ id: receiptId, sourceId: topic.outputSourceId, route: topic.route, text });
533
+ }
384
534
  const lane = this.requireLane(input.target!);
385
535
  const sourceId = this.getMeta(`handoff-source:${id}`);
386
536
  const source = sourceId ? this.requireInput(sourceId) : input;
@@ -456,9 +606,9 @@ export class Store implements StorePort {
456
606
  this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
457
607
  .run(JSON.stringify({ ...lane, observation }), lane.id, generation);
458
608
  this.setMeta(seen, serialized);
459
- // Only a new evidence snapshot or waiting transition needs a head turn.
460
- // Repeated reports remain inspectable without manufacturing progress.
461
- if (changed) this.progress(id, generation, sessionId, `structured:${eventId}`, [
609
+ // Topic evidence stays inspectable; only assistant commentary is delivered.
610
+ // Legacy HEAD review needs a new evidence snapshot or waiting transition.
611
+ if (changed && !this.topicOwner(input)) this.progress(id, generation, sessionId, `structured:${eventId}`, [
462
612
  `Structured lane observation: ${JSON.stringify(observation)}`,
463
613
  "Evidence is observed/worker-selected, not verified acceptance. Waiting and its resolution grant no dispatch, approval or resume authority.",
464
614
  ].join("\n\n"));
@@ -480,7 +630,7 @@ export class Store implements StorePort {
480
630
  this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
481
631
  .run(JSON.stringify({ ...lane, observation: resolved }), lane.id, generation);
482
632
  // Completion/cancellation of a wait is not evidence of successful work.
483
- this.progress(id, generation, sessionId, `resolved:${JSON.stringify([kind, nativeId, waiting.since])}`, [
633
+ if (!this.topicOwner(input)) this.progress(id, generation, sessionId, `resolved:${JSON.stringify([kind, nativeId, waiting.since])}`, [
484
634
  `Native waiting target finished or was cancelled: ${JSON.stringify(waiting.target)}.`,
485
635
  `Structured lane observation: ${JSON.stringify(resolved)}`,
486
636
  "This clears only the matching wait observation. It does not verify success, answer an approval, or resume work.",
@@ -498,7 +648,16 @@ export class Store implements StorePort {
498
648
  const progress = this.getMeta(`progress-source:${id}`);
499
649
  if (progress && !this.progressOpen(JSON.parse(progress))) output = undefined;
500
650
  // An uncertain request can only be resolved explicitly, never resubmitted.
501
- if (output && input.target && input.target !== "main") {
651
+ const topic = output && this.topicDelivery(id);
652
+ if (output && topic) {
653
+ if (output.text.trim() && (topic.source.id === id
654
+ || topic.source.state !== "cancelled" && topic.source.state !== "uncertain")) {
655
+ this.queueOutput({
656
+ ...output, id: input.state === "uncertain" ? `${output.id}:${state}` : output.id,
657
+ sourceId: topic.outputSourceId, route: topic.route,
658
+ });
659
+ }
660
+ } else if (output && input.target && input.target !== "main") {
502
661
  const lane = this.requireLane(input.target);
503
662
  const sourceId = this.getMeta(`handoff-source:${id}`);
504
663
  const source = sourceId ? this.requireInput(sourceId) : input;
@@ -636,13 +795,13 @@ export class Store implements StorePort {
636
795
  }).immediate();
637
796
  }
638
797
 
639
- private deliveryRoute(source: InputRecord): Route {
798
+ private deliveryRoute(source: InputRecord, expectedLane?: string | null): Route {
640
799
  const stored = this.getMeta(`head-delivery:${source.id}`);
641
800
  if (!stored) return source.route;
642
801
  const decision = JSON.parse(stored) as { source: Route; destination: Route; laneId: string };
643
802
  const lane = this.lane(decision.laneId);
644
803
  const handoff = this.input(`handoff:${source.id}:lane`);
645
- if (!lane || routeKey(decision.source) !== routeKey(source.route)
804
+ if (!lane || expectedLane !== undefined && lane.id !== expectedLane || routeKey(decision.source) !== routeKey(source.route)
646
805
  || !handoff || handoff.target !== lane.id || this.getMeta(`handoff-source:${handoff.id}`) !== source.id
647
806
  || routeKey(handoff.route) !== routeKey(lane.route) || routeKey(decision.destination) !== routeKey(lane.route)) {
648
807
  throw new Error(`Invalid head-selected delivery binding: ${source.id}`);
@@ -656,6 +815,7 @@ export class Store implements StorePort {
656
815
  if (existing) {
657
816
  if (existing.sourceId !== output.sourceId || routeKey(existing.route) !== routeKey(output.route)
658
817
  || existing.text !== output.text || !isDeepStrictEqual(existing.picker, output.picker)
818
+ || !isDeepStrictEqual(existing.resultAttachment, output.resultAttachment)
659
819
  || output.replyTo !== undefined && (!existing.replyTo
660
820
  || existing.replyTo.messageId !== output.replyTo.messageId
661
821
  || physicalRouteKey(existing.replyTo.route) !== physicalRouteKey(output.replyTo.route))) {
@@ -670,6 +830,24 @@ export class Store implements StorePort {
670
830
  // Synthetic handoffs/reports can carry a copied messageId on a different
671
831
  // route. Follow only durable source links, never that copy or ReplyContext.
672
832
  const original = this.ownerSource(output.sourceId);
833
+ const attachment = output.resultAttachment;
834
+ if (attachment) {
835
+ const native = this.input(attachment.inputId);
836
+ const topic = native && this.topicDelivery(native.id);
837
+ const runId = native && this.getMeta(`steering-owner:${native.id}`);
838
+ const run = runId && this.input(runId);
839
+ const ownership = run && this.getMeta(`${native?.target === "main" ? "head-native-owner" : "lane-observation-owner"}:${run.id}`);
840
+ const owner = ownership && JSON.parse(ownership);
841
+ if (output.text || output.picker || !original || original.id !== attachment.sourceId || !native || native.state !== "submitted"
842
+ || native.requestId !== attachment.requestId || native.generation !== attachment.generation
843
+ || !run || !owner || run.target !== native.target || owner.requestId !== run.requestId
844
+ || owner.generation !== attachment.generation || owner.sessionId !== attachment.sessionId
845
+ || owner.sessionFile !== attachment.sessionFile
846
+ || (topic ? topic.source.id !== original.id || topic.outputSourceId !== output.sourceId || routeKey(topic.route) !== routeKey(output.route)
847
+ : native.target !== "main" || native.id !== original.id || native.id !== output.sourceId)) {
848
+ throw new Error(`Result attachment does not match its original native request: ${output.id}`);
849
+ }
850
+ }
673
851
  const replyTo = original?.route.platform === "discord" && original.messageId
674
852
  && physicalRouteKey(original.route) === physicalRouteKey(output.route)
675
853
  ? { route: physicalRoute(original.route), messageId: original.messageId } : undefined;
@@ -677,9 +855,9 @@ export class Store implements StorePort {
677
855
  || physicalRouteKey(output.replyTo.route) !== physicalRouteKey(replyTo.route))) {
678
856
  throw new Error(`Output reply differs from its source: ${output.id}`);
679
857
  }
680
- return this.db.query("INSERT INTO outputs(id, source_id, route, text, reply_to, picker) VALUES (?, ?, ?, ?, ?, ?)")
858
+ return this.db.query("INSERT INTO outputs(id, source_id, route, text, reply_to, picker, result_attachment) VALUES (?, ?, ?, ?, ?, ?, ?)")
681
859
  .run(output.id, output.sourceId, JSON.stringify(output.route), output.text, replyTo ? JSON.stringify(replyTo) : null,
682
- output.picker ? JSON.stringify(output.picker) : null).changes === 1;
860
+ output.picker ? JSON.stringify(output.picker) : null, attachment ? JSON.stringify(attachment) : null).changes === 1;
683
861
  }).immediate();
684
862
  }
685
863
 
@@ -688,6 +866,13 @@ export class Store implements StorePort {
688
866
  .all() as OutputRow[]).map(toOutput);
689
867
  }
690
868
 
869
+ hasUnresolvedHeadDelivery(): boolean {
870
+ return this.db.query(`SELECT 1 FROM outputs
871
+ LEFT JOIN inputs ON inputs.id = outputs.source_id
872
+ WHERE outputs.state IN ('sending','uncertain') AND
873
+ (inputs.target IS NULL OR inputs.target = 'main') LIMIT 1`).get() !== null;
874
+ }
875
+
691
876
  claimOutput(id: string): boolean {
692
877
  const progress = this.getMeta(`progress-output:${id}`);
693
878
  if (progress && !this.progressOpen(JSON.parse(progress))) {
@@ -706,6 +891,9 @@ export class Store implements StorePort {
706
891
  if (remoteId !== undefined && output.remoteId !== remoteId) throw new Error(`Output receipt conflict: ${id}`);
707
892
  return;
708
893
  }
894
+ if (output.resultAttachment && state === "pending") {
895
+ throw new Error(`A result attachment is never retried: ${id}`);
896
+ }
709
897
  const retry = state === "pending" && (output.state === "uncertain" || output.state === "failed");
710
898
  const reconcile = output.state === "uncertain" && state === "sent";
711
899
  if (output.state !== "sending" && !retry && !reconcile) {
@@ -713,6 +901,12 @@ export class Store implements StorePort {
713
901
  }
714
902
  this.db.query("UPDATE outputs SET state = ?, remote_id = ?, error = ? WHERE id = ?")
715
903
  .run(state, state === "pending" ? null : remoteId ?? output.remoteId, error ?? null, id);
904
+ // Start the owner's response window with the durable question receipt,
905
+ // never with input admission or an unconfirmed send attempt.
906
+ if (state === "sent" && id === `${output.sourceId}:workspace`
907
+ && this.getMeta(`topic-history:${output.sourceId}`) !== null && !this.getMeta(`topic-creator:${output.sourceId}`)) {
908
+ this.setMeta(`topic-choice-deadline:${output.sourceId}`, String(Date.now() + TOPIC_CHOICE_WAIT_MS));
909
+ }
716
910
  }).immediate();
717
911
  }
718
912
 
@@ -832,7 +1026,7 @@ export class Store implements StorePort {
832
1026
  }).immediate();
833
1027
  }
834
1028
 
835
- putApproval(approval: Approval): void {
1029
+ putApproval(approval: Approval, ownerInputId?: string): void {
836
1030
  this.db.transaction(() => {
837
1031
  const existing = this.approval(approval.id);
838
1032
  if (existing) {
@@ -841,7 +1035,14 @@ export class Store implements StorePort {
841
1035
  }
842
1036
  return; // Re-observation cannot undo a previous answer/cancellation.
843
1037
  }
844
- this.checkTarget(approval.target, approval.route);
1038
+ if (ownerInputId) {
1039
+ const owner = this.input(ownerInputId);
1040
+ const topic = owner?.target === approval.target && owner.generation === approval.generation
1041
+ ? this.topicDelivery(owner.id) : null;
1042
+ if (!topic || routeKey(topic.route) !== routeKey(approval.route))
1043
+ throw new Error(`Approval does not match its topic source: ${approval.id}`);
1044
+ this.setMeta(`topic-approval:${approval.id}`, topic.source.id);
1045
+ } else this.checkTarget(approval.target, approval.route);
845
1046
  const lane = this.lane(approval.target);
846
1047
  if (lane && lane.generation !== approval.generation) throw new Error("Stale approval generation");
847
1048
  this.db.query("INSERT INTO approvals(id, target, generation, request_id, data, state, remote_id) VALUES (?, ?, ?, ?, ?, ?, ?)")