omp-superagent 0.1.11 → 0.1.15

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 (82) hide show
  1. package/DESIGN.md +21 -5
  2. package/README.ko.md +3 -1
  3. package/README.md +3 -1
  4. package/THIRD_PARTY_NOTICES.md +6 -0
  5. package/assets/architecture-dark.svg +4 -4
  6. package/assets/architecture.ko-dark.svg +4 -4
  7. package/assets/architecture.ko.svg +4 -4
  8. package/assets/architecture.mmd +5 -5
  9. package/assets/architecture.svg +4 -4
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +242 -31
  12. package/docs/OPERATIONS.md +225 -25
  13. package/docs/design/execution.md +161 -43
  14. package/docs/design/messaging.md +45 -9
  15. package/docs/releases/0.1.11.md +4 -2
  16. package/docs/releases/0.1.13.md +13 -0
  17. package/docs/releases/0.1.15.md +13 -0
  18. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  21. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  25. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  26. package/package.json +9 -3
  27. package/scripts/prepare-worker-memory.ts +37 -0
  28. package/scripts/upgrade-evidence-files.mjs +100 -0
  29. package/scripts/upgrade-evidence.mjs +192 -0
  30. package/scripts/upgrade-host-wire.mjs +162 -0
  31. package/skills/head/SKILL.md +22 -47
  32. package/skills/head/references/routing.md +11 -12
  33. package/skills/head/references/supervision.md +10 -14
  34. package/skills/lane/SKILL.md +14 -16
  35. package/skills/lane/references/workflow.md +14 -27
  36. package/src/cli.ts +59 -79
  37. package/src/config/config.ts +4 -0
  38. package/src/contracts.ts +34 -27
  39. package/src/cron/cron-jobs.ts +4 -3
  40. package/src/cron/cron-pr-intake.ts +1 -2
  41. package/src/extension.ts +57 -14
  42. package/src/gateway/gateway-client.ts +14 -12
  43. package/src/group/group-runner.ts +3 -2
  44. package/src/group-runner-extension.ts +7 -3
  45. package/src/host-extension.ts +109 -2
  46. package/src/host-sdk-helper.ts +12 -3
  47. package/src/lane/decision-tool.ts +2 -3
  48. package/src/lane/lane-report.ts +8 -30
  49. package/src/lane/lane-rows.ts +1 -1
  50. package/src/lane/workflow.ts +44 -3
  51. package/src/lane-extension.ts +5 -46
  52. package/src/messaging/discord-context.ts +8 -6
  53. package/src/omp/host-protocol.ts +4 -3
  54. package/src/omp/host.ts +24 -7
  55. package/src/omp/managed-super.ts +43 -27
  56. package/src/omp/native-sessions.ts +12 -0
  57. package/src/omp/worker-memory-import.ts +410 -0
  58. package/src/omp/worker-memory-sdk.ts +8 -0
  59. package/src/operator/setup.ts +8 -13
  60. package/src/operator/stop-lane.ts +25 -0
  61. package/src/pr/pr-github-schema.ts +9 -0
  62. package/src/pr/pr-github.ts +6 -2
  63. package/src/pr/pr-intake-automation.ts +11 -8
  64. package/src/pr/pr-intake-fix.ts +2 -5
  65. package/src/pr/pr-intake-review.ts +7 -7
  66. package/src/routing/topic-history.ts +2 -2
  67. package/src/runtime/controller.ts +444 -408
  68. package/src/runtime/head-recovery.ts +7 -7
  69. package/src/runtime/worker-memory.ts +156 -0
  70. package/src/storage/deferred-routing.ts +1 -7
  71. package/src/storage/store.ts +441 -375
  72. package/src/worker/worker-host.ts +3 -2
  73. package/src/worker/worker-ledger.ts +20 -11
  74. package/src/worker/worker-memory-page.ts +83 -0
  75. package/src/worker/worker-memory-proofs.ts +260 -0
  76. package/src/worker/worker-memory-source.ts +305 -0
  77. package/src/worker/worker-memory-storage.ts +130 -0
  78. package/src/worker/worker-profile.ts +2 -0
  79. package/src/worker/worker-repository.ts +92 -7
  80. package/src/worker/worker-request.ts +1 -0
  81. package/src/worker/worker-service.ts +25 -8
  82. package/src/worker/worker-wire.ts +20 -6
@@ -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 {}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Generated bridge entry for standalone OMP, where runtime extensions cannot
3
+ * resolve these pinned SDK internals through its legacy virtual registry.
4
+ */
5
+ export { computeMnemopiBankScope } from "@oh-my-pi/pi-coding-agent/mnemopi/config";
6
+ export { insertLiveEmbeddings } from "@oh-my-pi/pi-mnemopi/core/beam/helpers";
7
+ export { embed, fastembedModelName } from "@oh-my-pi/pi-mnemopi/core/embeddings";
8
+ export { getMnemopiRuntimeOptions, withMnemopiRuntimeOptions } from "@oh-my-pi/pi-mnemopi/core/runtime-options";
@@ -3,7 +3,6 @@ import {
3
3
  openSync, readFileSync, realpathSync, unlinkSync, writeSync,
4
4
  } from "node:fs";
5
5
  import { dirname, isAbsolute, join, resolve } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
6
  import { isatty } from "node:tty";
8
7
  import { setImmediate as yieldToSignals } from "node:timers/promises";
9
8
  import { credentialEnvNames, hostPaths, parseConfig, type Config } from "../config/config";
@@ -15,7 +14,7 @@ import {
15
14
  import { applyConsentedMnemopi, canEnableGlobalMemory, inspectManagedMemory, memoryBlockReason } from "../omp/managed-memory";
16
15
  import { inspectNativeJudge } from "./setup-judge";
17
16
 
18
- const root = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
17
+ const root = resolve(import.meta.dir, "../..");
19
18
 
20
19
  class SetupCancelled extends Error {
21
20
  constructor(saved = false) {
@@ -167,7 +166,6 @@ export async function setup(configPath: string): Promise<void> {
167
166
  const path = resolve(configPath);
168
167
  const terminal = new Terminal();
169
168
  let configTemporary: string | undefined;
170
- let createdConfig = false;
171
169
  try {
172
170
  const previousConfig = currentConfig(path);
173
171
  const previousCredentials = readCredentialFile(path);
@@ -183,10 +181,11 @@ export async function setup(configPath: string): Promise<void> {
183
181
  ({ config, text } = await newConfig(terminal, path));
184
182
  }
185
183
  hostPaths(config, "main");
186
- await inspectInstalledOmp(config.command, credentialEnvNames(config));
184
+ const credentialNames = credentialEnvNames(config);
185
+ await inspectInstalledOmp(config.command, credentialNames);
187
186
  const values = Object.assign(Object.create(null) as Record<string, string>, previousCredentials?.values);
188
187
  let replacing = false;
189
- for (const name of credentialEnvNames(config)) {
188
+ for (const name of credentialNames) {
190
189
  const old = Object.hasOwn(values, name) ? values[name] : undefined;
191
190
  const explicit = process.env[name];
192
191
  const configured = !!(explicit || old);
@@ -225,7 +224,7 @@ export async function setup(configPath: string): Promise<void> {
225
224
  : "Write configuration/credentials?");
226
225
  // Snapshot the same environment-over-file precedence used by start before
227
226
  // native settings imports can populate unrelated dotenv values.
228
- const profileCredentials = Object.fromEntries(credentialEnvNames(config).map(name => [name, process.env[name] || values[name]!]));
227
+ const profileCredentials = Object.fromEntries(credentialNames.map(name => [name, process.env[name] || values[name]!]));
229
228
  // Deliver pending cancellation before entering the synchronous commit section.
230
229
  await yieldToSignals();
231
230
  terminal.check();
@@ -233,17 +232,13 @@ export async function setup(configPath: string): Promise<void> {
233
232
  unchanged(path, previousConfig);
234
233
  assertCredentialsUnchanged(path, previousCredentials);
235
234
  terminal.check();
236
- if (configTemporary) {
237
- linkSync(configTemporary, path); // Exclusive creation: never overwrite another config.
238
- createdConfig = true;
239
- }
235
+ if (configTemporary) linkSync(configTemporary, path); // Exclusive creation: never overwrite another config.
240
236
  try { writeCredentials(path, values, previousCredentials); }
241
237
  catch (error) {
242
- if (createdConfig && configTemporary) {
238
+ if (configTemporary) {
243
239
  const staged = lstatSync(configTemporary);
244
240
  const current = lstatSync(path);
245
241
  if (staged.dev === current.dev && staged.ino === current.ino) unlinkSync(path);
246
- createdConfig = false;
247
242
  }
248
243
  throw error;
249
244
  }
@@ -260,7 +255,7 @@ export async function setup(configPath: string): Promise<void> {
260
255
  console.log(`Setup saved but is incomplete. ${memoryBlockReason(memory)} No service was started by setup.`);
261
256
  process.exitCode = 1;
262
257
  }
263
- if (createdConfig) {
258
+ if (configTemporary) {
264
259
  const judge = await inspectNativeJudge(config.headCwd);
265
260
  if (judge.status === "unknown") {
266
261
  console.log("Setup saved, but native OMP judge configuration could not be verified; judge configuration is unknown, not confirmed missing. Native model settings were not changed by this check.");
@@ -0,0 +1,25 @@
1
+ import { hostPaths, type Config } from "../config/config";
2
+ import type { Lane } from "../contracts";
3
+ import { HostConnection } from "../omp/host";
4
+ import { lookupWorker, remoteLanePaths, workerConnect, workerRef } from "../worker/worker-wire";
5
+
6
+ /** The saved lane and selected instance must agree before contact. Send the
7
+ * stop only over the connection on which its native identity was established. */
8
+ export async function stopManagedLane(config: Config, lane: Lane): Promise<void> {
9
+ const remote = lane.remote;
10
+ const paths = remote ? remoteLanePaths(remote, lane.id) : hostPaths(config, lane.id);
11
+ if (!lane.pid || !lane.sessionId || lane.socketPath !== paths.socketPath || (remote && lane.sessionFile !== paths.sessionFile))
12
+ throw new Error("Lane has no recorded Host identity eligible for shutdown");
13
+
14
+ const endpoint = remote ? {
15
+ connection: await workerConnect(await lookupWorker(config.stateDir, remote), workerRef(lane)),
16
+ } : await HostConnection.open(paths.socketPath);
17
+ try {
18
+ const state = "state" in endpoint ? endpoint.state : await endpoint.connection.client.getState();
19
+ if (state.hostPid !== lane.pid || state.sessionId !== lane.sessionId || state.sessionFile !== lane.sessionFile ||
20
+ (!remote && "workerAttempt" in state))
21
+ throw new Error("Host identity no longer matches the recorded lane; shutdown was not sent");
22
+ const response = await endpoint.connection.request({ type: "shutdown_host" });
23
+ if (!response.success) throw new Error(response.error ?? "Host refused shutdown");
24
+ } finally { await endpoint.connection.close(); }
25
+ }
@@ -87,6 +87,15 @@ export function parseWire<T extends TSchema>(schema: T, output: string): Static<
87
87
  return value;
88
88
  }
89
89
 
90
+ /** Count key tokens in already parsed JSON, including duplicate keys hidden by JSON.parse. */
91
+ export function hasExactJsonPropertyCount(source: string, expected: number): boolean {
92
+ let count = 0;
93
+ for (const token of source.matchAll(/"(?:[^"\\]|\\[\s\S])*"/g)) {
94
+ if (/^\s*:/.test(source.slice(token.index + token[0].length))) count++;
95
+ }
96
+ return count === expected;
97
+ }
98
+
90
99
  export function pages<T extends TSchema>(schema: T) {
91
100
  return Type.Array(schema, { minItems: 1 });
92
101
  }
@@ -38,8 +38,12 @@ export function parsePrRef(value: string): PrRef {
38
38
  return { owner: owner.toLowerCase(), repo: repo.toLowerCase(), number };
39
39
  }
40
40
 
41
+ function checkedPrRef(ref: PrRef): PrRef {
42
+ return parsePrRef(`${ref.owner}/${ref.repo}#${ref.number}`);
43
+ }
44
+
41
45
  export function prKey(ref: PrRef): string {
42
- const parsed = parsePrRef(`${ref.owner}/${ref.repo}#${ref.number}`);
46
+ const parsed = checkedPrRef(ref);
43
47
  return `${parsed.owner}/${parsed.repo}#${parsed.number}`;
44
48
  }
45
49
 
@@ -85,7 +89,7 @@ function checkAttempt(run: Static<typeof checkPageSchema>["check_runs"][number])
85
89
  export async function readPrSnapshot(
86
90
  ref: PrRef, options: { readonly previousHead?: string; readonly signal: AbortSignal },
87
91
  ): Promise<PrSnapshot> {
88
- const parsed = parsePrRef(prKey(ref));
92
+ const parsed = checkedPrRef(ref);
89
93
  const root = `repos/${parsed.owner}/${parsed.repo}`;
90
94
  const endpoint = `${root}/pulls/${parsed.number}`;
91
95
  const { signal } = options;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Type, type Static } from "@sinclair/typebox/type";
3
3
  import type { StorePort } from "../contracts";
4
- import { PrReadError, parseWire, sha40 as sha } from "./pr-github-schema";
4
+ import { hasExactJsonPropertyCount, PrReadError, parseWire, sha40 as sha } from "./pr-github-schema";
5
5
  import { inspectIntakeComment, publishIntakeComment } from "./pr-intake-comment";
6
6
  import { applyIntakeFix, parseIntakeFix, reconcileIntakeFix } from "./pr-intake-fix";
7
7
  import { inspectIntakeMerge, mergeIntakePull } from "./pr-intake-github";
@@ -98,12 +98,16 @@ function unresolved(receipt: Receipt | undefined): receipt is Extract<Receipt, {
98
98
  return receipt?.state === "pending" || receipt?.state === "unknown";
99
99
  }
100
100
 
101
+ export function hasUnresolvedIntakeWrites(state: Pick<Ledger, "comments" | "fix" | "merge">): boolean {
102
+ return state.comments.some(unresolved) || unresolved(state.fix) || unresolved(state.merge);
103
+ }
104
+
101
105
  export function prIntakeManualHold(
102
106
  store: Pick<StorePort, "getMeta">, scope: Scope, action: "pr-review" | "pr-fix" | "pr-merge", head?: string,
103
107
  ): string | null {
104
108
  const state = readPrIntakeAutomation(store, scope);
105
109
  if (!state) return null;
106
- if (state.comments.some(unresolved) || unresolved(state.fix) || unresolved(state.merge))
110
+ if (hasUnresolvedIntakeWrites(state))
107
111
  return "An automatic GitHub write is unresolved for this PR. Reconcile it read-only before any new review or write.";
108
112
  if (state.merge?.state === "confirmed") return `GitHub already confirmed merge ${state.merge.id}.`;
109
113
  if (state.fix?.state === "confirmed" && state.fix.head === head)
@@ -126,9 +130,7 @@ function parseVerdict(answer: string) {
126
130
  const summary = snippets.reduce((text, snippet) => snippet ? text.replaceAll(snippet, "[source omitted]") : text, value.summary);
127
131
  return { verdict: "fix" as const, summary, proposal };
128
132
  }
129
- const keys = [...answer.matchAll(/"(?:[^"\\]|\\[\s\S])*"/g)]
130
- .filter(token => /^\s*:/.test(answer.slice(token.index + token[0].length)));
131
- return keys.length === 2 && Object.keys(value).length === 2 ? { ...value, verdict: value.verdict } : null;
133
+ return hasExactJsonPropertyCount(answer, 2) && Object.keys(value).length === 2 ? { ...value, verdict: value.verdict } : null;
132
134
  } catch (error) {
133
135
  if (error instanceof PrReadError) return null;
134
136
  throw error;
@@ -256,14 +258,15 @@ export async function advancePrIntakeAutomation(r: ReviewRound, d: PrIntakeAutom
256
258
  case "confirmed":
257
259
  if (kind === "fix" && !attempted) throw new PrIntakeAutomationError("Fix confirmation lacks its durable send fence.");
258
260
  saveEffect(kind, { ...entry, state: "confirmed", id: result.id });
259
- return { ...result, attempted };
261
+ break;
260
262
  case "unknown":
261
263
  saveEffect(kind, { ...entry, state: "unknown" });
262
- return { ...result, attempted };
264
+ break;
263
265
  case "blocked":
264
266
  if (attempted) saveEffect(kind, { ...entry, state: "refused", reason: result.reason });
265
- return { ...result, attempted };
267
+ break;
266
268
  }
269
+ return { ...result, attempted };
267
270
  };
268
271
  try {
269
272
  if (!savedComment) {
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { Type, type Static } from "@sinclair/typebox/type";
3
- import { parseWire, PrReadError, sha40 as oid } from "./pr-github-schema";
3
+ import { hasExactJsonPropertyCount, parseWire, PrReadError, sha40 as oid } from "./pr-github-schema";
4
4
  import { openIntakeGitHubSession, queryIntakeGitHub, type IntakeRepositoryIdentity } from "./pr-intake-github";
5
5
  import {
6
6
  intakeEvidenceDeadlineMs, IntakeMaterialError, readIntakeDiff, readIntakePullIdentity, serializeIntakeDiff,
@@ -87,10 +87,7 @@ export function parseIntakeFix(text: string): IntakeFixProposal | null {
87
87
  if (Buffer.byteLength(text) > 64 * 1024) return null;
88
88
  try {
89
89
  const { path, old, replacement, summary } = parseWire(verdict, text);
90
- // JSON.parse alone silently accepts an object that states two different verdicts.
91
- const keys = [...text.matchAll(/"(?:[^"\\]|\\[\s\S])*"/g)]
92
- .filter(token => /^\s*:/.test(text.slice(token.index + token[0].length)));
93
- if (keys.length !== Object.keys(verdict.properties).length) return null;
90
+ if (!hasExactJsonPropertyCount(text, Object.keys(verdict.properties).length)) return null;
94
91
  const proposal = { path, old, replacement };
95
92
  return summary.trim() && safeProposal(proposal) ? proposal : null;
96
93
  } catch (error) {