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
@@ -15,7 +15,7 @@ import { buildServiceTierByFamily } from "@oh-my-pi/pi-coding-agent/config/servi
15
15
  import { getRestorableSessionModels } from "@oh-my-pi/pi-coding-agent/session/session-context";
16
16
  import { clampThinkingLevelForModel } from "@oh-my-pi/pi-catalog/model-thinking";
17
17
  import { parseSessionEntries, readSessionHeaderId } from "@oh-my-pi/pi-coding-agent/session/session-loader";
18
- import { HostChannel, LANE_MODEL_PROMOTION_RECEIPT, PR_REVIEW_GITHUB_ENV, PR_REVIEW_SYSTEM_PROMPT, indexServiceCompletions, serviceGenerationKey, type FastModeState, type Frame, type ServiceUnit } from "./omp/host-protocol";
18
+ import { HostChannel, LANE_MODEL_PROMOTION_RECEIPT, PR_REVIEW_GITHUB_ENV, PR_REVIEW_SYSTEM_PROMPT, indexServiceCompletions, serviceGenerationKey, terminalService, type FastModeState, type Frame, type ServiceUnit } from "./omp/host-protocol";
19
19
  import { USER_INTERRUPT_LABEL } from "@oh-my-pi/pi-coding-agent/session/messages";
20
20
  import { MAX_RPC_REASSEMBLED_BYTES } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-frame";
21
21
  import { fitAbortAndRestoreQueueResponse } from "@oh-my-pi/pi-coding-agent/modes/rpc/rpc-mode";
@@ -32,8 +32,11 @@ import { installReplyVoice } from "./omp/host-reply-voice";
32
32
  import { matchesPreparedLaunch } from "./omp/stock-head-launch";
33
33
  import { NATIVE_PROFILE_ENV, bindNativeProfile, matchesNativeProfile, type HostReadyEvent,
34
34
  type NativeProfileBinding, type NativeProfilePaths } from "./omp/native-sessions";
35
+ import { isWorkerMemoryCursor, isWorkerMemoryStamp } from "./worker/worker-memory-page";
36
+ import { canBeginWorkerFact, isWorkerFactRoot, type WorkerFactCarrier } from "./worker/worker-memory-proofs";
37
+ import { bindWorkerMemorySource } from "./worker/worker-memory-source";
38
+ import { WORKER_MEMORY_ENV, WORKER_MEMORY_PROFILE_ENV } from "./worker/worker-memory-storage";
35
39
 
36
- const terminalService = (state: ServiceUnit["state"]) => state === "exited" || state === "failed";
37
40
  const serviceGeneration = ({ owner, id, generation, startedAt, restartCount }: ServiceUnit) =>
38
41
  ({ owner, id, generation, startedAt, restartCount });
39
42
  const serviceName = (value: unknown) => typeof value === "string" ? value.trim() || undefined : undefined;
@@ -90,6 +93,12 @@ export default function hostExtension(pi: ExtensionAPI): void {
90
93
  let instanceKey: string | undefined;
91
94
  const selectedSuperkit = process.env[MANAGED_ULW_ENV];
92
95
  const workerAttempt = process.env.OMP_SUPERAGENT_WORKER_ATTEMPT;
96
+ const memoryLaunch = workerAttempt && process.env.OMP_SUPERAGENT_ROLE === "lane" ? process.env[WORKER_MEMORY_ENV] : undefined;
97
+ const workerMemoryProfileBinding: NativeProfileBinding | null = memoryLaunch
98
+ ? JSON.parse(process.env[WORKER_MEMORY_PROFILE_ENV] ?? "null") : null;
99
+ let workerMemoryProfile: { readonly root: ReturnType<typeof exact>; readonly paths: NativeProfilePaths } | undefined;
100
+ let workerMemoryProfileAttempted = false;
101
+ let workerMemory: ReturnType<typeof bindWorkerMemorySource> | undefined;
93
102
  const reviewCwd = process.env.OMP_SUPERAGENT_PR_REVIEW_CWD;
94
103
  let replyVoice: ReturnType<typeof installReplyVoice>;
95
104
  if (reviewCwd && PR_REVIEW_GITHUB_ENV.some(name => process.env[name]))
@@ -202,6 +211,24 @@ export default function hostExtension(pi: ExtensionAPI): void {
202
211
  if (!(error instanceof Error)) throw error;
203
212
  }
204
213
  };
214
+ const workerMemoryProfileCurrent = ({ session, ref, id, file }: ReturnType<typeof exact>): boolean => {
215
+ if (!workerMemoryProfileBinding || !workerMemoryProfile || !file) return false;
216
+ const { root, paths } = workerMemoryProfile;
217
+ if (root.session !== session || root.ref !== ref || root.id !== id || root.file !== file) return false;
218
+ const { profile, discoveryEntry } = workerMemoryProfileBinding;
219
+ return matchesNativeProfile(paths, profile) && realpathSync(dirname(discoveryEntry)) === dirname(discoveryEntry)
220
+ && realpathSync(discoveryEntry) === file;
221
+ };
222
+ const currentWorkerMemory = (identity: ReturnType<typeof exact>) => {
223
+ const { session, file } = identity;
224
+ if (!memoryLaunch || !workerAttempt || !file || !workerMemoryProfileCurrent(identity)) return;
225
+ // Background native initialization must not delay Host startup or tools.
226
+ // Keep the attested root/profile even if there is not yet a live source.
227
+ if (!workerMemory && session.getMnemopiSessionState?.()) {
228
+ workerMemory = bindWorkerMemorySource(session, { encoded: memoryLaunch, file, attempt: workerAttempt });
229
+ }
230
+ return workerMemory;
231
+ };
205
232
  const snapshot = () => {
206
233
  const { session } = exact();
207
234
  return { modelRoles: session.settings.getModelRoles(),
@@ -682,12 +709,61 @@ export default function hostExtension(pi: ExtensionAPI): void {
682
709
  if (observationHeld) throw new Error("Durable native observations are unavailable");
683
710
  return { ...ownerIdentity(identity), leafId: identity.session.sessionManager.getLeafId() };
684
711
  }
712
+ if (command.type === "get_worker_memory") {
713
+ const { after, unchanged } = command;
714
+ if (!workerMemoryProfile || !isWorkerMemoryCursor(after) || (unchanged !== undefined && (after !== 0 || !isWorkerMemoryStamp(unchanged))))
715
+ throw new Error("Worker memory is unavailable");
716
+ const identity = exact();
717
+ const { session } = identity;
718
+ const run = runOrdinal;
719
+ const assertIdle = () => {
720
+ assertSameRoot(identity);
721
+ if (runOrdinal !== run || !localIdle() || session.isSessionTransitioning !== false
722
+ || session.isRunActive !== false || session.getPlanModeState()?.enabled || session.getPrewalkState?.())
723
+ throw new Error("session_busy");
724
+ if (!workerMemoryProfileCurrent(identity)) throw new Error("Worker memory profile changed");
725
+ };
726
+ assertIdle();
727
+ const source = currentWorkerMemory(identity);
728
+ if (!source) throw new Error("Worker memory is unavailable");
729
+ await source.verifyCheckout();
730
+ assertIdle();
731
+ const observed = source.page({ after, ...(unchanged !== undefined && { unchanged }) }, run > 0);
732
+ // The earlier worker probe alone cannot cover later Git changes while
733
+ // attached. Check again before releasing any native contents.
734
+ await source.verifyCheckout();
735
+ assertIdle();
736
+ observed.assertCurrent();
737
+ return { ...ownerIdentity(identity), page: observed.page };
738
+ }
685
739
  if (command.type === "snapshot") {
686
740
  const ownership = await owned();
687
741
  // The owner requires this first snapshot before opening its public socket.
688
742
  const prReviewPolicy = reviewCwd ? reviewPolicy(ownership.identity.session, reviewCwd) : undefined;
689
743
  if (!reviewCwd) loadedSuperkitPath ??= await verifyHostSuperkit(ownership.identity.session, selectedSuperkit);
690
744
  const { session, ref } = ownership.identity;
745
+ let workerMemoryControlVersion: 1 | undefined;
746
+ if (memoryLaunch && workerAttempt && workerMemoryProfileBinding && ownership.identity.file) {
747
+ try {
748
+ if (!workerMemoryProfileAttempted) {
749
+ workerMemoryProfileAttempted = true;
750
+ const { id, file } = ownership.identity;
751
+ const paths = await bindNativeProfile(pi.pi, {
752
+ agentDir: session.settings.getAgentDir(), id, file,
753
+ }, workerMemoryProfileBinding);
754
+ assertSameRoot(ownership.identity);
755
+ workerMemoryProfile = { root: ownership.identity, paths };
756
+ } else assertSameRoot(ownership.identity);
757
+ const source = currentWorkerMemory(ownership.identity);
758
+ if (source) {
759
+ source.validate();
760
+ workerMemoryControlVersion = 1;
761
+ }
762
+ } catch (error) {
763
+ // An unavailable bank does not make ordinary observations unavailable.
764
+ if (!(error instanceof Error)) throw error;
765
+ }
766
+ }
691
767
  const wakes = session.wakeSources;
692
768
  const running = process.env.OMP_SUPERAGENT_ROLE === "head" && ownership.tree
693
769
  ? ownership.tree.running.filter(job => job.ownerId === ref.id) : undefined;
@@ -708,6 +784,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
708
784
  ? session.effectiveServiceTier(session.model) ?? "none" : undefined,
709
785
  } : {}),
710
786
  journalCursorControlVersion: 1,
787
+ ...(workerMemoryControlVersion && { workerMemoryControlVersion }),
711
788
  ...(replyVoice?.available() ? { replyVoiceControlVersion: 2 } : {}),
712
789
  ...(running ? { headJobs: { running: running.map(job => job.id), awaitingOnly } } : {}),
713
790
  fastMode: headFastMode(ownership.identity.session),
@@ -870,6 +947,33 @@ export default function hostExtension(pi: ExtensionAPI): void {
870
947
  pi.on("agent_start", () => {
871
948
  if (context?.agent.kind === "main") observation("rpc_agent_start", { runOrdinal: ++runOrdinal, hostPid: process.pid });
872
949
  });
950
+ const observeWorkerFact = (tool: string, ctx: ExtensionContext, observe: (source: NonNullable<typeof workerMemory>,
951
+ name: WorkerFactCarrier) => void, input?: unknown) => {
952
+ if (!workerMemoryProfile || (tool !== "retain" && tool !== "learn" && tool !== "bash")
953
+ || ctx.agent.kind !== "main" || ctx.agent.id !== pi.pi.MAIN_AGENT_ID
954
+ || (!workerMemory && !canBeginWorkerFact(tool, input))) return;
955
+ try {
956
+ const identity = exact();
957
+ if (!isWorkerFactRoot(ctx, pi.pi.MAIN_AGENT_ID, identity.session.sessionManager)
958
+ || !identity.session.getAllToolInfos().some(info =>
959
+ info.name === tool && info.sourceInfo.source === "builtin" && info.sourceInfo.path === `<builtin:${tool}>`)) return;
960
+ const source = currentWorkerMemory(identity);
961
+ if (source) observe(source, tool);
962
+ } catch (error) {
963
+ // Attestation is optional and cannot change the native tool's outcome.
964
+ if (!(error instanceof Error)) throw error;
965
+ workerMemory?.clearFactStarts();
966
+ }
967
+ };
968
+ pi.on("tool_execution_start", (event, ctx) => {
969
+ observeWorkerFact(event.toolName, ctx, (source, tool) => source.startFact(tool, event.toolCallId, event.args), event.args);
970
+ });
971
+ pi.on("tool_execution_end", (event, ctx) => {
972
+ observeWorkerFact(event.toolName, ctx, (source, tool) => source.finishFact(tool, event.toolCallId, !event.isError, event.result));
973
+ });
974
+ pi.on("agent_end", (_event, ctx) => {
975
+ if (ctx.agent.kind === "main" && ctx.agent.id === pi.pi.MAIN_AGENT_ID) workerMemory?.clearFactStarts();
976
+ });
873
977
  pi.on("tool_call", async (event, ctx) => {
874
978
  if (reviewCwd) return { block: true, reason: "Static PR review does not execute tools" };
875
979
  const input = event.input as Frame;
@@ -927,6 +1031,8 @@ export default function hostExtension(pi: ExtensionAPI): void {
927
1031
  notDispatched ? "not_dispatched" : undefined);
928
1032
  });
929
1033
  pi.on("tool_result", async (event, ctx) => {
1034
+ if (!event.isError && event.parentToolCallId === undefined)
1035
+ observeWorkerFact(event.toolName, ctx, (source, toolName) => source.returnFact({ ...event, toolName }), event.input);
930
1036
  const owner = serviceOwner(ctx);
931
1037
  const key = JSON.stringify([owner, event.toolCallId]);
932
1038
  const start = serviceStarts.get(key);
@@ -1028,6 +1134,7 @@ export default function hostExtension(pi: ExtensionAPI): void {
1028
1134
  });
1029
1135
  pi.on("session_shutdown", async () => {
1030
1136
  if (!context || context.agent.kind !== "main") return;
1137
+ workerMemory?.close();
1031
1138
  server?.close();
1032
1139
  await fs.unlink(socketPath).catch(error => { if (error.code !== "ENOENT") throw error; });
1033
1140
  });
@@ -17,6 +17,7 @@ type Manifest = {
17
17
  readonly headRotationSelection?: RotationSelection;
18
18
  readonly headHibernationSessionId?: string;
19
19
  readonly expectedNativeProfile?: NativeProfile;
20
+ readonly workerMemoryProfile?: NativeProfile;
20
21
  };
21
22
 
22
23
  async function run(operation: string | undefined, manifest: Manifest, input: unknown, nativeProfile?: NativeProfile) {
@@ -130,6 +131,7 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
130
131
  if (options.prReviewOnly) await chmod(options.sessionFile, 0o600);
131
132
  }
132
133
  let nativeProfileBinding: NativeProfileBinding | undefined;
134
+ let workerMemoryProfileBinding: NativeProfileBinding | undefined;
133
135
  if (!options.prReviewOnly) {
134
136
  requireNativeProfile();
135
137
  const discoveryEntry = await publishNativeSession(options.sessionFile, options.cwd, parkedSession, nativeProfile);
@@ -137,10 +139,13 @@ async function run(operation: string | undefined, manifest: Manifest, input: unk
137
139
  if (!discoveryEntry) throw new Error("Prepared native session could not be found in discovery");
138
140
  nativeProfileBinding = { profile: nativeProfile, discoveryEntry };
139
141
  }
142
+ if (manifest.workerMemoryProfile && discoveryEntry
143
+ && matchesNativeProfile(sdkNativeProfilePaths(), manifest.workerMemoryProfile))
144
+ workerMemoryProfileBinding = { profile: manifest.workerMemoryProfile, discoveryEntry };
140
145
  }
141
146
  const { hostInventoryManifest } = await import("./omp/host-inventory-manifest");
142
147
  return { toolsExplicitlySelected: parsed.tools !== undefined, noTools: parsed.noTools === true,
143
- nativeProfileBinding,
148
+ nativeProfileBinding, workerMemoryProfileBinding,
144
149
  replayableArgvHash: argv.argv[0] === "launch" && !stockReplayRefusal(parsed, options.sessionFile)
145
150
  ? launchArgvHash(launchArgs) : undefined,
146
151
  ...(options.prReviewOnly ? { emptyToolSelection } : {}),
@@ -22,11 +22,10 @@ export function registerDecisionAsk(pi: ExtensionAPI): void {
22
22
  pi.registerTool({
23
23
  name: "decision_ask", label: "Request a tracked decision", approval: "read", loadMode: "essential",
24
24
  description: (role === "lane"
25
- ? "Use to: \"head\" for an in-scope coordination choice that needs HEAD's answer, even from a work topic. " +
25
+ ? "Use to: \"head\" for a coordination choice that needs HEAD's answer, even from a work topic. " +
26
26
  "Omit to for the normal recipient (topic: owner; manager handoff: HEAD). " +
27
27
  "HEAD may select an original option or escalate the same question to the owner. " +
28
- "On corrective assignments, to: \"head\" is cancelled privately, not sent to the owner. " +
29
- "An answer never grants execution approval or changes scope. "
28
+ "An answer never grants execution approval or authority to change the assignment. "
30
29
  : "Ask the owner structured questions on this managed session's native UI. ") +
31
30
  "Returns a stable decision id and the actual submitted answers or cancellation, timeout, or chat state. Recommendations, timeouts and chat are not acceptance. No default answers, route override, or automatic work resume.",
32
31
  parameters: Type.Object({
@@ -1,5 +1,4 @@
1
1
  import { isAbsolute, normalize } from "node:path";
2
- import { isDeepStrictEqual } from "node:util";
3
2
 
4
3
  export type LaneWaitTarget =
5
4
  | { kind: "tool" | "approval" | "job"; id: string; target: string }
@@ -25,27 +24,6 @@ export interface LaneReportEvent {
25
24
  report: LaneReport;
26
25
  }
27
26
 
28
- /** Evidence of a tool execution only; it does not authorize a scope change. */
29
- export type ScopeReviewReceipt = {
30
- readonly type: "superagent-scope-review";
31
- readonly sourceId: string;
32
- readonly sessionId: string;
33
- readonly sessionFile: string;
34
- readonly toolCallId: string;
35
- };
36
-
37
- /** Stock OMP select wire for this tool. A positive answer describes this call
38
- * only; the native Host, not the controller, handles any session-wide choice. */
39
- export function scopeReviewApproval(request: Record<string, unknown>, response?: { value?: string }): boolean {
40
- if (request.method !== "select" || request.secret === true) return false;
41
- const options = request.options;
42
- const session = "Approve lane_report for this session";
43
- if (!isDeepStrictEqual(options, ["Approve", "Deny"]) && !isDeepStrictEqual(options, ["Approve", session, "Deny"])) return false;
44
- if (!response) return true;
45
- return isDeepStrictEqual(response, { value: "Approve" })
46
- || Array.isArray(options) && options.includes(session) && isDeepStrictEqual(response, { value: session });
47
- }
48
-
49
27
  export function laneWaitKey(waiting: LaneWaitTarget): string {
50
28
  return JSON.stringify([waiting.kind, waiting.kind === "dependency" ? waiting.target : waiting.id]);
51
29
  }
@@ -56,6 +34,13 @@ const text = (value: unknown): value is string => typeof value === "string" && v
56
34
  const keys = (value: Record<string, unknown>, names: string[]) =>
57
35
  Object.keys(value).every(key => names.includes(key));
58
36
 
37
+ export function isLaneWaitTarget(value: unknown): value is LaneWaitTarget {
38
+ return record(value) && text(value.target) && (value.kind === "dependency"
39
+ ? keys(value, ["kind", "target"])
40
+ : ["tool", "approval", "job"].includes(value.kind as string) &&
41
+ keys(value, ["kind", "id", "target"]) && text(value.id));
42
+ }
43
+
59
44
  /** Parse only the structured native result, never receipt text or a claimed event in content. */
60
45
  export function parseLaneReportResult(result: unknown): LaneReportEvent | null {
61
46
  try {
@@ -76,14 +61,7 @@ export function parseLaneReportResult(result: unknown): LaneReportEvent | null {
76
61
  if (report.status !== "waiting" && report.evidence.length === 0) return null;
77
62
  if (report.status === "progress") {
78
63
  if (Object.hasOwn(report, "waiting")) return null;
79
- } else {
80
- const waiting = report.waiting;
81
- if (!record(waiting) || !text(waiting.target)) return null;
82
- if (waiting.kind === "dependency") {
83
- if (!keys(waiting, ["kind", "target"])) return null;
84
- } else if (!["tool", "approval", "job"].includes(waiting.kind as string) ||
85
- !text(waiting.id) || !keys(waiting, ["kind", "id", "target"])) return null;
86
- }
64
+ } else if (!isLaneWaitTarget(report.waiting)) return null;
87
65
  return event as unknown as LaneReportEvent;
88
66
  } catch {
89
67
  // Malformed native details must not escape into the head's event loop.
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
  import { isAbsolute, normalize } from "node:path";
3
- import { Type } from "@sinclair/typebox";
3
+ import { Type } from "@sinclair/typebox/type";
4
4
  import { Value } from "@sinclair/typebox/value";
5
5
  import type { Lane } from "../contracts";
6
6
  import type { RemotePlacement } from "../worker/worker-wire";
@@ -1,4 +1,4 @@
1
- import { WORKFLOW_NAMES, type InputRecord, type WorkflowActivation, type WorkflowChoice, type WorkflowName } from "../contracts";
1
+ import { WORKFLOW_NAMES, type Inbound, type InputRecord, type WorkflowActivation, type WorkflowChoice, type WorkflowName } from "../contracts";
2
2
 
3
3
  // Public commands and leading delimiters match omp-superkit ulw.ts at c11a6e4.
4
4
  // Skill paths and persisted native keys are deliberately not public selectors.
@@ -47,11 +47,52 @@ function invocation(text: string): { name: WorkflowName; length: number; legacy?
47
47
  return { name: "super", length: prefix + plain[0].length, legacy: true };
48
48
  }
49
49
 
50
- export function leadingWorkflow(text: string): WorkflowName | null {
50
+ function leadingInvocation(text: string) {
51
51
  const match = invocation(text);
52
52
  // Upstream masks URLs before reading its SUPER/ULW selectors. Do not
53
53
  // accidentally admit one just because a real command may use a colon.
54
- return match && (match.name === "jevify" || !leadingUri.test(text)) ? match.name : null;
54
+ return match && (match.name === "jevify" || !leadingUri.test(text)) ? match : null;
55
+ }
56
+
57
+ export function leadingWorkflow(text: string): WorkflowName | null {
58
+ return leadingInvocation(text)?.name ?? null;
59
+ }
60
+
61
+ /** Telegram's entity view can corroborate a written selector, but cannot supply one. */
62
+ export function ownerWorkflowRequest(input: Inbound, task: string): {
63
+ readonly name: WorkflowName | null;
64
+ readonly projection?: { readonly text: string; readonly selectorChanged: boolean };
65
+ } {
66
+ if (input.route.platform !== "telegram" || input.pickerSelection || input.routingText === input.text)
67
+ return { name: leadingWorkflow(task) };
68
+
69
+ // Remove only the wrapper parsed from the genuine request. Parsing a new
70
+ // /head, /new or cwd header exposed by redaction could also expose a selector.
71
+ const written = leadingInvocation(task);
72
+ const prefix = input.text.slice(0, input.text.length - task.length);
73
+ const view = input.routingText ?? "";
74
+ const aligned = view.startsWith(prefix);
75
+ const body = aligned ? view.slice(prefix.length) : view;
76
+ const visible = leadingInvocation(body);
77
+ const selector = task.slice(0, written?.length ?? 0);
78
+ const exact = aligned && written && visible && visible.name === written.name
79
+ && body.slice(0, visible.length) === selector;
80
+ if (exact) {
81
+ // The adapter attests the first slash token, but prose (or a selector
82
+ // after a wrapper) can be ambiguous if redaction exposed a repeated word.
83
+ // CR/LF survive redaction, so only the rest of the same line can stand in for it.
84
+ const directSlash = !prefix && input.telegramProtectedCommand === false && /^\/\S+$/u.test(selector.trimStart());
85
+ const finalWord = /\S+$/u.exec(selector)?.[0];
86
+ const sameLine = /^[^\r\n]*/u.exec(task.slice(selector.length))?.[0];
87
+ if (directSlash || !finalWord || !sameLine?.includes(finalWord)) {
88
+ return { name: written.name, projection: { text: body, selectorChanged: false } };
89
+ }
90
+ }
91
+ return {
92
+ name: null,
93
+ // In particular, a revealed jevify must not reach the native prose matcher.
94
+ projection: { text: visible ? body.slice(visible.length) : body, selectorChanged: Boolean(written || visible) },
95
+ };
55
96
  }
56
97
 
57
98
  /** Read old coordination identities without making aliases valid manager inputs. */
@@ -4,7 +4,7 @@ import { resolve } from "node:path";
4
4
  import type { ToolCall, ToolResultMessage } from "@oh-my-pi/pi-ai";
5
5
  import type { ExtensionAPI, ExtensionContext } from "@oh-my-pi/pi-coding-agent";
6
6
  import { type Static, Type } from "@sinclair/typebox";
7
- import { type LaneEvidence, type LaneReportEvent, type ScopeReviewReceipt, parseLaneReportResult } from "./lane/lane-report";
7
+ import { isLaneWaitTarget, type LaneEvidence, type LaneReportEvent, parseLaneReportResult } from "./lane/lane-report";
8
8
  import { registerResultAttach, RESULT_ATTACH_TOOL } from "./messaging/result-attachment";
9
9
  import { registerDecisionAsk } from "./lane/decision-tool";
10
10
 
@@ -29,7 +29,6 @@ const parameters = Type.Union([
29
29
  { additionalProperties: false }),
30
30
  Type.Object({ status: Type.Literal("resolved"), summary, waiting, evidence: requiredEvidence },
31
31
  { additionalProperties: false }),
32
- Type.Object({ status: Type.Literal("scope_review"), sourceId: nonempty }, { additionalProperties: false }),
33
32
  ]);
34
33
  // Resumed native journals can still contain retired board tools. They were never work evidence.
35
34
  const coordinationTool = (name: string) =>
@@ -43,10 +42,6 @@ const keys = (value: Record<string, unknown>, names: string[]) =>
43
42
  // Direct native/custom-tool dispatch can bypass model argument validation.
44
43
  function validInput(input: unknown): input is Static<typeof parameters> {
45
44
  if (!record(input)) return false;
46
- if (input.status === "scope_review") {
47
- return Object.hasOwn(input, "status") && Object.hasOwn(input, "sourceId") &&
48
- keys(input, ["status", "sourceId"]) && text(input.sourceId);
49
- }
50
45
  if (!keys(input, ["status", "summary", "waiting", "evidence"]) ||
51
46
  !text(input.summary) || input.summary.length > 4000 ||
52
47
  !["progress", "waiting", "resolved"].includes(input.status as string)) return false;
@@ -56,11 +51,7 @@ function validInput(input: unknown): input is Static<typeof parameters> {
56
51
  : item.kind !== "tool" || !keys(item, ["kind", "toolCallId"]) || !text(item.toolCallId))))) return false;
57
52
  if (input.status !== "waiting" && (!Array.isArray(input.evidence) || input.evidence.length === 0)) return false;
58
53
  if (input.status === "progress") return !Object.hasOwn(input, "waiting");
59
- const target = input.waiting;
60
- return record(target) && text(target.target) && (target.kind === "dependency"
61
- ? keys(target, ["kind", "target"])
62
- : ["tool", "approval", "job"].includes(target.kind as string) &&
63
- keys(target, ["kind", "id", "target"]) && text(target.id));
54
+ return isLaneWaitTarget(input.waiting);
64
55
  }
65
56
 
66
57
  function fileEvidence(path: string, cwd: string): LaneEvidence {
@@ -119,8 +110,7 @@ function toolEvidence(id: string, records: ReturnType<typeof toolRecords>): Lane
119
110
  if (!call || !result || result.toolName !== call.name || result.isError !== false ||
120
111
  coordinationTool(call.name) || (typeof call.arguments.path === "string" &&
121
112
  /^xd:\/\/(?:lane_report|board_[a-z_]+)(?:[/?#]|$)/.test(call.arguments.path)) ||
122
- parseLaneReportResult(result) || (record(result.details) && result.details.type === "superagent-scope-review") ||
123
- transportedCoordination(call, result)) {
113
+ parseLaneReportResult(result) || transportedCoordination(call, result)) {
124
114
  throw new Error("Lane tool evidence requires a completed successful native tool call, not a coordination receipt");
125
115
  }
126
116
  // Native identity/time envelopes are not evidence of changed work.
@@ -148,12 +138,10 @@ export default function laneExtension(pi: ExtensionAPI): void {
148
138
  registerResultAttach(pi);
149
139
  let approvalSessionId: string | undefined;
150
140
  const pendingApprovals = new Set<string>();
151
- const scopeApprovals = new Map<string, "requested" | "approved" | "unverified">();
152
141
  const approvals = (ctx: ExtensionContext) => {
153
142
  const sessionId = ctx.sessionManager.getSessionId();
154
143
  if (approvalSessionId !== sessionId) {
155
144
  pendingApprovals.clear();
156
- scopeApprovals.clear();
157
145
  approvalSessionId = sessionId;
158
146
  }
159
147
  return pendingApprovals;
@@ -178,22 +166,13 @@ export default function laneExtension(pi: ExtensionAPI): void {
178
166
  pi.on("tool_approval_requested", (event, ctx) => {
179
167
  if (ctx.agent.kind === "main" && event.sessionId === ctx.sessionManager.getSessionId()) {
180
168
  approvals(ctx).add(event.toolCallId);
181
- if (event.toolName === "lane_report")
182
- scopeApprovals.set(event.toolCallId, scopeApprovals.has(event.toolCallId) ? "unverified" : "requested");
183
169
  }
184
170
  });
185
171
  pi.on("tool_approval_resolved", (event, ctx) => {
186
172
  if (event.sessionId !== ctx.sessionManager.getSessionId()) return;
187
173
  approvals(ctx).delete(event.toolCallId);
188
- if (ctx.agent.kind === "main" && event.toolName === "lane_report")
189
- scopeApprovals.set(event.toolCallId,
190
- event.approved && scopeApprovals.get(event.toolCallId) === "requested" ? "approved" : "unverified");
191
- });
192
- pi.on("agent_end", (_event, ctx) => { if (ctx.agent.kind === "main") scopeApprovals.clear(); });
193
- pi.on("session_shutdown", () => {
194
- pendingApprovals.clear();
195
- scopeApprovals.clear();
196
174
  });
175
+ pi.on("session_shutdown", () => { pendingApprovals.clear(); });
197
176
  pi.on("before_agent_start", async (event, ctx) => {
198
177
  if (ctx.agent.kind !== "main") return;
199
178
  return { systemPrompt: [
@@ -209,31 +188,11 @@ export default function laneExtension(pi: ExtensionAPI): void {
209
188
  "Decision receipts and other coordination activity are not evidence of work. " +
210
189
  "Waiting/resolved name the exact tool/approval/job ID or a dependency label. Native tool/approval/job waiting IDs must be observable now. " +
211
190
  "Topic observations do not notify HEAD. For manager handoffs, changed evidence or wait transitions are queued for HEAD. " +
212
- "For a standalone original owner message in the active bound topic that appears to supersede the existing assignment, " +
213
- "call lane_report directly with status scope_review and its Original source ID, never via eval, bash, or write. " +
214
- "This only requests HEAD review; it does not grant permission. " +
215
191
  "Reports do not themselves send messenger messages, prove acceptance, dispatch, resume, or change execution authority.",
216
192
  parameters,
217
- async execute(id, params, signal, _onUpdate, ctx) {
193
+ async execute(id, params, _signal, _onUpdate, ctx) {
218
194
  if (ctx.agent.kind !== "main") throw new Error("Lane reporting is restricted to the root lane session");
219
195
  if (!validInput(params)) throw new Error("Invalid lane report parameters");
220
- approvals(ctx);
221
- const nativeApproval = scopeApprovals.get(id);
222
- scopeApprovals.delete(id);
223
- if (params.status === "scope_review") {
224
- signal?.throwIfAborted();
225
- const sessionFile = ctx.sessionManager.getSessionFile();
226
- if (!sessionFile) throw new Error("Lane scope review requires a native session file");
227
- const receipt: ScopeReviewReceipt = {
228
- type: "superagent-scope-review", sourceId: params.sourceId,
229
- sessionId: ctx.sessionManager.getSessionId(), sessionFile, toolCallId: id,
230
- };
231
- // Only a matched direct native start/end can request review. Do not append a custom entry.
232
- return {
233
- content: [{ type: "text", text: "Emitted a scope-review signal. HEAD admission depends on controller verification and successful settlement; the assignment has not changed." }],
234
- details: nativeApproval === undefined ? receipt : { ...receipt, nativeApproval },
235
- };
236
- }
237
196
  const target = params.status === "waiting" ? params.waiting : undefined;
238
197
  if (target?.kind === "approval" && !approvals(ctx).has(target.id)) {
239
198
  throw new Error("Lane approval wait requires an observed pending native tool approval");
@@ -88,31 +88,33 @@ function state(store: Metadata): Purposes {
88
88
  return parsed;
89
89
  }
90
90
 
91
- export function discordPurposeNotes(store: Metadata, route: Route): readonly DiscordPurposeNote[] {
92
- const notes = state(store).notes;
91
+ function notesForRoute(notes: Purposes["notes"], route: Route): readonly DiscordPurposeNote[] {
93
92
  const parent = { ...physicalRoute(route), threadId: null };
94
93
  const keys = [...new Set([physicalRouteKey(parent), physicalRouteKey(route)])];
95
94
  return keys.flatMap(key => notes[key] ? [notes[key]] : []);
96
95
  }
97
96
 
97
+ export function discordPurposeNotes(store: Metadata, route: Route): readonly DiscordPurposeNote[] {
98
+ return notesForRoute(state(store).notes, route);
99
+ }
100
+
98
101
  /** One synchronous metadata write atomically preserves the note and its source-bound receipt. */
99
102
  export function changeDiscordPurpose(store: Metadata, request: DiscordPurposeRequest): readonly DiscordPurposeNote[] {
100
103
  if (request.action === "list") return discordPurposeNotes(store, request.route);
101
104
  const previous = state(store);
102
- const receiptKey = JSON.stringify([request.sourceId, physicalRouteKey(request.route)]);
105
+ const key = physicalRouteKey(request.route);
106
+ const receiptKey = JSON.stringify([request.sourceId, key]);
103
107
  const saved = previous.receipts[receiptKey];
104
108
  if (saved) {
105
109
  if (!isDeepStrictEqual(saved.request, request)) throw new DeliveryError("Discord purpose source identity conflict", "rejected");
106
110
  return saved.result;
107
111
  }
108
112
  const notes = { ...previous.notes };
109
- const key = physicalRouteKey(request.route);
110
113
  switch (request.action) {
111
114
  case "set": notes[key] = { route: physicalRoute(request.route), purpose: request.purpose }; break;
112
115
  case "clear": delete notes[key]; break;
113
116
  }
114
- const parent = { ...physicalRoute(request.route), threadId: null };
115
- const result = [...new Set([physicalRouteKey(parent), key])].flatMap(id => notes[id] ? [notes[id]] : []);
117
+ const result = notesForRoute(notes, request.route);
116
118
  store.setMeta(PURPOSES, JSON.stringify({ notes, receipts: { ...previous.receipts, [receiptKey]: { request, result } } }));
117
119
  return result;
118
120
  }
@@ -0,0 +1,36 @@
1
+ import { authorizeRoute, type Config } from "../config/config";
2
+ import { routeKey, type Route, type StorePort } from "../contracts";
3
+ import { groupRoom } from "../group/group-policy";
4
+
5
+ export function guildThreadParent(config: Config, source: Route, parent: Route): boolean {
6
+ return config.discord?.allowCrossChannelThreads === true && config.discord.crossChannelThreadScope === "guild"
7
+ && source.platform === "discord" && parent.platform === "discord" && source.guildId !== null
8
+ && source.guildId === parent.guildId && source.accountId === parent.accountId && source.authorityId === parent.authorityId
9
+ && source.channelId !== parent.channelId && parent.threadId === null && parent.topicId === undefined
10
+ && authorizeRoute(config, source) && !groupRoom(config, parent);
11
+ }
12
+
13
+ export function discordWorkThreadKey(threadId: string): string {
14
+ // Gateway reads the same exact source and thread receipt from SQLite.
15
+ return `discord:work-thread:${threadId}`;
16
+ }
17
+
18
+ export function discordWorkThreadOwnerKey(inputId: string): string {
19
+ return `discord:work-thread-owner:${inputId}`;
20
+ }
21
+
22
+ /** Read the exact placement receipt without making it current authorization. */
23
+ export function recordedDiscordWorkThreadSource(store: Pick<StorePort, "getMeta">, route: Route): Route | null {
24
+ if (route.platform !== "discord" || !route.threadId || route.topicId !== undefined) return null;
25
+ const saved = store.getMeta(discordWorkThreadKey(route.threadId));
26
+ if (!saved) return null;
27
+ const binding: { source: Route; route: Route } = JSON.parse(saved);
28
+ return routeKey(binding.route) === routeKey(route) ? binding.source : null;
29
+ }
30
+
31
+ /** Delivery authority for a confirmed native lane thread, never request ingress. */
32
+ export function discordWorkThreadSource(config: Config, store: Pick<StorePort, "getMeta">, route: Route): Route | null {
33
+ if (config.discord?.crossChannelThreadScope !== "guild" || config.discord.allowCrossChannelThreads !== true) return null;
34
+ const source = recordedDiscordWorkThreadSource(store, route);
35
+ return source && guildThreadParent(config, source, { ...route, threadId: null }) ? source : null;
36
+ }
@@ -31,6 +31,7 @@ export type HostState = RpcSessionState & {
31
31
  readonly loadedSuperkitPath?: string;
32
32
  readonly prReviewPolicy?: { readonly version: 1; readonly cwd: string; readonly modelApi: string };
33
33
  readonly journalCursorVersion?: 1;
34
+ readonly memorySyncVersion?: 1;
34
35
  readonly replyVoiceVersion?: 1 | 2;
35
36
  readonly fastMode?: FastModeState;
36
37
  readonly serviceTier?: Readonly<ServiceTierByFamily>;
@@ -70,7 +71,7 @@ export const serviceGenerationKey = (value: Frame | ServiceUnit) =>
70
71
  const hasValidGeneration = (daemon: Frame | ServiceUnit) =>
71
72
  !("generation" in daemon) || typeof daemon.generation === "string" && daemon.generation.length > 0;
72
73
  const isFrame = (value: unknown): value is Frame => value !== null && typeof value === "object";
73
- const isTerminal = (state: unknown): state is "exited" | "failed" => state === "exited" || state === "failed";
74
+ export const terminalService = (state: unknown): state is "exited" | "failed" => state === "exited" || state === "failed";
74
75
 
75
76
  function launchCompletions(value: unknown): readonly unknown[] | undefined {
76
77
  if (!isFrame(value) || value.type !== "custom_message" || value.customType !== "launch-completion") return;
@@ -98,7 +99,7 @@ export function indexServiceCompletions(entries: readonly unknown[]) {
98
99
  for (const observed of daemons) {
99
100
  // The historical generation lookup could not cross an unreadable row.
100
101
  if (observed === null || observed === undefined) generationEvidenceBlocked = true;
101
- if (!isFrame(observed) || !isTerminal(observed.state)) continue;
102
+ if (!isFrame(observed) || !terminalService(observed.state)) continue;
102
103
  const key = serviceExitKey(observed);
103
104
  if (key === undefined) continue;
104
105
  exact[observed.state].add(key);
@@ -108,7 +109,7 @@ export function indexServiceCompletions(entries: readonly unknown[]) {
108
109
  return {
109
110
  hasGeneration: (key: string) => byGeneration.has(key),
110
111
  hasCompletion: (daemon: Frame | ServiceUnit) => {
111
- if (!isTerminal(daemon.state) || !hasValidGeneration(daemon)) return false;
112
+ if (!terminalService(daemon.state) || !hasValidGeneration(daemon)) return false;
112
113
  const key = serviceExitKey(daemon);
113
114
  return key !== undefined && exact[daemon.state].has(key);
114
115
  },