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
package/src/omp/host.ts CHANGED
@@ -16,6 +16,7 @@ import { requireHostOwner } from "./host-owner-path";
16
16
  import { inspectInstalledOmp, resolveOmpCommand } from "./installed-omp";
17
17
  import type { DialogResponse, LanePresetSnapshot } from "../contracts";
18
18
  import type { WorkerHostProfile } from "../worker/worker-profile";
19
+ import { WORKER_MEMORY_PROFILE_ENV, type WorkerMemoryBinding } from "../worker/worker-memory-storage";
19
20
  import { activeManagedUlw, managedUlwLaunch, MANAGED_ULW_ENV, MANAGED_ULW_FIXTURE_ENV, MANAGED_ULW_FIXTURE_ROOT_ENV, validateManagedUlwPackage } from "./managed-super";
20
21
 
21
22
  const CONNECT_TIMEOUT_MS = 5_000;
@@ -390,7 +391,7 @@ function selectManagedUlw(options: HostOptions): string {
390
391
  }
391
392
 
392
393
  /** Launch only a new host. Existing endpoints require the caller's explicit adoption decision. */
393
- export async function startHost(options: HostOptions, beforeSessionPrepare?: () => void): Promise<{ pid: number }> {
394
+ export async function startHost(options: HostOptions, beforeSessionPrepare?: (memory?: WorkerMemoryBinding) => void): Promise<{ pid: number }> {
394
395
  try { return await launchHost(options, beforeSessionPrepare); }
395
396
  catch (cause) {
396
397
  // Never read child output into errors: logs can contain credentials or prompt content.
@@ -398,7 +399,7 @@ export async function startHost(options: HostOptions, beforeSessionPrepare?: ()
398
399
  }
399
400
  }
400
401
 
401
- async function launchHost(options: HostOptions, beforeSessionPrepare?: () => void): Promise<{ pid: number }> {
402
+ async function launchHost(options: HostOptions, beforeSessionPrepare?: (memory?: WorkerMemoryBinding) => void): Promise<{ pid: number }> {
402
403
  // Snapshot once before any awaits; an updater may activate a newer revision
403
404
  // during startup, but this Host must load one exact immutable package.
404
405
  if (options.prReviewOnly) {
@@ -461,7 +462,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
461
462
  const cleanLaunch = () => cleanup ??= fs.rm(launchDirectory, { recursive: true });
462
463
  try {
463
464
  const initialSettings = options.modelPreset?.preset ?? options.modelSettings;
464
- await fs.writeFile(configPath, JSON.stringify({
465
+ const hostSettings = {
465
466
  ...options.worker?.config,
466
467
  task: { maxConcurrency: options.subagentConcurrency },
467
468
  goal: { continuationModes: [RPC_GOAL_CONTINUATION_MODE] },
@@ -475,7 +476,8 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
475
476
  ...(initialSettings.defaultThinkingLevel !== undefined
476
477
  ? { defaultThinkingLevel: initialSettings.defaultThinkingLevel } : {}),
477
478
  } : options.model ? { modelRoles: { default: options.model } } : {}),
478
- }), { flag: "wx", mode: 0o600 });
479
+ };
480
+ await fs.writeFile(configPath, JSON.stringify(hostSettings), { flag: "wx", mode: 0o600 });
479
481
  log = await fs.open(options.logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
480
482
  const stat = await log.stat();
481
483
  if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) {
@@ -485,6 +487,7 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
485
487
  const { env: _inheritedEnvironment, worker: _workerProfile, ...launchOptions } = options;
486
488
  const helperPath = fileURLToPath(new URL("../host-sdk-helper.ts", import.meta.url));
487
489
  let manifest: Record<string, unknown> | undefined;
490
+ let workerMemory: { binding: WorkerMemoryBinding; env: Record<string, string> } | undefined;
488
491
  const extensionPaths = managedUlwPath === undefined ? [] : [fileURLToPath(new URL("../../", import.meta.url)),
489
492
  managedUlwPath, options.extensionPath,
490
493
  fileURLToPath(new URL("../host-extension.ts", import.meta.url))];
@@ -493,13 +496,26 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
493
496
  // is sent. Preparation and owner startup share the same deadline.
494
497
  const { composition, prepared, deadline } = await managedUlwLaunch({ cwd: options.cwd, managedUlwPath,
495
498
  extensionPaths, configPath, parentConfigPath: process.env.OMP_SUPERAGENT_HOST_CONFIG, commandArgs: options.command.slice(1),
496
- ...(options.worker ? { worker: { extensionPaths: options.worker.extensionPaths } } : {}),
499
+ ...(options.worker ? { worker: { extensionPaths: options.worker.extensionPaths, memory: options.worker.memory } } : {}),
497
500
  launchArgs: managedUlwPath === undefined ? [] : [...options.command.slice(1), ...await buildHostArgs(options, configPath)],
498
501
  env: options.env, bunCommand: [bun, "--no-env-file"] }, {
499
- stderr: log.fd, timeoutMs: START_TIMEOUT_MS, beforeManifest: beforeSessionPrepare,
502
+ stderr: log.fd, timeoutMs: START_TIMEOUT_MS, beforeManifest: () => beforeSessionPrepare?.(workerMemory?.binding),
500
503
  manifest: async composition => {
504
+ if (options.worker?.memory?.previous && !composition.workerMemory && !composition.workerMemoryDormant)
505
+ throw new Error("Worker memory cannot resume without its verified private bank");
506
+ if (composition.workerMemory && options.worker?.memory) {
507
+ const { prepareWorkerMemory } = await import("../worker/worker-memory-storage");
508
+ const privateMemory = prepareWorkerMemory(options.worker.memory, options, composition.workerMemory);
509
+ // Discovery verified the actual native backend and scope with no overlay
510
+ // override. Only redirect the opted-in native bank before journal preparation.
511
+ const overlay = await fs.open(configPath, constants.O_WRONLY | constants.O_NOFOLLOW | constants.O_TRUNC);
512
+ try { await overlay.writeFile(JSON.stringify({ ...hostSettings, ...privateMemory.config })); }
513
+ finally { await overlay.close(); }
514
+ workerMemory = privateMemory;
515
+ }
501
516
  manifest = { options: launchOptions, args: await buildHostArgs(options, configPath, composition), configPath,
502
517
  memoryWriteDir: composition.memoryWriteDir, processBackend, helperPath,
518
+ ...(workerMemory && { workerMemoryProfile: composition.workerMemory?.profile }),
503
519
  nativeSocket: path.join(path.dirname(options.socketPath), `.n-${crypto.randomUUID().slice(0, 8)}.sock`) };
504
520
  return manifest;
505
521
  },
@@ -519,7 +535,8 @@ async function launchHost(options: HostOptions, beforeSessionPrepare?: () => voi
519
535
  inventory: flags.inventory, nativeProfileBinding: flags.nativeProfileBinding, replayableArgvHash: flags.replayableArgvHash }), { flag: "wx", mode: 0o600 });
520
536
  if (performance.now() >= deadline) throw new Error("Native Host startup timed out before launch");
521
537
  child = spawn(hostOwnerExecutable, [manifestPath], {
522
- cwd: options.cwd, env: options.env,
538
+ cwd: options.cwd, env: workerMemory ? { ...options.env, ...workerMemory.env,
539
+ [WORKER_MEMORY_PROFILE_ENV]: JSON.stringify(flags.workerMemoryProfileBinding ?? null) } : options.env,
523
540
  detached: true, stdio: ["ignore", log.fd, log.fd], shell: false,
524
541
  });
525
542
  child.once("error", error => { failure = error; });
@@ -4,6 +4,7 @@ import { chmod, link, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename
4
4
  import { dirname, isAbsolute, join, resolve, sep } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import type { WorkerHostProfile } from "../worker/worker-profile";
7
+ import type { WorkerMemoryPlan } from "../worker/worker-memory-storage";
7
8
  import type { NativeProfile, NativeProfileBinding, NativeProfilePaths } from "./native-sessions";
8
9
 
9
10
  const projectRoot = fileURLToPath(new URL("../../", import.meta.url));
@@ -200,7 +201,7 @@ export type ManagedUlwLaunchInput = {
200
201
  commandArgs: string[];
201
202
  /** Exact native OMP argv, including the original command's flags and generated Host args; no executable prefix. */
202
203
  launchArgs: string[];
203
- worker?: Pick<WorkerHostProfile, "extensionPaths">;
204
+ worker?: Pick<WorkerHostProfile, "extensionPaths" | "memory">;
204
205
  expectedNativeProfile?: NativeProfile;
205
206
  };
206
207
  type ManagedUlwLaunchOptions = Omit<ManagedUlwLaunchInput, "managedUlwPath"> & {
@@ -216,6 +217,8 @@ export type ManagedUlwLaunchComposition = {
216
217
  nativeProfile?: NativeProfile;
217
218
  nativeProfilePaths?: NativeProfilePaths;
218
219
  nativeDotenvPaths?: string[];
220
+ workerMemory?: WorkerMemoryPlan;
221
+ workerMemoryDormant?: true;
219
222
  };
220
223
 
221
224
  const LAUNCH_DISCOVERY_TIMEOUT_MS = 30_000;
@@ -345,7 +348,9 @@ export async function managedUlwLaunchComposition(input: ManagedUlwLaunchInput):
345
348
  return input.worker ? workerLaunchComposition({ ...input, worker: input.worker }) : launchComposition(input);
346
349
  }
347
350
 
348
- async function workerLaunchComposition(input: ManagedUlwLaunchInput & { worker: Pick<WorkerHostProfile, "extensionPaths"> }): Promise<ManagedUlwLaunchComposition> {
351
+ async function workerLaunchComposition(input: ManagedUlwLaunchInput & {
352
+ worker: Pick<WorkerHostProfile, "extensionPaths" | "memory">;
353
+ }): Promise<ManagedUlwLaunchComposition> {
349
354
  const { assertWorkerWorkspaceStartup } = await import("../worker/worker-profile");
350
355
  const { homedir } = await import("node:os");
351
356
  assertWorkerWorkspaceStartup(input.cwd, homedir());
@@ -358,11 +363,27 @@ async function workerLaunchComposition(input: ManagedUlwLaunchInput & { worker:
358
363
  const { effectiveManagedMemory, memoryBlockReason } = await import("./managed-memory");
359
364
  const memory = await effectiveManagedMemory(settings, null);
360
365
  if (memory.status !== "enabled") throw new Error(memoryBlockReason(memory));
366
+ let workerMemory: WorkerMemoryPlan | undefined;
367
+ if (input.worker.memory && memory.backend === "mnemopi") {
368
+ const { cfgMnemopiBank, cfgMnemopiScoping } = await import("@oh-my-pi/pi-coding-agent/mnemopi/settings");
369
+ const { computeMnemopiBankScope } = await import("@oh-my-pi/pi-coding-agent/mnemopi/config");
370
+ const configured = settings.rawValue(cfgMnemopiScoping);
371
+ if ((configured === undefined || cfgMnemopiScoping.accepts(configured)) && cfgMnemopiScoping.get(settings) === "per-project") {
372
+ const { nativeMemoryProjectCwd, resolveNativeProfile, sdkNativeProfilePaths } = await import("./native-sessions");
373
+ workerMemory = {
374
+ bank: computeMnemopiBankScope(cfgMnemopiBank.get(settings), nativeMemoryProjectCwd(input.cwd), "per-project").retainBank,
375
+ profile: resolveNativeProfile(sdkNativeProfilePaths(parsed.launchAgentDir)),
376
+ };
377
+ }
378
+ }
379
+ if (input.worker.memory?.previous && memory.backend === "mnemopi" && !workerMemory)
380
+ throw new Error("Worker memory cannot resume with a different native backend or bank scope");
361
381
  // Do not enumerate ambient packages/hooks for a worker. The operator pins
362
382
  // opt-in modules as files, while managed packages retain their own resources.
363
383
  const managed = validateManagedUlwPackage(input.managedUlwPath);
364
384
  const extensionPaths = [...new Set([...input.extensionPaths, managed, ...input.worker.extensionPaths])];
365
- return { extensionPaths, noExtensions: true, memoryWriteDir: null };
385
+ return { extensionPaths, noExtensions: true, memoryWriteDir: null, workerMemory,
386
+ ...(input.worker.memory?.previous && memory.backend !== "mnemopi" && { workerMemoryDormant: true }) };
366
387
  }
367
388
 
368
389
  async function launchComposition(input: ManagedUlwLaunchInput): Promise<ManagedUlwLaunchComposition> {
@@ -587,20 +608,26 @@ export async function updateManagedUlw(options: ManagedUlwOptions = {}): Promise
587
608
  preparedRepository = provenance.repository;
588
609
  } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
589
610
  const provenance: ActiveRevision = { revision: upstreamRevision, repository: manifest.repository, branch, preparedAt: new Date().toISOString() };
590
- if (!preparedRepository) {
591
- stage = await mkdtemp(join(root, ".stage-"));
592
- const source = join(stage, "source");
593
- const distribution = join(stage, "distribution");
594
- const packagePath = join(distribution, "package");
595
- await mkdir(packagePath, { recursive: true, mode: 0o700 });
611
+ stage = await mkdtemp(join(root, ".stage-"));
612
+ const source = join(stage, preparedRepository ? "ancestry" : "source");
613
+ const distribution = join(stage, "distribution");
614
+ const packagePath = join(preparedRepository ? revisionRoot : distribution, "package");
615
+ if (!preparedRepository) await mkdir(packagePath, { recursive: true, mode: 0o700 });
616
+ // A previously prepared revision may have been active before a remote
617
+ // rewind. Do not bypass ancestry merely because its files already exist.
618
+ if (!preparedRepository || active) {
596
619
  await git(["clone", "--no-checkout", "--no-local", manifest.repository, source]);
597
620
  await git(["fetch", "origin", upstreamRevision], source);
621
+ }
622
+ if (!preparedRepository) {
598
623
  await git(["checkout", "--detach", upstreamRevision], source);
599
624
  if (await git(["rev-parse", "HEAD"], source) !== upstreamRevision) throw new Error("ULW checkout revision changed while staging");
600
- if (active) {
601
- try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], source); }
602
- catch { throw new Error("ULW upstream update is not a provable fast-forward; explicit operator reconciliation required"); }
603
- }
625
+ }
626
+ if (active) {
627
+ try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], source); }
628
+ catch { throw new Error("ULW upstream update is not a provable fast-forward; explicit operator reconciliation required"); }
629
+ }
630
+ if (!preparedRepository) {
604
631
  await git(["submodule", "update", "--init", "--recursive", "--depth=1"], source);
605
632
  await checkLinks(source);
606
633
  // Export tracked runtime/resources, not .git, dev node_modules, or the
@@ -622,25 +649,14 @@ export async function updateManagedUlw(options: ManagedUlwOptions = {}): Promise
622
649
  }
623
650
  validateManagedUlwPackage(packagePath);
624
651
  await checkLinks(packagePath);
625
- await probe(packagePath, stage, manifest);
652
+ }
653
+ await probe(packagePath, stage, manifest);
654
+ if (!preparedRepository) {
626
655
  await writeFile(join(distribution, "provenance.json"), JSON.stringify(provenance, null, 2) + "\n", { mode: 0o444 });
627
656
  await immutableTree(packagePath);
628
657
  await mkdir(join(root, "revisions"), { recursive: true, mode: 0o700 });
629
658
  await rename(distribution, revisionRoot);
630
659
  }
631
- if (preparedRepository) {
632
- // A previously prepared revision may have been active before a remote
633
- // rewind. Do not bypass ancestry merely because its files already exist.
634
- stage = await mkdtemp(join(root, ".stage-"));
635
- if (active) {
636
- const source = join(stage, "ancestry");
637
- await git(["clone", "--no-checkout", "--no-local", manifest.repository, source]);
638
- await git(["fetch", "origin", upstreamRevision], source);
639
- try { await git(["merge-base", "--is-ancestor", active.revision, upstreamRevision], source); }
640
- catch { throw new Error("ULW upstream update is not a provable fast-forward; explicit operator reconciliation required"); }
641
- }
642
- await probe(join(revisionRoot, "package"), stage, manifest);
643
- }
644
660
  nextActive = { ...provenance, repository: preparedRepository ?? provenance.repository };
645
661
  }
646
662
  // Finish fallible staging cleanup/status publication before committing the
@@ -37,6 +37,18 @@ function isMissing(error: unknown): boolean {
37
37
  return error instanceof Error && "code" in error && error.code === "ENOENT";
38
38
  }
39
39
 
40
+ /** Match stock getProjectDir's Darwin spelling for bank hashing, never an arbitrary alias. */
41
+ export function nativeMemoryProjectCwd(canonical: string): string {
42
+ if (!isAbsolute(canonical) || realpathSync(canonical) !== canonical)
43
+ throw new Error("Worker memory requires a physically canonical checkout");
44
+ if (process.platform === "darwin" && canonical.startsWith("/private/")) {
45
+ const alias = canonical.slice("/private".length);
46
+ try { if (realpathSync(alias) === canonical) return alias; }
47
+ catch (error) { if (!isMissing(error)) throw error; }
48
+ }
49
+ return canonical;
50
+ }
51
+
40
52
  /** Resolve through existing ancestors without creating directories or accepting dangling symlinks. */
41
53
  function canonicalDirectory(path: string): string {
42
54
  if (!isAbsolute(path)) throw new Error("Native profile paths must be absolute");
@@ -0,0 +1,410 @@
1
+ import { SQLiteError, type Database } from "bun:sqlite";
2
+ import { createHash } from "node:crypto";
3
+ import { lstatSync, realpathSync } from "node:fs";
4
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
5
+ import { MAIN_AGENT_ID, type AgentSession } from "@oh-my-pi/pi-coding-agent";
6
+ import { lookup } from "@oh-my-pi/pi-coding-agent/config/registry";
7
+ import { getMemoriesDir } from "@oh-my-pi/pi-utils/dirs";
8
+ import { nativeMemoryProjectCwd } from "./native-sessions";
9
+ import type * as StockMemorySdk from "./worker-memory-sdk";
10
+ import {
11
+ type WorkerMemoryRecord, WORKER_MEMORY_PAGE_BYTES, WORKER_MEMORY_ROWS, safeWorkerMemoryText, workerMemoryId,
12
+ } from "../worker/worker-memory-page";
13
+
14
+ type NativeState = NonNullable<ReturnType<AgentSession["getMnemopiSessionState"]>>;
15
+ type NativeMemory = NativeState["memory"];
16
+ type Sdk = typeof StockMemorySdk;
17
+ export type WorkerMemoryImportResult = WorkerMemoryIndexStatus & {
18
+ readonly inserted: number;
19
+ readonly skipped: number;
20
+ readonly rejected: number;
21
+ readonly confirmation?: Promise<WorkerMemoryIndexStatus | undefined>;
22
+ };
23
+ type WorkerMemoryIndexStatus = {
24
+ readonly lexical: number;
25
+ readonly indexed: number;
26
+ readonly disabled: number;
27
+ readonly pending: number;
28
+ readonly deferred: number;
29
+ };
30
+ export type WorkerMemoryImport = {
31
+ readonly namespace: string;
32
+ readonly receiptNamespace: string;
33
+ importPage(
34
+ records: readonly WorkerMemoryRecord[], origin: string, receipts?: WorkerMemoryReceipts, canIndex?: () => boolean,
35
+ ): WorkerMemoryImportResult | undefined;
36
+ };
37
+ export type WorkerMemoryReceipts = {
38
+ seen(digest: string): boolean;
39
+ mark(digests: readonly string[]): void;
40
+ };
41
+
42
+ const source = "superagent-worker-fact";
43
+ const bankFiles = new WeakMap<NativeMemory, { readonly namespace: string; readonly sidecars: string }>();
44
+ const durablePolicies = new WeakMap<AgentSession["settings"], {
45
+ revision: number; unsafe: boolean; disabled: boolean; offline: boolean;
46
+ }>();
47
+ const pendingVectors = new WeakMap<NativeMemory, Map<string, Promise<void>>>();
48
+ const digest = (parts: readonly string[]) => createHash("sha256").update(JSON.stringify(parts)).digest("hex");
49
+
50
+ function usesLocalModel(sdk: Sdk, model: unknown): boolean {
51
+ return typeof model === "string" && typeof sdk.fastembedModelName(model.trim()) === "string";
52
+ }
53
+
54
+ function durablePolicy(settings: AgentSession["settings"], sdk: Sdk) {
55
+ const revision = settings.revision;
56
+ const cached = durablePolicies.get(settings);
57
+ if (cached?.revision === revision) return cached;
58
+ const layers = settings.mirrorState();
59
+ let disabled = false;
60
+ let offline = false;
61
+ let unsafe = false;
62
+ for (const layer of [layers.global, layers.project, layers.configOverlay]) {
63
+ const models = layer.models;
64
+ if (models !== undefined && (models === null || typeof models !== "object" || Array.isArray(models))) offline = false;
65
+ else if (models && "offline" in models) {
66
+ if (models.offline !== true) offline = false;
67
+ else if (layer === layers.global) offline = true;
68
+ }
69
+ const group = layer.mnemopi;
70
+ if (group === undefined) continue;
71
+ if (group === null || typeof group !== "object" || Array.isArray(group)) {
72
+ unsafe = true;
73
+ disabled = false;
74
+ continue;
75
+ }
76
+ if ("noEmbeddings" in group) {
77
+ if (group.noEmbeddings !== true) disabled = false;
78
+ // Only the underlying profile can prove disabled if a project or
79
+ // invocation overlay is omitted the next time native OMP opens the bank.
80
+ else if (layer === layers.global) disabled = true;
81
+ }
82
+ if (("embeddingApiUrl" in group && group.embeddingApiUrl) ||
83
+ ("embeddingModel" in group && group.embeddingModel && !usesLocalModel(sdk, group.embeddingModel))) unsafe = true;
84
+ }
85
+ const result = { revision, disabled, offline, unsafe };
86
+ durablePolicies.set(settings, result);
87
+ return result;
88
+ }
89
+
90
+ function bankIdentity(path: string) {
91
+ if (realpathSync(path) !== path) return;
92
+ const database = lstatSync(path, { bigint: true, throwIfNoEntry: false });
93
+ if (!database?.isFile() || database.nlink !== 1n) return;
94
+ const sidecars = [];
95
+ for (const suffix of ["-wal", "-shm", "-journal"]) {
96
+ const sidecar = lstatSync(path + suffix, { bigint: true, throwIfNoEntry: false });
97
+ if (sidecar && (!sidecar.isFile() || sidecar.nlink !== 1n)) return;
98
+ sidecars.push(sidecar ? `${sidecar.dev}:${sidecar.ino}` : "");
99
+ }
100
+ return { file: `${database.dev}:${database.ino}`, sidecars: sidecars.join(",") };
101
+ }
102
+
103
+ function readNativeSetting(settings: AgentSession["settings"], key: string, includeDefault = false): unknown {
104
+ const setting = lookup(key);
105
+ if (!setting) throw new WorkerMemoryImportError("Native worker memory settings unavailable");
106
+ return settings.rawValue(setting) ?? (includeDefault ? setting.default : undefined);
107
+ }
108
+
109
+ function liveDestination(session: AgentSession, cwd: string, sdk: Sdk) {
110
+ // The caller verifies stock class/registry identity via the running Host's injected pi.pi.
111
+ const settingsCwd = session.settings.getCwd();
112
+ if (session.getAgentId() !== MAIN_AGENT_ID || session.isDisposed !== false || !session.memoryEnabled
113
+ || !session.sessionFile || session.hindsightActive !== false || session.sessionManager.getCwd() !== cwd
114
+ || !isAbsolute(cwd) || realpathSync(cwd) !== cwd
115
+ || (settingsCwd !== cwd && settingsCwd !== nativeMemoryProjectCwd(cwd))) return;
116
+ const workspace = lstatSync(cwd, { bigint: true });
117
+ if (!workspace.isDirectory()) return;
118
+
119
+ const { settings } = session;
120
+ if (readNativeSetting(settings, "memory.backend") !== "mnemopi"
121
+ || readNativeSetting(settings, "mnemopi.scoping", true) !== "per-project") return;
122
+ const state = session.getMnemopiSessionState();
123
+ if (!state || state.aliasOf || state.session !== session || state.sessionId !== session.sessionId
124
+ || state.config.scoping !== "per-project") return;
125
+ const configuredBank = readNativeSetting(settings, "mnemopi.bank");
126
+ const scope = sdk.computeMnemopiBankScope(typeof configuredBank === "string" ? configuredBank : undefined, settingsCwd, "per-project");
127
+ const { bank, memory } = state.getScopedRetainTarget();
128
+ const beam = memory.beam;
129
+ const recall = state.getScopedRecallTargets();
130
+ if (bank !== scope.retainBank || state.config.retainBank !== bank || state.config.globalBank !== scope.globalBank
131
+ || bank === scope.globalBank || recall.length !== 1 || recall[0]?.memory !== memory
132
+ || memory !== state.memory || memory.bank !== bank || memory.sessionId !== bank || memory.channelId !== bank
133
+ || beam.sessionId !== bank || beam.channelId !== bank || memory.db !== beam.db
134
+ || typeof beam.importFromDict !== "function" || !(beam.pendingExtractions instanceof Set)) return;
135
+
136
+ const agentDir = settings.getAgentDir();
137
+ if (!isAbsolute(agentDir) || realpathSync(agentDir) !== agentDir) return;
138
+ const profile = lstatSync(agentDir, { bigint: true });
139
+ if (!profile.isDirectory()) return;
140
+ const base = state.config.dbPath;
141
+ const configuredPath = readNativeSetting(settings, "mnemopi.dbPath");
142
+ if (resolve(base) !== base || (typeof configuredPath === "string" && configuredPath.trim()
143
+ ? base !== configuredPath.trim() || !base.startsWith(agentDir + sep)
144
+ : base !== join(getMemoriesDir(agentDir), "mnemopi", "mnemopi.db"))) return;
145
+ const path = join(dirname(base), "banks", bank, "mnemopi.db");
146
+ if (memory.dbPath !== path || beam.dbPath !== path || beam.db.filename !== path) return;
147
+ const identity = bankIdentity(path);
148
+ if (!identity) return;
149
+ const receiptNamespace = digest([agentDir, cwd, path, bank]);
150
+ const namespace = digest([receiptNamespace, `${profile.dev}:${profile.ino}`, `${workspace.dev}:${workspace.ino}`, identity.file]);
151
+ const prior = bankFiles.get(memory);
152
+ if (prior && (prior.namespace !== namespace || prior.sidecars !== identity.sidecars)) return;
153
+ bankFiles.set(memory, { namespace, sidecars: identity.sidecars });
154
+
155
+ const options = memory.runtimeOptions?.embeddings;
156
+ const disabled = readNativeSetting(settings, "mnemopi.noEmbeddings", true);
157
+ const embeddingModel = options?.model;
158
+ if (!options || typeof embeddingModel !== "string" || !embeddingModel.trim()
159
+ || options.apiUrl !== readNativeSetting(settings, "mnemopi.embeddingApiUrl")
160
+ || options.disabled !== disabled || typeof disabled !== "boolean") return;
161
+ // Stock API embedding follows redirects without reauthorizing their targets.
162
+ // An eligible row with no vector could also be submitted by native startup
163
+ // reconciliation, so don't persist worker facts under an unverified API route.
164
+ const startupModel = readNativeSetting(settings, "mnemopi.embeddingModel");
165
+ const ambientModel = process.env.MNEMOPI_EMBEDDING_MODEL;
166
+ const durable = durablePolicy(settings, sdk);
167
+ const mayUseApi = durable.unsafe || !usesLocalModel(sdk, embeddingModel) || (startupModel && !usesLocalModel(sdk, startupModel))
168
+ || (ambientModel && !usesLocalModel(sdk, ambientModel)) || options.apiUrl
169
+ || process.env.MNEMOPI_EMBEDDING_API_URL || process.env.OPENROUTER_BASE_URL
170
+ || process.env.MNEMOPI_EMBEDDINGS_VIA_API;
171
+ if (settings.overlayParent() || (mayUseApi && (!disabled || !durable.disabled))) return;
172
+ // On reopen, stock reconciliation can route missing vectors through its
173
+ // process-wide override before local resolution. A local model name or a
174
+ // temporary offline setting is not a durable prohibition on that route.
175
+ if (!(disabled && durable.disabled)
176
+ && !(durable.offline && readNativeSetting(settings, "models.offline", true) === true)) return;
177
+ if (!disabled && !options.provider && options.allowRemote?.("") !== false) return;
178
+ return {
179
+ namespace, receiptNamespace, state, memory, bank, options, embeddingModel, disabled, sdk, sessionId: session.sessionId,
180
+ sessionFile: session.sessionFile, revision: settings.revision,
181
+ };
182
+ }
183
+
184
+ function destinationOrUnavailable(session: AgentSession, cwd: string, sdk: Sdk) {
185
+ try {
186
+ return liveDestination(session, cwd, sdk);
187
+ } catch (error) {
188
+ // A missing file, closed handle, or unsupported installed SDK is not a destination.
189
+ if (!(error instanceof Error)) throw error;
190
+ return undefined;
191
+ }
192
+ }
193
+
194
+ type Destination = NonNullable<ReturnType<typeof liveDestination>>;
195
+
196
+ function mayScheduleEmbedding({ options, disabled }: Destination): boolean {
197
+ return !disabled && !!options.provider && options.allowRemote?.("") === true;
198
+ }
199
+
200
+ async function stockDocumentEmbedding(destination: Destination, texts: readonly string[], current: () => boolean) {
201
+ const { memory, options, sdk } = destination;
202
+ const scope = memory.runtimeOptions;
203
+ if (!scope || scope.embeddings !== options || !options.provider || !current() || !mayScheduleEmbedding(destination)) return;
204
+ // The bridge may use the exact authorized stock in-process provider, never
205
+ // the SDK's process-wide override, default resolver or model initializer.
206
+ const scoped = { ...scope, embeddings: { ...options, provider: options.provider } };
207
+ return sdk.withMnemopiRuntimeOptions(scoped, () =>
208
+ sdk.getMnemopiRuntimeOptions() === scoped ? sdk.embed(texts, "document") : null);
209
+ }
210
+
211
+ /** Do not block HEAD for the live connection's usual 5s busy timeout. */
212
+ function withoutLockWait<T>(db: Database, action: () => T): T | undefined {
213
+ const original = db.query<{ timeout: number }, []>("PRAGMA busy_timeout").get();
214
+ if (!original) throw new WorkerMemoryImportError("Cannot read native SQLite lock policy");
215
+ db.exec("PRAGMA busy_timeout=0");
216
+ try {
217
+ return action();
218
+ } catch (error) {
219
+ if (error instanceof SQLiteError && ((error.errno & 255) === 5 || (error.errno & 255) === 6)) return;
220
+ throw error;
221
+ } finally {
222
+ db.exec(`PRAGMA busy_timeout=${original.timeout}`);
223
+ }
224
+ }
225
+
226
+ function indexFresh(destination: Destination, page: {
227
+ readonly fresh: readonly ImportRow[];
228
+ current(): boolean;
229
+ needsVector(row: ImportRow): boolean;
230
+ }): void {
231
+ const { memory, embeddingModel, options, sdk } = destination;
232
+ const { beam, db } = memory;
233
+ if (page.fresh.length === 0 || beam.pendingExtractions.size > 64 || !mayScheduleEmbedding(destination)) return;
234
+ const pending = pendingVectors.get(memory) ?? new Map<string, Promise<void>>();
235
+ pendingVectors.set(memory, pending);
236
+ const provider = options.provider;
237
+ const authorized = () => options.provider === provider && mayScheduleEmbedding(destination) && page.current();
238
+ const task = (async () => {
239
+ if (!authorized()) return;
240
+ const matrix = await stockDocumentEmbedding(destination, page.fresh.map(row => row.content), authorized);
241
+ if (matrix?.length !== page.fresh.length || !authorized()) return;
242
+ const staged = page.fresh.flatMap((row, index) => {
243
+ const vector = matrix[index];
244
+ return vector?.length && vector.every(Number.isFinite) && vector.some(value => value !== 0)
245
+ ? [{ memoryId: row.id, content: row.content, json: JSON.stringify(Array.from(vector)), row }] : [];
246
+ });
247
+ if (staged.length === 0 || db.inTransaction) return;
248
+ const committed = withoutLockWait(db, db.transaction(() => {
249
+ if (!authorized()) return 0;
250
+ return sdk.insertLiveEmbeddings(db, staged.filter(({ row }) => page.needsVector(row)), embeddingModel);
251
+ }).immediate);
252
+ if (committed) beam.caches.queryCache?.invalidate();
253
+ })();
254
+ for (const row of page.fresh) pending.set(row.id, task);
255
+ beam.pendingExtractions.add(task);
256
+ const settle = () => {
257
+ for (const row of page.fresh) if (pending.get(row.id) === task) pending.delete(row.id);
258
+ beam.pendingExtractions.delete(task);
259
+ };
260
+ void task.then(settle, settle);
261
+ }
262
+
263
+ function canWriteNow(session: AgentSession): boolean {
264
+ // Admission can inspect the bank during lane_start, but only an idle live
265
+ // session outside native read-only modes may authorize an actual write.
266
+ return session.isDisposed === false && session.isSessionTransitioning === false
267
+ && session.isRunActive === false && session.isBusyForSnapshot === false
268
+ && session.hasAdmittedSubmission === false && session.hasPostPromptWork === false
269
+ && session.queuedMessageCount === 0 && session.yieldQueue?.has() === false
270
+ && typeof session.getPlanModeState === "function" && !session.getPlanModeState()?.enabled
271
+ && typeof session.getPrewalkState === "function" && session.getPrewalkState() === undefined;
272
+ }
273
+
274
+ function importRows(records: readonly WorkerMemoryRecord[], scope: {
275
+ readonly origin: string;
276
+ readonly cwd: string;
277
+ readonly bank: string;
278
+ readonly receiptNamespace: string;
279
+ }) {
280
+ const { origin, cwd, bank, receiptNamespace } = scope;
281
+ return records.flatMap(record => {
282
+ const content = record.content.trim();
283
+ if (!safeWorkerMemoryText(record.content)
284
+ || /<|^\s*(?:\/\w|(?:[#>*\s\[]*)(?:system|developer|assistant|user|tool|command)(?:\s*:|\s*\]))/iu.test(content)
285
+ || /^\{\s*"(?:role|command|tool_call)"\s*:/iu.test(content)
286
+ || !workerMemoryId.test(record.id)) return [];
287
+ return [{
288
+ id: digest([source, receiptNamespace, origin, content]),
289
+ content,
290
+ source,
291
+ session_id: bank,
292
+ channel_id: bank,
293
+ scope: "bank",
294
+ trust_tier: "IMPORTED",
295
+ veracity: "imported",
296
+ memory_type: "fact",
297
+ metadata_json: JSON.stringify({ cwd, origin, row: record.id }),
298
+ }];
299
+ });
300
+ }
301
+
302
+ type ImportRow = ReturnType<typeof importRows>[number];
303
+
304
+ export function prepareWorkerMemoryImport(session: AgentSession, cwd: string, sdk: Sdk): WorkerMemoryImport | undefined {
305
+ const destination = destinationOrUnavailable(session, cwd, sdk);
306
+ if (!destination) return;
307
+ const currentDestination = () => {
308
+ const current = destinationOrUnavailable(session, cwd, sdk);
309
+ if (current && current.state === destination.state && current.namespace === destination.namespace
310
+ && current.options === destination.options
311
+ && current.sessionId === destination.sessionId && current.sessionFile === destination.sessionFile
312
+ && current.revision === destination.revision && current.embeddingModel === destination.embeddingModel) return current;
313
+ };
314
+ return {
315
+ namespace: destination.namespace,
316
+ receiptNamespace: destination.receiptNamespace,
317
+ importPage(records, origin, receipts, canIndex) {
318
+ if (!/^[0-9a-f]{64}$/u.test(origin) || records.length > WORKER_MEMORY_ROWS
319
+ || Buffer.byteLength(JSON.stringify(records)) > WORKER_MEMORY_PAGE_BYTES) return;
320
+ const current = currentDestination();
321
+ if (!current || !canWriteNow(session)) return;
322
+
323
+ const { bank, memory, embeddingModel, disabled } = current;
324
+ const rows = importRows(records, { origin, cwd, bank, receiptNamespace: destination.receiptNamespace });
325
+ const byId = new Map<string, ImportRow>();
326
+ for (const row of rows) if (!byId.has(row.id)) byId.set(row.id, row);
327
+ const unique = [...byId.values()];
328
+ const { db, beam } = memory;
329
+ if (db.inTransaction) return;
330
+ return withoutLockWait(db, () => {
331
+ const provenance = "source = ? AND session_id = ? AND scope = 'bank' AND CASE WHEN json_valid(metadata_json)"
332
+ + " THEN json_extract(metadata_json, '$.origin') = ? AND json_extract(metadata_json, '$.cwd') = ? END";
333
+ const existing = db.query<{ owned: number }, [string, string, string, string, string]>(
334
+ `SELECT CASE WHEN ${provenance} THEN 1 ELSE 0 END AS owned FROM working_memory WHERE id = ?`,
335
+ );
336
+ const stored = db.query<{ found: number }, [string, string, string, string, string, string]>(
337
+ `SELECT 1 AS found FROM working_memory WHERE id = ? AND content = ? AND ${provenance}`
338
+ + " AND superseded_by IS NULL AND valid_until IS NULL AND embed_text IS NULL",
339
+ );
340
+ const fresh = unique.length === 0 ? [] : db.transaction(() => {
341
+ const inserted: ImportRow[] = [];
342
+ const unrecorded: string[] = [];
343
+ for (const row of unique) {
344
+ if (receipts?.seen(row.id)) continue;
345
+ const existingRow = existing.get(source, bank, origin, cwd, row.id);
346
+ if (!existingRow) inserted.push(row);
347
+ if (receipts && (!existingRow || existingRow.owned === 1)) unrecorded.push(row.id);
348
+ }
349
+ if (inserted.length > 0) {
350
+ const now = new Date().toISOString();
351
+ const result = beam.importFromDict({ working_memory: inserted.map(row => ({
352
+ ...row, timestamp: now, created_at: now,
353
+ })) }, false).working_memory;
354
+ if (result.inserted !== inserted.length || result.overwritten !== 0 || result.skipped !== 0)
355
+ throw new WorkerMemoryImportError("Native worker memory insert did not establish all new rows");
356
+ }
357
+ // Two stores cannot share this commit. Fence replay before committing
358
+ // the bank: uncertainty may leave a fact held, never revived after forget.
359
+ if (unrecorded.length) receipts?.mark(unrecorded);
360
+ return inserted;
361
+ }).immediate();
362
+ const lexicalMatch = db.query<{ found: number }, [string, string]>(
363
+ // A dense bank may leave a result unobserved; never scan it just to confirm status.
364
+ "SELECT 1 AS found FROM (SELECT id FROM fts_working WHERE fts_working MATCH ? LIMIT 64)"
365
+ + " WHERE id = ? LIMIT 1",
366
+ );
367
+ const vector = db.query<{ found: number }, [string, string]>(
368
+ "SELECT 1 AS found FROM memory_embeddings WHERE memory_id = ? AND model = ?"
369
+ + " AND json_valid(embedding_json) AND json_array_length(embedding_json) > 0",
370
+ );
371
+ const isLive = (row: ImportRow) => stored.get(row.id, row.content, source, bank, origin, cwd) !== null;
372
+ const isIndexed = (row: ImportRow) => vector.get(row.id, embeddingModel) !== null;
373
+ indexFresh(current, {
374
+ fresh,
375
+ current: () => !!currentDestination() && canWriteNow(session) && (canIndex?.() ?? true),
376
+ needsVector: row => isLive(row) && !isIndexed(row),
377
+ });
378
+ const awaiting = new Set<Promise<void>>();
379
+ const inFlight = pendingVectors.get(memory);
380
+ for (const row of unique) {
381
+ const task = inFlight?.get(row.id);
382
+ if (task) awaiting.add(task);
383
+ }
384
+ const inspect = (): WorkerMemoryIndexStatus => {
385
+ let lexical = 0;
386
+ let indexed = 0;
387
+ let live = 0;
388
+ let pending = 0;
389
+ for (const row of unique) {
390
+ if (!isLive(row)) continue;
391
+ live++;
392
+ if (/[\p{L}\p{N}]/u.test(row.content) && lexicalMatch.get(`"${row.content.replaceAll('"', '""')}"`, row.id)) lexical++;
393
+ if (!disabled && isIndexed(row)) indexed++;
394
+ else if (!disabled && inFlight?.has(row.id)) pending++;
395
+ }
396
+ return { lexical, indexed, disabled: disabled ? live : 0, pending, deferred: disabled ? 0 : live - indexed - pending };
397
+ };
398
+ const confirmation = awaiting.size ? Promise.allSettled(awaiting).then(() => {
399
+ if (currentDestination()) return withoutLockWait(db, inspect);
400
+ }) : undefined;
401
+ return {
402
+ inserted: fresh.length, skipped: rows.length - fresh.length, rejected: records.length - rows.length,
403
+ ...inspect(), ...(confirmation ? { confirmation } : {}),
404
+ };
405
+ });
406
+ },
407
+ };
408
+ }
409
+
410
+ class WorkerMemoryImportError extends Error {}