omp-superagent 0.1.13 → 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.
- package/DESIGN.md +8 -5
- package/THIRD_PARTY_NOTICES.md +6 -0
- package/assets/architecture-dark.svg +4 -4
- package/assets/architecture.ko-dark.svg +4 -4
- package/assets/architecture.ko.svg +4 -4
- package/assets/architecture.mmd +5 -5
- package/assets/architecture.svg +4 -4
- package/config.example.json +1 -0
- package/docs/OPERATIONS.en.md +59 -23
- package/docs/OPERATIONS.md +53 -18
- package/docs/design/execution.md +161 -43
- package/docs/design/messaging.md +45 -9
- package/docs/releases/0.1.15.md +13 -0
- package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
- package/gateway/bin/omp-gateway-darwin-x64 +0 -0
- package/gateway/bin/omp-gateway-linux-arm64 +0 -0
- package/gateway/bin/omp-gateway-linux-x64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
- package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
- package/package.json +6 -3
- package/scripts/prepare-worker-memory.ts +37 -0
- package/skills/head/SKILL.md +22 -47
- package/skills/head/references/routing.md +11 -12
- package/skills/head/references/supervision.md +10 -14
- package/skills/lane/SKILL.md +14 -16
- package/skills/lane/references/workflow.md +14 -27
- package/src/cli.ts +56 -56
- package/src/config/config.ts +4 -0
- package/src/contracts.ts +34 -27
- package/src/cron/cron-jobs.ts +4 -3
- package/src/cron/cron-pr-intake.ts +1 -2
- package/src/extension.ts +57 -14
- package/src/gateway/gateway-client.ts +14 -12
- package/src/group/group-runner.ts +3 -2
- package/src/group-runner-extension.ts +7 -3
- package/src/host-extension.ts +109 -2
- package/src/host-sdk-helper.ts +6 -1
- package/src/lane/decision-tool.ts +2 -3
- package/src/lane/lane-report.ts +8 -30
- package/src/lane/lane-rows.ts +1 -1
- package/src/lane/workflow.ts +44 -3
- package/src/lane-extension.ts +5 -46
- package/src/messaging/discord-context.ts +8 -6
- package/src/omp/host-protocol.ts +4 -3
- package/src/omp/host.ts +24 -7
- package/src/omp/managed-super.ts +43 -27
- package/src/omp/native-sessions.ts +12 -0
- package/src/omp/worker-memory-import.ts +410 -0
- package/src/omp/worker-memory-sdk.ts +8 -0
- package/src/operator/setup.ts +8 -13
- package/src/pr/pr-github-schema.ts +9 -0
- package/src/pr/pr-github.ts +6 -2
- package/src/pr/pr-intake-automation.ts +11 -8
- package/src/pr/pr-intake-fix.ts +2 -5
- package/src/pr/pr-intake-review.ts +7 -7
- package/src/routing/topic-history.ts +2 -2
- package/src/runtime/controller.ts +444 -408
- package/src/runtime/head-recovery.ts +7 -7
- package/src/runtime/worker-memory.ts +156 -0
- package/src/storage/deferred-routing.ts +1 -7
- package/src/storage/store.ts +441 -375
- package/src/worker/worker-host.ts +3 -2
- package/src/worker/worker-ledger.ts +20 -11
- package/src/worker/worker-memory-page.ts +83 -0
- package/src/worker/worker-memory-proofs.ts +260 -0
- package/src/worker/worker-memory-source.ts +305 -0
- package/src/worker/worker-memory-storage.ts +130 -0
- package/src/worker/worker-profile.ts +2 -0
- package/src/worker/worker-repository.ts +92 -7
- package/src/worker/worker-request.ts +1 -0
- package/src/worker/worker-service.ts +25 -8
- package/src/worker/worker-wire.ts +20 -6
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
3
|
+
import { lookup as lookupSetting } from "@oh-my-pi/pi-coding-agent/config/registry";
|
|
4
|
+
import type { AgentSession } from "@oh-my-pi/pi-coding-agent/session/agent-session";
|
|
5
|
+
import type { MnemopiSessionState } from "@oh-my-pi/pi-coding-agent/memory-backend";
|
|
6
|
+
import { nativeMemoryProjectCwd } from "../omp/native-sessions";
|
|
7
|
+
import { isWorkerMemoryCursor, isWorkerMemoryStamp, parseWorkerMemoryPage, safeWorkerMemoryText, workerMemoryId,
|
|
8
|
+
WORKER_MEMORY_PAGE_BYTES, WORKER_MEMORY_ROWS, WORKER_MEMORY_TEXT_BYTES, type WorkerMemoryRecord } from "./worker-memory-page";
|
|
9
|
+
import { checkWorkerMemoryFiles, readWorkerMemoryIdentity, workerMemoryPaths } from "./worker-memory-storage";
|
|
10
|
+
import { ownsCheckout } from "./worker-checkout";
|
|
11
|
+
import { sameWorkerFactEntry, sameWorkerFactResult, workerFactDigest, workerFactEntry, workerFactProofs, workerFactResult,
|
|
12
|
+
type WorkerFactCarrier, type WorkerFactEntry, type WorkerFactTool } from "./worker-memory-proofs";
|
|
13
|
+
import { workerMemoryCheckoutStamp, workerMemoryRepositoryMatches } from "./worker-repository";
|
|
14
|
+
import { WorkerRefusal } from "./worker-request";
|
|
15
|
+
|
|
16
|
+
const memoryScanRows = 64;
|
|
17
|
+
const metadataBytes = 8192;
|
|
18
|
+
const journalTailBytes = 128 * 1024;
|
|
19
|
+
type NativeMemory = Pick<MnemopiSessionState["memory"], "beam" | "get">;
|
|
20
|
+
type MemoryOrigin = { readonly sessionId: string; readonly cwd: string; readonly bank: string;
|
|
21
|
+
readonly attempt: string; readonly bankFile: string };
|
|
22
|
+
type Candidate = { readonly at: number; readonly id: string | null };
|
|
23
|
+
type PageRequest = { readonly after: number; readonly unchanged?: string };
|
|
24
|
+
type Proofs = ReturnType<typeof workerFactProofs>;
|
|
25
|
+
type FactBatch = NonNullable<ReturnType<typeof workerFactResult>>;
|
|
26
|
+
type FactReturn = { readonly entry: WorkerFactEntry; readonly batch: FactBatch };
|
|
27
|
+
type FactObservation = { readonly carrier: WorkerFactCarrier; started?: WorkerFactEntry; returned?: FactReturn;
|
|
28
|
+
checkout?: { readonly stamp: string; readonly verified: Promise<boolean> } };
|
|
29
|
+
|
|
30
|
+
function unavailable(): never {
|
|
31
|
+
throw new WorkerRefusal("Worker memory is unavailable");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function originContent(raw: unknown, id: string, origin: MemoryOrigin): {
|
|
35
|
+
readonly content: string; readonly tool: WorkerFactTool;
|
|
36
|
+
} | null {
|
|
37
|
+
if (!raw || typeof raw !== "object" || !("memory_store" in raw) || raw.memory_store !== "working"
|
|
38
|
+
|| !("id" in raw) || raw.id !== id || !("veracity" in raw) || raw.veracity !== "tool"
|
|
39
|
+
|| !("session_id" in raw) || raw.session_id !== origin.bank || !("source" in raw)
|
|
40
|
+
|| (raw.source !== "coding-agent-retain" && raw.source !== "coding-agent-learn")
|
|
41
|
+
|| !("metadata_json" in raw) || typeof raw.metadata_json !== "string"
|
|
42
|
+
|| Buffer.byteLength(raw.metadata_json, "utf8") > metadataBytes
|
|
43
|
+
|| !("valid_until" in raw) || raw.valid_until !== null || !("superseded_by" in raw) || raw.superseded_by !== null
|
|
44
|
+
|| !("content" in raw) || typeof raw.content !== "string" || !safeWorkerMemoryText(raw.content)) return null;
|
|
45
|
+
let metadata: unknown;
|
|
46
|
+
try { metadata = JSON.parse(raw.metadata_json); }
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (error instanceof SyntaxError) return null;
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
if (!metadata || typeof metadata !== "object" || Object.keys(metadata).length !== 4
|
|
52
|
+
|| !("session_id" in metadata) || metadata.session_id !== origin.sessionId
|
|
53
|
+
|| !("cwd" in metadata) || metadata.cwd !== origin.cwd
|
|
54
|
+
|| !("context" in metadata) || (metadata.context !== null && typeof metadata.context !== "string")
|
|
55
|
+
|| !("tool" in metadata) || (raw.source === "coding-agent-retain" ? metadata.tool !== "retain" : metadata.tool !== "learn")) return null;
|
|
56
|
+
return { content: raw.content, tool: metadata.tool === "retain" ? "retain" : "learn" } as const;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** SQLite only locates bounded candidate IDs. The native row API supplies the content and origin. */
|
|
60
|
+
export function readWorkerMemoryPage(memory: NativeMemory, origin: MemoryOrigin & { readonly proofs: Proofs }, { after, unchanged }: PageRequest) {
|
|
61
|
+
const { beam } = memory;
|
|
62
|
+
if (!isWorkerMemoryCursor(after) || !beam.pendingExtractions || beam.pendingExtractions.size !== 0
|
|
63
|
+
|| (unchanged !== undefined && (after !== 0 || !isWorkerMemoryStamp(unchanged)))
|
|
64
|
+
|| beam.db.inTransaction) unavailable();
|
|
65
|
+
return beam.db.transaction(() => {
|
|
66
|
+
const { db } = beam;
|
|
67
|
+
using total = db.prepare<{ changes: string }, []>("SELECT CAST(total_changes() AS TEXT) AS changes");
|
|
68
|
+
using version = db.prepare<{ data_version: number }, []>("PRAGMA main.data_version");
|
|
69
|
+
const changes = total.get()?.changes;
|
|
70
|
+
const dataVersion = version.get()?.data_version;
|
|
71
|
+
if (typeof changes !== "string" || dataVersion === undefined || !Number.isSafeInteger(dataVersion)) unavailable();
|
|
72
|
+
const proofVersion = origin.proofs.version();
|
|
73
|
+
const stamp = createHash("sha256").update(JSON.stringify([origin.attempt, origin.bankFile, changes, dataVersion, proofVersion])).digest("hex");
|
|
74
|
+
if (stamp === unchanged) return { after, next: 0, records: [], stamp };
|
|
75
|
+
using table = db.prepare<{ type: string; wr: number }, []>("PRAGMA main.table_list('working_memory')");
|
|
76
|
+
const layout = table.get();
|
|
77
|
+
if (layout?.type !== "table" || layout.wr !== 0) unavailable();
|
|
78
|
+
using shadow = db.prepare("PRAGMA temp.table_list('working_memory')");
|
|
79
|
+
if (shadow.get()) unavailable();
|
|
80
|
+
// No WHERE filter on origin in the keyset: bad rows still consume scan work.
|
|
81
|
+
// Walk a bounded rowid range, then wrap to zero at end. Rowid is not identity;
|
|
82
|
+
// edits, deletions, native dedupe and rowid reuse cannot permanently hide IDs.
|
|
83
|
+
using keyset = db.prepare<Candidate, [string, number]>(`
|
|
84
|
+
SELECT rowid AS at, CASE WHEN
|
|
85
|
+
typeof(id) = 'text' AND octet_length(id) = 16
|
|
86
|
+
AND scope = 'bank' AND session_id = ?1 AND channel_id = ?1
|
|
87
|
+
AND author_id = 'coding-agent' AND author_type = 'agent'
|
|
88
|
+
AND source IN ('coding-agent-retain', 'coding-agent-learn')
|
|
89
|
+
AND veracity = 'tool' AND memory_type = 'fact' AND trust_tier = 'STATED'
|
|
90
|
+
AND valid_until IS NULL AND superseded_by IS NULL
|
|
91
|
+
AND typeof(content) = 'text' AND octet_length(content) BETWEEN 1 AND ${WORKER_MEMORY_TEXT_BYTES}
|
|
92
|
+
AND typeof(metadata_json) = 'text' AND octet_length(metadata_json) BETWEEN 1 AND ${metadataBytes}
|
|
93
|
+
AND octet_length(timestamp) <= 64 AND octet_length(created_at) <= 64
|
|
94
|
+
THEN id ELSE NULL END AS id
|
|
95
|
+
FROM main.working_memory WHERE rowid > ?2 ORDER BY rowid LIMIT ${memoryScanRows + 1}
|
|
96
|
+
`);
|
|
97
|
+
const keys = keyset.all(origin.bank, after);
|
|
98
|
+
using proofs = origin.proofs.lookup();
|
|
99
|
+
const records: WorkerMemoryRecord[] = [];
|
|
100
|
+
let position = after;
|
|
101
|
+
for (const { at, id } of keys.slice(0, memoryScanRows)) {
|
|
102
|
+
if (!Number.isSafeInteger(at) || at <= position) unavailable();
|
|
103
|
+
if (id && workerMemoryId.test(id)) {
|
|
104
|
+
const found = originContent(memory.get(id), id, origin);
|
|
105
|
+
if (found !== null && proofs.has(workerFactDigest(origin, found.tool, found.content))) {
|
|
106
|
+
const { content } = found;
|
|
107
|
+
const record = { at, id, content };
|
|
108
|
+
const candidate = { after, next: at, records: [...records, record], stamp };
|
|
109
|
+
if (records.length === WORKER_MEMORY_ROWS || Buffer.byteLength(JSON.stringify(candidate), "utf8") + 16 > WORKER_MEMORY_PAGE_BYTES) {
|
|
110
|
+
if (origin.proofs.version() !== proofVersion) unavailable();
|
|
111
|
+
return parseWorkerMemoryPage({ after, next: position, records, stamp }, after);
|
|
112
|
+
}
|
|
113
|
+
records.push(record);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
position = at;
|
|
117
|
+
}
|
|
118
|
+
if (origin.proofs.version() !== proofVersion) unavailable();
|
|
119
|
+
return parseWorkerMemoryPage({ after, next: keys.length > memoryScanRows ? position : 0, records, stamp }, after);
|
|
120
|
+
})();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function durableJournalTail(file: string, expectedId: string): boolean {
|
|
124
|
+
if (realpathSync(file) !== file) return false;
|
|
125
|
+
using journal = {
|
|
126
|
+
fd: openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK),
|
|
127
|
+
[Symbol.dispose]() { closeSync(this.fd); },
|
|
128
|
+
};
|
|
129
|
+
const start = fstatSync(journal.fd, { bigint: true });
|
|
130
|
+
if (!start.isFile() || start.uid !== BigInt(process.getuid?.() ?? -1) || start.nlink !== 1n
|
|
131
|
+
|| (start.mode & 0o022n) !== 0n || start.size > BigInt(Number.MAX_SAFE_INTEGER)) return false;
|
|
132
|
+
const length = Math.min(Number(start.size), journalTailBytes);
|
|
133
|
+
const offset = Number(start.size) - length;
|
|
134
|
+
const tail = Buffer.alloc(length);
|
|
135
|
+
if (readSync(journal.fd, tail, 0, length, offset) !== length || tail.at(-1) !== 10) return false;
|
|
136
|
+
const end = length - 1;
|
|
137
|
+
const delimiter = end > 0 ? tail.lastIndexOf(10, end - 1) : -1;
|
|
138
|
+
if (delimiter < 0 && offset > 0) return false;
|
|
139
|
+
let row: unknown;
|
|
140
|
+
try { row = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(tail.subarray(delimiter + 1, end))); }
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (error instanceof SyntaxError || error instanceof TypeError) return false;
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
const current = lstatSync(file, { bigint: true });
|
|
146
|
+
return current.dev === start.dev && current.ino === start.ino && current.size === start.size
|
|
147
|
+
&& current.mtimeNs === start.mtimeNs && current.ctimeNs === start.ctimeNs
|
|
148
|
+
&& !!row && typeof row === "object" && "id" in row && row.id === expectedId;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Bind one live root's native memory object, native profile, journal, bank and file inode. */
|
|
152
|
+
export function bindWorkerMemorySource(session: AgentSession, binding: { readonly encoded: string; readonly file: string; readonly attempt: string }) {
|
|
153
|
+
const { encoded, file, attempt } = binding;
|
|
154
|
+
const identity = readWorkerMemoryIdentity(encoded);
|
|
155
|
+
if (!identity.proof) unavailable();
|
|
156
|
+
const paths = workerMemoryPaths({ ...identity, sessionFile: file });
|
|
157
|
+
const journal = session.sessionManager;
|
|
158
|
+
// The running CLI owns the effective descriptors. Compiled OMP exposes
|
|
159
|
+
// its populated registry to extensions, not every SDK domain module.
|
|
160
|
+
const backend = lookupSetting("memory.backend");
|
|
161
|
+
const scoping = lookupSetting("mnemopi.scoping");
|
|
162
|
+
const dbPath = lookupSetting("mnemopi.dbPath");
|
|
163
|
+
if (!backend || !scoping || !dbPath) unavailable();
|
|
164
|
+
// SQLite counters are scoped to an open connection. A setting transition
|
|
165
|
+
// may reopen the same inode during one native attempt, resetting them.
|
|
166
|
+
const origin = { sessionId: journal.getSessionId(), cwd: identity.cwd, bank: paths.bank, attempt,
|
|
167
|
+
bankFile: `${identity.file}:${crypto.randomUUID()}`, proofs: workerFactProofs(paths.proofsPath, identity.proof) };
|
|
168
|
+
if (typeof session.getMnemopiSessionState !== "function" || typeof journal.getEntriesView !== "function"
|
|
169
|
+
|| typeof journal.onPersistenceError !== "function") unavailable();
|
|
170
|
+
const state = session.getMnemopiSessionState();
|
|
171
|
+
if (!state || state.aliasOf || state.session !== session) unavailable();
|
|
172
|
+
const memory = state.getScopedRetainTarget().memory;
|
|
173
|
+
const claim = { gitDir: identity.checkout.gitDir, attempt };
|
|
174
|
+
const checkoutStamp = () => ownsCheckout(claim) ? workerMemoryCheckoutStamp(origin.cwd, identity.checkout) : null;
|
|
175
|
+
const verifiedCheckout = async (stamp: string) => {
|
|
176
|
+
try {
|
|
177
|
+
return checkoutStamp() === stamp && await workerMemoryRepositoryMatches(origin.cwd, identity.checkout)
|
|
178
|
+
&& checkoutStamp() === stamp;
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (error instanceof Error) return false;
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const nativePaths = () => {
|
|
185
|
+
using databases = memory.beam.db.prepare<{ name: string; file: string }, []>("PRAGMA database_list");
|
|
186
|
+
const open = databases.all();
|
|
187
|
+
return open.find(entry => entry.name === "main")?.file === paths.dbPath
|
|
188
|
+
&& open.every(entry => entry.name === "main" || entry.name === "temp" && !entry.file);
|
|
189
|
+
};
|
|
190
|
+
const validate = () => {
|
|
191
|
+
const config = state.config;
|
|
192
|
+
const recall = state.getScopedRecallTargets();
|
|
193
|
+
const settingsCwd = session.settings.getCwd();
|
|
194
|
+
if (session.memoryEnabled !== true || backend.get(session.settings) !== "mnemopi"
|
|
195
|
+
|| scoping.get(session.settings) !== "per-project" || dbPath.get(session.settings) !== paths.base
|
|
196
|
+
|| session.getMnemopiSessionState() !== state || state.sessionId !== origin.sessionId
|
|
197
|
+
|| journal.getSessionId() !== origin.sessionId || journal.getSessionFile() !== file
|
|
198
|
+
|| journal.getCwd() !== origin.cwd || realpathSync(origin.cwd) !== origin.cwd
|
|
199
|
+
|| (settingsCwd !== origin.cwd && settingsCwd !== nativeMemoryProjectCwd(origin.cwd)) || realpathSync(settingsCwd) !== origin.cwd
|
|
200
|
+
|| session.settings.getAgentDir() !== identity.agentDir || realpathSync(identity.agentDir) !== identity.agentDir
|
|
201
|
+
|| config.dbPath !== paths.base || config.scoping !== "per-project" || config.retainBank !== origin.bank
|
|
202
|
+
|| !ownsCheckout(claim)
|
|
203
|
+
|| recall.length !== 1 || recall[0]?.memory !== memory || recall[0].bank !== origin.bank
|
|
204
|
+
|| state.getScopedRetainTarget().memory !== memory || typeof memory.get !== "function"
|
|
205
|
+
|| memory.beam?.dbPath !== paths.dbPath || memory.beam.sessionId !== origin.bank
|
|
206
|
+
|| !Number.isSafeInteger(memory.beam.pendingExtractions?.size)
|
|
207
|
+
|| typeof memory.beam.db?.transaction !== "function" || !nativePaths()) unavailable();
|
|
208
|
+
checkWorkerMemoryFiles(paths, identity.file);
|
|
209
|
+
};
|
|
210
|
+
validate();
|
|
211
|
+
// Older receipts have no witness. A fresh receipt still needs an exact
|
|
212
|
+
// reserved file and schema before the native owner can advertise transfer.
|
|
213
|
+
{
|
|
214
|
+
using proof = origin.proofs.lookup();
|
|
215
|
+
proof.check();
|
|
216
|
+
}
|
|
217
|
+
// Wrapper tool_result and the root's event stream may be scheduled
|
|
218
|
+
// independently. Hold only bounded digests until the root's terminal event.
|
|
219
|
+
const facts = new Map<string, FactObservation>();
|
|
220
|
+
let pending = 0;
|
|
221
|
+
let closed = false;
|
|
222
|
+
const nativeTool = (tool: WorkerFactTool) => session.getAllToolInfos().some(info =>
|
|
223
|
+
info.name === tool && info.sourceInfo.source === "builtin" && info.sourceInfo.path === `<builtin:${tool}>`);
|
|
224
|
+
const observe = (carrier: WorkerFactCarrier, id: string, event: { readonly started: WorkerFactEntry } | { readonly returned: FactReturn }) => {
|
|
225
|
+
if (!id || id.length > 256) return;
|
|
226
|
+
const current = facts.get(id);
|
|
227
|
+
if (current) {
|
|
228
|
+
if (current.carrier !== carrier || ("started" in event ? current.started !== undefined : current.returned !== undefined))
|
|
229
|
+
facts.delete(id);
|
|
230
|
+
else Object.assign(current, event);
|
|
231
|
+
} else if (facts.size + pending < WORKER_MEMORY_ROWS) facts.set(id, { carrier, ...event });
|
|
232
|
+
};
|
|
233
|
+
let journalFailed = false;
|
|
234
|
+
const unsubscribe = journal.onPersistenceError(() => { journalFailed = true; });
|
|
235
|
+
return {
|
|
236
|
+
validate,
|
|
237
|
+
close() { closed = true; facts.clear(); unsubscribe(); },
|
|
238
|
+
clearFactStarts() { facts.clear(); },
|
|
239
|
+
startFact(carrier: WorkerFactCarrier, id: string, input: unknown) {
|
|
240
|
+
const entry = workerFactEntry(origin, carrier, input);
|
|
241
|
+
if (!entry || (entry.kind === "mounted" && !nativeTool(entry.tool))) return;
|
|
242
|
+
validate();
|
|
243
|
+
const stamp = checkoutStamp();
|
|
244
|
+
if (!stamp) return;
|
|
245
|
+
observe(carrier, id, { started: entry });
|
|
246
|
+
const observation = facts.get(id);
|
|
247
|
+
if (observation?.started === entry && pending < WORKER_MEMORY_ROWS) {
|
|
248
|
+
pending++;
|
|
249
|
+
observation.checkout = { stamp, verified: verifiedCheckout(stamp).finally(() => { pending--; }) };
|
|
250
|
+
// An asynchronous metadata read can finish after an interrupted start.
|
|
251
|
+
void observation.checkout.verified.catch(() => {});
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
returnFact(event: {
|
|
255
|
+
readonly toolName: WorkerFactCarrier; readonly toolCallId: string; readonly parentToolCallId?: string;
|
|
256
|
+
readonly isError: boolean; readonly input: unknown; readonly details?: unknown;
|
|
257
|
+
}) {
|
|
258
|
+
if (event.isError || event.parentToolCallId !== undefined) return;
|
|
259
|
+
const entry = workerFactEntry(origin, event.toolName, event.input);
|
|
260
|
+
if (!entry || (entry.kind === "mounted" && !nativeTool(entry.tool))) return;
|
|
261
|
+
const batch = workerFactResult(origin, entry, event.details);
|
|
262
|
+
if (!batch) return;
|
|
263
|
+
validate();
|
|
264
|
+
observe(event.toolName, event.toolCallId, { returned: { entry, batch } });
|
|
265
|
+
},
|
|
266
|
+
finishFact(carrier: WorkerFactCarrier, id: string, success: boolean, result: unknown) {
|
|
267
|
+
const observation = facts.get(id);
|
|
268
|
+
facts.delete(id);
|
|
269
|
+
const { started, returned, checkout } = observation ?? {};
|
|
270
|
+
if (!success || observation?.carrier !== carrier || !started || !returned || !sameWorkerFactEntry(started, returned.entry)
|
|
271
|
+
|| (started.kind === "mounted" && !nativeTool(started.tool)) || !result || typeof result !== "object"
|
|
272
|
+
|| !("details" in result) || !sameWorkerFactResult(returned.batch, workerFactResult(origin, started, result.details))
|
|
273
|
+
|| !checkout || pending >= WORKER_MEMORY_ROWS || checkoutStamp() !== checkout.stamp) return;
|
|
274
|
+
validate();
|
|
275
|
+
pending++;
|
|
276
|
+
void Promise.all([checkout.verified, verifiedCheckout(checkout.stamp)]).then(([entered, completed]) => {
|
|
277
|
+
if (closed || !entered || !completed || checkoutStamp() !== checkout.stamp) return;
|
|
278
|
+
validate();
|
|
279
|
+
origin.proofs.seal(returned.batch);
|
|
280
|
+
}).catch(() => { /* An uncertain witness never affects a successful native write. */ })
|
|
281
|
+
.finally(() => { pending--; });
|
|
282
|
+
},
|
|
283
|
+
async verifyCheckout() {
|
|
284
|
+
const stamp = checkoutStamp();
|
|
285
|
+
if (!stamp || !await verifiedCheckout(stamp)) unavailable();
|
|
286
|
+
},
|
|
287
|
+
page(request: PageRequest, hasRun: boolean) {
|
|
288
|
+
validate();
|
|
289
|
+
const last = journal.getEntriesView().at(-1)?.id ?? origin.sessionId;
|
|
290
|
+
// Stock's first-turn background recall commits synchronously once this
|
|
291
|
+
// flag is set. If a started run has not reached it, absence of work is unknown.
|
|
292
|
+
if (pending !== 0 || journalFailed || (hasRun && state.config.autoRecall && !state.hasRecalledForFirstTurn)
|
|
293
|
+
|| !durableJournalTail(file, last)) unavailable();
|
|
294
|
+
const page = readWorkerMemoryPage(memory, origin, request);
|
|
295
|
+
return {
|
|
296
|
+
page,
|
|
297
|
+
assertCurrent() {
|
|
298
|
+
validate();
|
|
299
|
+
if (pending !== 0 || journalFailed || memory.beam.pendingExtractions.size !== 0
|
|
300
|
+
|| (journal.getEntriesView().at(-1)?.id ?? origin.sessionId) !== last) unavailable();
|
|
301
|
+
},
|
|
302
|
+
};
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, opendirSync, openSync, realpathSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { Type, type Static } from "@sinclair/typebox/type";
|
|
5
|
+
import { Value } from "@sinclair/typebox/value";
|
|
6
|
+
import type { NativeProfile } from "../omp/native-sessions";
|
|
7
|
+
import { privateWorkerDirectory } from "./worker-checkout";
|
|
8
|
+
import { reserveWorkerFactProofs, workerFactProofs } from "./worker-memory-proofs";
|
|
9
|
+
import { WorkerRefusal } from "./worker-request";
|
|
10
|
+
|
|
11
|
+
export const WORKER_MEMORY_WIRE_ENV = "OMP_SUPERAGENT_WORKER_MEMORY_WIRE";
|
|
12
|
+
export const WORKER_MEMORY_ENV = "OMP_SUPERAGENT_WORKER_MEMORY";
|
|
13
|
+
export const WORKER_MEMORY_PROFILE_ENV = "OMP_SUPERAGENT_WORKER_MEMORY_PROFILE";
|
|
14
|
+
const strict = { additionalProperties: false } as const;
|
|
15
|
+
const storageKey = Type.String({ pattern: "^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}(?![\\s\\S])" });
|
|
16
|
+
const bankFile = Type.String({ pattern: "^[0-9]+:[0-9]+(?![\\s\\S])" });
|
|
17
|
+
const bankName = Type.String({ minLength: 1, maxLength: 64, pattern: "^[A-Za-z0-9_-]+(?![\\s\\S])" });
|
|
18
|
+
export const workerMemoryBinding = Type.Object({
|
|
19
|
+
key: storageKey,
|
|
20
|
+
profile: Type.String({ pattern: "^[0-9a-f]{64}$" }),
|
|
21
|
+
bank: bankName,
|
|
22
|
+
file: bankFile,
|
|
23
|
+
proof: Type.Optional(bankFile),
|
|
24
|
+
}, strict);
|
|
25
|
+
export type WorkerMemoryBinding = Readonly<Static<typeof workerMemoryBinding>>;
|
|
26
|
+
const checkout = Type.Object({
|
|
27
|
+
repoRoot: Type.String({ minLength: 1, maxLength: 4096 }),
|
|
28
|
+
gitDir: Type.String({ minLength: 1, maxLength: 4096 }),
|
|
29
|
+
repoId: Type.String({ pattern: "^[0-9a-f]{64}(?![\\s\\S])" }),
|
|
30
|
+
revision: Type.String({ pattern: "^(?:[0-9a-f]{40}|[0-9a-f]{64})(?![\\s\\S])" }),
|
|
31
|
+
subdir: Type.String({ maxLength: 2048 }),
|
|
32
|
+
}, strict);
|
|
33
|
+
export type WorkerMemoryCheckout = Readonly<Static<typeof checkout>>;
|
|
34
|
+
export type WorkerMemoryLaunch = {
|
|
35
|
+
readonly key: string;
|
|
36
|
+
readonly checkout: WorkerMemoryCheckout;
|
|
37
|
+
readonly previous?: WorkerMemoryBinding;
|
|
38
|
+
};
|
|
39
|
+
export type WorkerMemoryPlan = { readonly bank: string; readonly profile: NativeProfile };
|
|
40
|
+
const identity = Type.Object({ key: storageKey, bank: bankName, file: bankFile, proof: Type.Optional(bankFile),
|
|
41
|
+
agentDir: Type.String(), cwd: Type.String(), checkout }, strict);
|
|
42
|
+
type MemoryIdentity = Readonly<Static<typeof identity>>;
|
|
43
|
+
|
|
44
|
+
export function readWorkerMemoryIdentity(encoded: string): MemoryIdentity {
|
|
45
|
+
const value: unknown = JSON.parse(encoded);
|
|
46
|
+
if (!Value.Check(identity, value)) throw new WorkerRefusal("Worker memory launch identity is invalid");
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type MemoryLocation = {
|
|
51
|
+
readonly key: string;
|
|
52
|
+
readonly bank: string;
|
|
53
|
+
readonly sessionFile: string;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export function workerMemoryPaths({ key, bank, sessionFile }: MemoryLocation) {
|
|
57
|
+
if (!Value.Check(storageKey, key) || !Value.Check(bankName, bank) || bank === "default")
|
|
58
|
+
throw new WorkerRefusal("Invalid worker memory location");
|
|
59
|
+
const sessionDir = dirname(sessionFile);
|
|
60
|
+
const dir = join(sessionDir, `memory-${key}`);
|
|
61
|
+
const base = join(dir, "mnemopi.db");
|
|
62
|
+
const banks = join(dir, "banks");
|
|
63
|
+
const bankDir = join(banks, bank);
|
|
64
|
+
return { sessionDir, dir, base, banks, bankDir, bank, dbPath: join(bankDir, "mnemopi.db"),
|
|
65
|
+
blobs: join(dir, "blobs"), proofsPath: join(dir, "fact-proofs.sqlite") };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function ownedMemoryFile(file: string) {
|
|
69
|
+
const stat = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
70
|
+
if (!stat) return;
|
|
71
|
+
if (!stat.isFile() || stat.nlink !== 1n || stat.uid !== BigInt(process.getuid?.() ?? -1)
|
|
72
|
+
|| (stat.mode & 0o022n) !== 0n || realpathSync(file) !== file)
|
|
73
|
+
throw new WorkerRefusal("Worker memory contains a non-private file");
|
|
74
|
+
return `${stat.dev}:${stat.ino}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function checkWorkerMemoryFiles(paths: ReturnType<typeof workerMemoryPaths>, expected: string): void {
|
|
78
|
+
for (const directory of [paths.sessionDir, paths.dir, paths.banks, paths.bankDir, paths.blobs])
|
|
79
|
+
if (!privateWorkerDirectory(directory)) throw new WorkerRefusal("Worker memory directory is unavailable");
|
|
80
|
+
if (ownedMemoryFile(paths.base) !== undefined || ownedMemoryFile(paths.dbPath) !== expected)
|
|
81
|
+
throw new WorkerRefusal("Worker memory database identity changed");
|
|
82
|
+
for (const suffix of ["-wal", "-shm", "-journal"]) ownedMemoryFile(`${paths.dbPath}${suffix}`);
|
|
83
|
+
// Native recall may discover legacy sibling banks. There must be none.
|
|
84
|
+
const entries = opendirSync(paths.banks);
|
|
85
|
+
try {
|
|
86
|
+
if (entries.readSync()?.name !== paths.bank || entries.readSync() !== null)
|
|
87
|
+
throw new WorkerRefusal("Worker memory must contain only its private bank");
|
|
88
|
+
} finally { entries.closeSync(); }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function prepareWorkerMemory(request: WorkerMemoryLaunch, launch: {
|
|
92
|
+
readonly sessionFile: string; readonly cwd: string;
|
|
93
|
+
}, plan: WorkerMemoryPlan) {
|
|
94
|
+
const { bank, profile: { agentDir, dataDir, sessionsDir } } = plan;
|
|
95
|
+
const profile = createHash("sha256").update(JSON.stringify([agentDir, dataDir, sessionsDir])).digest("hex");
|
|
96
|
+
if (request.previous && (request.previous.profile !== profile || request.previous.bank !== bank
|
|
97
|
+
|| request.previous.key !== request.key))
|
|
98
|
+
throw new WorkerRefusal("Worker memory native profile or bank changed");
|
|
99
|
+
const paths = workerMemoryPaths({ key: request.key, bank, sessionFile: launch.sessionFile });
|
|
100
|
+
let file = request.previous?.file;
|
|
101
|
+
let proof = request.previous?.proof;
|
|
102
|
+
if (file === undefined) {
|
|
103
|
+
// The random lane-owned directory must be new. Never adopt an existing store.
|
|
104
|
+
for (const directory of [paths.dir, paths.banks, paths.bankDir, paths.blobs]) mkdirSync(directory, { mode: 0o700 });
|
|
105
|
+
const fd = openSync(paths.dbPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
106
|
+
try {
|
|
107
|
+
const stat = fstatSync(fd, { bigint: true });
|
|
108
|
+
file = `${stat.dev}:${stat.ino}`;
|
|
109
|
+
} finally { closeSync(fd); }
|
|
110
|
+
proof = reserveWorkerFactProofs(paths.proofsPath);
|
|
111
|
+
}
|
|
112
|
+
checkWorkerMemoryFiles(paths, file);
|
|
113
|
+
if (request.previous && proof) {
|
|
114
|
+
try { workerFactProofs(paths.proofsPath, proof).recover(); }
|
|
115
|
+
catch (error) {
|
|
116
|
+
// Damaged optional evidence cannot keep the original private bank or
|
|
117
|
+
// its native workload from opening. Live evidence checks will refuse.
|
|
118
|
+
if (!(error instanceof Error)) throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
binding: { key: request.key, bank, profile, file, ...(proof && { proof }) },
|
|
123
|
+
config: { mnemopi: { dbPath: paths.base } },
|
|
124
|
+
env: {
|
|
125
|
+
[WORKER_MEMORY_ENV]: JSON.stringify({ key: request.key, bank, file, proof, agentDir, cwd: launch.cwd, checkout: request.checkout }),
|
|
126
|
+
MNEMOPI_DATA_DIR: paths.dir,
|
|
127
|
+
MNEMOPI_BLOB_DIR: paths.blobs,
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
@@ -6,12 +6,14 @@ import { gitWorkerRepository } from "./worker-repository";
|
|
|
6
6
|
import { WorkerRefusal } from "./worker-request";
|
|
7
7
|
import { trustedWorkerPath, workerInstallRoot } from "./worker-trust";
|
|
8
8
|
import type { WorkerPolicy, WorkerRepo } from "./worker-wire";
|
|
9
|
+
import type { WorkerMemoryLaunch } from "./worker-memory-storage";
|
|
9
10
|
|
|
10
11
|
export interface WorkerHostProfile {
|
|
11
12
|
readonly config: Readonly<Record<string, unknown>>;
|
|
12
13
|
readonly flags: readonly string[];
|
|
13
14
|
readonly extensionPaths: readonly string[];
|
|
14
15
|
readonly managedUlwPath: string;
|
|
16
|
+
readonly memory?: WorkerMemoryLaunch;
|
|
15
17
|
}
|
|
16
18
|
|
|
17
19
|
const flags = ["--no-extensions", "--no-lsp"] as const;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { constants } from "node:fs";
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
3
3
|
import { lstat, open, readlink, realpath } from "node:fs/promises";
|
|
4
4
|
import { dirname, isAbsolute, join, relative, sep } from "node:path";
|
|
5
5
|
import type { WorkerLaneRef } from "./worker-wire";
|
|
@@ -22,7 +22,11 @@ function gitProcess(cwd: string, args: readonly string[], timeout?: number) {
|
|
|
22
22
|
|
|
23
23
|
/** Read the local Git repository without ambient Git configuration, hooks, or network access. */
|
|
24
24
|
export async function gitWorkerRepository(cwd: string, args: readonly string[]): Promise<string | null> {
|
|
25
|
-
|
|
25
|
+
return await readWorkerGit(cwd, args, gitTimeoutMs);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function readWorkerGit(cwd: string, args: readonly string[], timeout: number): Promise<string | null> {
|
|
29
|
+
const git = gitProcess(cwd, args, timeout);
|
|
26
30
|
const reader = git.stdout.getReader();
|
|
27
31
|
const decoder = new TextDecoder();
|
|
28
32
|
let size = 0;
|
|
@@ -51,8 +55,8 @@ function unavailablePath(error: unknown): boolean {
|
|
|
51
55
|
&& ["ENOENT", "ENOTDIR", "ELOOP", "EACCES", "EPERM", "EINVAL"].includes(error.code);
|
|
52
56
|
}
|
|
53
57
|
|
|
54
|
-
async function checkoutRoot(canonical: string): Promise<string | null> {
|
|
55
|
-
const layout = await
|
|
58
|
+
async function checkoutRoot(canonical: string, git = gitWorkerRepository): Promise<string | null> {
|
|
59
|
+
const layout = await git(canonical,
|
|
56
60
|
["rev-parse", "--path-format=absolute", "--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
|
|
57
61
|
const [root, gitDir, commonDir, end, ...extra] = layout?.split("\n") ?? [];
|
|
58
62
|
if (!root || !isAbsolute(root) || controls.test(root) || end !== "" || extra.length) return null;
|
|
@@ -64,13 +68,17 @@ async function checkoutRoot(canonical: string): Promise<string | null> {
|
|
|
64
68
|
return root;
|
|
65
69
|
}
|
|
66
70
|
|
|
67
|
-
async function repositoryIdentity(root: string): Promise<string | null> {
|
|
71
|
+
async function repositoryIdentity(root: string, git = gitWorkerRepository): Promise<string | null> {
|
|
68
72
|
// Resolve effective fetch URLs locally, including insteadOf rules. Require
|
|
69
73
|
// exactly one URL, and omit credentials from the hashed identity.
|
|
70
|
-
const output = await
|
|
74
|
+
const output = await git(root, ["remote", "get-url", "--all", "origin"]);
|
|
71
75
|
if (output === null) return null;
|
|
72
76
|
const [origin, end, ...extra] = output.split("\n");
|
|
73
|
-
|
|
77
|
+
return origin && end === "" && !extra.length ? repositoryOriginId(origin) : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function repositoryOriginId(origin: string): string | null {
|
|
81
|
+
if (/[\s?#\\]/u.test(origin)) return null;
|
|
74
82
|
const scp = /^(?:([A-Za-z0-9_.-]+)@)?([A-Za-z0-9.-]+):([^/][^:]*)$/.exec(origin);
|
|
75
83
|
const url = URL.parse(scp ? `ssh://${scp[1] ? `${scp[1]}@` : ""}${scp[2]}/${scp[3]}` : origin);
|
|
76
84
|
if (!url || !["http:", "https:", "ssh:"].includes(url.protocol)
|
|
@@ -112,6 +120,83 @@ function withinTree(path: string): boolean {
|
|
|
112
120
|
part && part !== ".." && part !== "." && part.toLowerCase() !== ".git"));
|
|
113
121
|
}
|
|
114
122
|
|
|
123
|
+
/** Re-attest only the workspace's identity, without scanning the index or tracked bytes. */
|
|
124
|
+
export async function workerMemoryRepositoryMatches(cwd: string, expected: Pick<WorkerLaneRef, "repoId" | "revision" | "subdir"> & {
|
|
125
|
+
readonly repoRoot: string; readonly gitDir: string;
|
|
126
|
+
}): Promise<boolean> {
|
|
127
|
+
try {
|
|
128
|
+
if (!withinTree(expected.subdir) || relative(expected.repoRoot, cwd) !== expected.subdir
|
|
129
|
+
|| join(expected.repoRoot, expected.subdir) !== cwd || join(expected.repoRoot, ".git") !== expected.gitDir
|
|
130
|
+
|| await realpath(cwd) !== cwd || !(await lstat(cwd)).isDirectory()) return false;
|
|
131
|
+
const git = (dir: string, args: readonly string[]) => readWorkerGit(dir, args, 750);
|
|
132
|
+
const args = [`--git-dir=${expected.gitDir}`, `--work-tree=${expected.repoRoot}`];
|
|
133
|
+
const [root, config, revision, type] = await Promise.all([
|
|
134
|
+
checkoutRoot(cwd, git),
|
|
135
|
+
git(expected.repoRoot, ["config", "--file", join(expected.gitDir, "config"), "--no-includes", "--list", "--null"]),
|
|
136
|
+
git(expected.repoRoot, [...args, "rev-parse", "--verify", "HEAD^{commit}"]),
|
|
137
|
+
expected.subdir ? git(expected.repoRoot, [...args, "cat-file", "-t", `${expected.revision}:${expected.subdir}`]) : "tree\n",
|
|
138
|
+
]);
|
|
139
|
+
if (root !== expected.repoRoot || !config?.endsWith("\0") || revision !== `${expected.revision}\n` || type !== "tree\n") return false;
|
|
140
|
+
const origins: string[] = [];
|
|
141
|
+
for (const entry of config.slice(0, -1).split("\0")) {
|
|
142
|
+
const split = entry.indexOf("\n");
|
|
143
|
+
const key = split < 0 ? entry : entry.slice(0, split);
|
|
144
|
+
if (/^(?:include(?:if)?\.|url\.|core\.worktree$|extensions\.(?:worktreeconfig|refstorage)$)/iu.test(key)) return false;
|
|
145
|
+
if (key === "remote.origin.url" && split >= 0) origins.push(entry.slice(split + 1));
|
|
146
|
+
}
|
|
147
|
+
return origins.length === 1 && repositoryOriginId(origins[0] ?? "") === expected.repoId;
|
|
148
|
+
} catch (error) {
|
|
149
|
+
if (unavailablePath(error)) return false;
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Bounded stat/read proof surrounding asynchronous Git verification and tool execution. */
|
|
155
|
+
export function workerMemoryCheckoutStamp(cwd: string, binding: { readonly repoRoot: string; readonly gitDir: string }): string | null {
|
|
156
|
+
try {
|
|
157
|
+
if (!withinTree(relative(binding.repoRoot, cwd))) return null;
|
|
158
|
+
// A subdirectory can become another checkout without changing its inode.
|
|
159
|
+
// Refuse any nested Git boundary between it and the admitted root.
|
|
160
|
+
for (let dir = cwd; dir !== binding.repoRoot; dir = dirname(dir)) {
|
|
161
|
+
if (lstatSync(join(dir, ".git"), { throwIfNoEntry: false }) || dirname(dir) === dir) return null;
|
|
162
|
+
}
|
|
163
|
+
const dirs = [binding.repoRoot, binding.gitDir, cwd].map(path => {
|
|
164
|
+
const stat = lstatSync(path, { bigint: true });
|
|
165
|
+
return stat.isDirectory() && realpathSync(path) === path ? `${stat.dev}:${stat.ino}:${stat.ctimeNs}` : null;
|
|
166
|
+
});
|
|
167
|
+
if (dirs.includes(null)) return null;
|
|
168
|
+
const stamp = (file: string) => {
|
|
169
|
+
const stat = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
170
|
+
if (!stat) return "absent";
|
|
171
|
+
if (!stat.isFile() || stat.nlink !== 1n || realpathSync(file) !== file) throw new Error("Unverifiable Git metadata");
|
|
172
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
173
|
+
};
|
|
174
|
+
const readRef = (file: string) => {
|
|
175
|
+
const first = stamp(file);
|
|
176
|
+
if (first === "absent") return { first, contents: "" };
|
|
177
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
178
|
+
try {
|
|
179
|
+
const { size } = fstatSync(fd);
|
|
180
|
+
if (size < 1 || size > 1024) throw new Error("Unverifiable Git reference");
|
|
181
|
+
const bytes = Buffer.alloc(size);
|
|
182
|
+
if (readSync(fd, bytes, 0, size, 0) !== size || stamp(file) !== first) throw new Error("Unverifiable Git reference");
|
|
183
|
+
return { first, contents: bytes.toString("utf8").replace(/\n$/u, "") };
|
|
184
|
+
} finally { closeSync(fd); }
|
|
185
|
+
};
|
|
186
|
+
const { first, contents } = readRef(join(binding.gitDir, "HEAD"));
|
|
187
|
+
const ref = contents.startsWith("ref: ") ? contents.slice(5) : undefined;
|
|
188
|
+
if (ref === undefined ? !gitOid.test(contents) : !ref.startsWith("refs/heads/") || controls.test(ref) || !withinTree(ref)) return null;
|
|
189
|
+
const branch = ref ? readRef(join(binding.gitDir, ref)) : null;
|
|
190
|
+
if (branch && branch.first !== "absent" && !gitOid.test(branch.contents)) return null;
|
|
191
|
+
const config = stamp(join(binding.gitDir, "config"));
|
|
192
|
+
if (config === "absent" || stamp(join(binding.gitDir, "config.worktree")) !== "absent") return null;
|
|
193
|
+
return JSON.stringify([dirs, first, contents, config, stamp(join(binding.gitDir, "packed-refs")), branch]);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
if (error instanceof Error) return null;
|
|
196
|
+
throw error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
115
200
|
async function matchesBlob(root: string, indexed: Buffer, committed: Buffer): Promise<boolean> {
|
|
116
201
|
const tab = indexed.indexOf(9);
|
|
117
202
|
if (tab < 0) return false;
|
|
@@ -36,6 +36,7 @@ const launch = Type.Object({
|
|
|
36
36
|
}, strict),
|
|
37
37
|
}, strict)),
|
|
38
38
|
subagentConcurrency: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
|
|
39
|
+
memorySync: Type.Optional(Type.Literal(true)),
|
|
39
40
|
}, strict);
|
|
40
41
|
const envelope = { version: Type.Literal(1) };
|
|
41
42
|
const bound = { ...envelope, workerId: id, ref: laneRefSchema };
|