zapagent 1.14.11 → 1.14.13

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 (51) hide show
  1. package/bundled-dependencies.json +201 -201
  2. package/package.json +1 -1
  3. package/src/agent-factory.ts +6 -3
  4. package/src/commands/dispatcher.ts +10 -0
  5. package/src/commands.ts +4 -0
  6. package/src/execution-environment.ts +1 -1
  7. package/src/goal-command.ts +173 -0
  8. package/src/goal-host.ts +408 -0
  9. package/src/goal-runner.ts +31 -0
  10. package/src/headless/goal-npm-install.ts +96 -0
  11. package/src/headless/goalPhase.ts +380 -0
  12. package/src/headless/runHeadless.ts +56 -4
  13. package/src/hooks/useTurnDispatcher.ts +3 -0
  14. package/src/index.tsx +17 -0
  15. package/src/ui/slash-palette.tsx +1 -0
  16. package/zapsdk/agent/loop.ts +13 -2
  17. package/zapsdk/agent/subagent-assembly.ts +5 -0
  18. package/zapsdk/agent/tool-execution-guards.ts +30 -17
  19. package/zapsdk/builtin-tools/command.ts +11 -0
  20. package/zapsdk/builtin-tools/subagent.ts +10 -3
  21. package/zapsdk/core/llm.ts +2 -0
  22. package/zapsdk/core/retry.ts +3 -0
  23. package/zapsdk/execution/broker.ts +18 -1
  24. package/zapsdk/execution/goal-workspace-gate.ts +95 -0
  25. package/zapsdk/execution/required-process-seal.ts +35 -0
  26. package/zapsdk/execution/types.ts +8 -0
  27. package/zapsdk/execution/workspace-runtime.ts +6 -0
  28. package/zapsdk/execution/zapvm.ts +117 -15
  29. package/zapsdk/goal/acceptance.ts +139 -0
  30. package/zapsdk/goal/budget.ts +406 -0
  31. package/zapsdk/goal/contracts.ts +93 -0
  32. package/zapsdk/goal/controller.ts +234 -0
  33. package/zapsdk/goal/errors.ts +17 -0
  34. package/zapsdk/goal/git-history-snapshot.ts +210 -0
  35. package/zapsdk/goal/git-operation-owner.ts +64 -0
  36. package/zapsdk/goal/metered-provider.ts +80 -0
  37. package/zapsdk/goal/npm-installer.ts +362 -0
  38. package/zapsdk/goal/scheduler.ts +34 -0
  39. package/zapsdk/goal/store.ts +173 -0
  40. package/zapsdk/goal/structured-output.ts +84 -0
  41. package/zapsdk/goal/workspace-broker.ts +11 -0
  42. package/zapsdk/goal/workspace.ts +425 -0
  43. package/zapsdk/policy/types.ts +4 -0
  44. package/zapsdk/runtime/factory.ts +7 -0
  45. package/zapsdk/scheduler/batch-scheduler.ts +2 -2
  46. package/zapsdk/tools/executor.ts +79 -6
  47. package/zapsdk/tools/types.ts +2 -0
  48. package/zapsdk/workspace/context.ts +8 -4
  49. package/zapsdk/workspace/copy.ts +14 -1
  50. package/zapsdk/workspace/manager.ts +67 -3
  51. package/zapsdk/workspace/types.ts +11 -0
@@ -0,0 +1,362 @@
1
+ import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { chmod, cp, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
+ import { copyPathOid, materializeCopyTree, removeOwnedCopyTree, scanCopyTree } from "../workspace/copy.js";
6
+ import { COPY_MERGE_JOURNAL, recoverCopyMerge, writeCopyMergeJournal, type CopyMergeJournal } from "../merge/copy-transaction.js";
7
+
8
+ /** Host preparation only. A caller must still execute the returned fixed argv
9
+ * through an authorized, offline broker that proves all descendants stopped.
10
+ * Merely running the command, or having an OS filesystem sandbox, is not that
11
+ * proof. The immutable inputs must stay fenced until the command has stopped. */
12
+ export interface PreparedNpmInstall {
13
+ readonly version: 1;
14
+ readonly workspace: string;
15
+ readonly privateRoot: string;
16
+ readonly directory: string;
17
+ readonly cleanupToken: string;
18
+ readonly cachePath: string;
19
+ /** Host-owned inputs for an eventual read-only VM mount. These are not
20
+ * sufficient by themselves to fence a workspace-backed installation. */
21
+ readonly snapshotPath: string;
22
+ readonly lockDigest: string;
23
+ readonly manifestDigest: string;
24
+ readonly tarballs: number;
25
+ readonly bytes: number;
26
+ readonly argv: readonly string[];
27
+ readonly environment: Readonly<Record<string, string>>;
28
+ }
29
+
30
+ export interface NpmInstallPreparation {
31
+ workspace: string;
32
+ /** Host-owned storage, outside the workspace and not writable by the Agent. */
33
+ privateRoot: string;
34
+ /** Host-selected, trusted absolute executables; never supplied by the model. */
35
+ nodeExecutable?: string;
36
+ npmCliScript?: string;
37
+ /** VM-only preparation does not depend on a Host Node/npm installation. */
38
+ vmOnly?: boolean;
39
+ signal?: AbortSignal;
40
+ /** Host/test transport. Implementations must perform the same GET request. */
41
+ fetch?: typeof fetch;
42
+ maxTarballBytes?: number;
43
+ maxTotalBytes?: number;
44
+ }
45
+
46
+ export interface NpmVmWorkspace {
47
+ /** A Host-owned directory, never the worker's writable workspace. */
48
+ readonly workspace: string;
49
+ /** Guest paths bind-mounted read-only by the execution backend. */
50
+ readonly protectedPaths: readonly string[];
51
+ /** Fixed guest arguments; the caller must launch via the sealed VM broker. */
52
+ readonly argv: readonly string[];
53
+ }
54
+
55
+ const DEFAULT_TARBALL_LIMIT = 64 * 1024 * 1024;
56
+ const DEFAULT_TOTAL_LIMIT = 512 * 1024 * 1024;
57
+ const MAX_LOCK_BYTES = 16 * 1024 * 1024;
58
+ const MAX_PACKAGES = 5000;
59
+
60
+ function sha256(bytes: Uint8Array): string { return createHash("sha256").update(bytes).digest("hex"); }
61
+ function inside(parent: string, child: string): boolean {
62
+ const value = relative(parent, child);
63
+ return value === "" || (!isAbsolute(value) && value !== ".." && !value.startsWith(`..${sep}`));
64
+ }
65
+ function limit(value: number | undefined, fallback: number): number {
66
+ if (value === undefined) return fallback;
67
+ if (!Number.isSafeInteger(value) || value <= 0 || value > fallback) throw new Error("Invalid npm preparation resource limit");
68
+ return value;
69
+ }
70
+
71
+ async function readRegular(path: string, maximum: number): Promise<Uint8Array> {
72
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
73
+ try {
74
+ const before = await file.stat({ bigint: true });
75
+ if (!before.isFile() || before.size > BigInt(maximum)) throw new Error("Npm input must be a bounded regular file");
76
+ const data = new Uint8Array(Number(before.size));
77
+ for (let offset = 0; offset < data.length;) {
78
+ const { bytesRead } = await file.read(data, offset, data.length - offset, offset);
79
+ if (!bytesRead) throw new Error("Npm input changed while reading");
80
+ offset += bytesRead;
81
+ }
82
+ const after = await file.stat({ bigint: true });
83
+ if (before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) throw new Error("Npm input changed while reading");
84
+ return data;
85
+ } finally { await file.close(); }
86
+ }
87
+
88
+ async function assertNoProjectNpmrc(workspace: string): Promise<void> {
89
+ try { await lstat(join(workspace, ".npmrc")); throw new Error("Project .npmrc must be removed or explicitly supported before Goal npm installation"); }
90
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
91
+ }
92
+
93
+ interface LockedTarball { url: string; hex: string }
94
+ function lockedTarballs(lockBytes: Uint8Array): LockedTarball[] {
95
+ let lock: unknown;
96
+ try { lock = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(lockBytes)); }
97
+ catch { throw new Error("Invalid npm package-lock.json"); }
98
+ if (!lock || typeof lock !== "object" || Array.isArray(lock)) throw new Error("Invalid npm package-lock.json");
99
+ const record = lock as Record<string, unknown>;
100
+ if (record.lockfileVersion !== 3 || !record.packages || typeof record.packages !== "object" || Array.isArray(record.packages)) throw new Error("Goal npm installation requires package-lock.json v3");
101
+ const entries = Object.entries(record.packages as Record<string, unknown>);
102
+ if (entries.length > MAX_PACKAGES + 1) throw new Error("Npm lockfile has too many packages");
103
+ const byHash = new Map<string, LockedTarball>();
104
+ for (const [path, value] of entries) {
105
+ if (path === "") continue;
106
+ if (!path.startsWith("node_modules/") || path.split("/").some(part => !part || part === "." || part === ".." || part === ".git") || path.includes("\\")
107
+ || !value || typeof value !== "object" || Array.isArray(value)) throw new Error("Unsupported local or linked npm dependency");
108
+ const entry = value as Record<string, unknown>;
109
+ if (entry.link || typeof entry.resolved !== "string" || typeof entry.integrity !== "string") throw new Error("Npm dependency must have a registry tarball and integrity");
110
+ let url: URL;
111
+ try { url = new URL(entry.resolved); } catch { throw new Error("Invalid npm tarball URL"); }
112
+ if (url.protocol !== "https:" || url.hostname !== "registry.npmjs.org" || url.port || url.username || url.password || url.search || url.hash
113
+ || !/^\/(?:@[^/%]+\/)?[^/%]+\/-\/[^/%]+\.tgz$/.test(url.pathname)) throw new Error("Only direct official npm registry tarball URLs are supported");
114
+ const match = /^sha512-([A-Za-z0-9+/]+={0,2})$/.exec(entry.integrity);
115
+ if (!match) throw new Error("Npm tarball requires a single SHA-512 integrity value");
116
+ const digest = Buffer.from(match[1]!, "base64");
117
+ if (digest.length !== 64 || digest.toString("base64") !== match[1]) throw new Error("Invalid npm SHA-512 integrity");
118
+ const hex = digest.toString("hex");
119
+ if (!byHash.has(hex)) byHash.set(hex, { url: url.toString(), hex });
120
+ }
121
+ return [...byHash.values()];
122
+ }
123
+
124
+ async function download(url: string, request: typeof fetch, max: number, signal?: AbortSignal): Promise<Uint8Array> {
125
+ signal?.throwIfAborted();
126
+ const response = await request(url, { method: "GET", redirect: "manual", credentials: "omit", signal });
127
+ if (!response.ok || response.status >= 300 || response.redirected) throw new Error(`Npm tarball GET failed (${response.status}); redirects are not allowed`);
128
+ const length = response.headers.get("content-length");
129
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > max)) throw new Error("Npm tarball exceeds resource limit");
130
+ if (!response.body) throw new Error("Npm tarball response has no body");
131
+ const reader = response.body.getReader();
132
+ const chunks: Uint8Array[] = [];
133
+ let bytes = 0;
134
+ try {
135
+ for (;;) {
136
+ signal?.throwIfAborted();
137
+ const { value, done } = await reader.read();
138
+ if (done) break;
139
+ bytes += value.byteLength;
140
+ if (bytes > max) throw new Error("Npm tarball exceeds resource limit");
141
+ chunks.push(value);
142
+ }
143
+ } catch (error) { await reader.cancel().catch(() => {}); throw error; }
144
+ finally { reader.releaseLock(); }
145
+ return Buffer.concat(chunks, bytes);
146
+ }
147
+
148
+ /** Only prefetches official immutable npm tarballs. No shell or package code
149
+ * is executed. Network is exclusively the host's explicit, credential-free
150
+ * GET requests; no CONNECT proxy is treated as an HTTP method boundary. */
151
+ export async function prepareNpmOfflineInstall(input: NpmInstallPreparation): Promise<PreparedNpmInstall> {
152
+ const workspace = await realpath(input.workspace);
153
+ if (!(await lstat(workspace)).isDirectory()) throw new Error("Npm workspace must be a directory");
154
+ await mkdir(input.privateRoot, { recursive: true, mode: 0o700 });
155
+ const privateStat = await lstat(input.privateRoot);
156
+ if (!privateStat.isDirectory() || privateStat.isSymbolicLink()
157
+ || (process.getuid && (privateStat.uid !== process.getuid() || (privateStat.mode & 0o077) !== 0))) throw new Error("Npm private root must be a private owned directory");
158
+ const privateRoot = await realpath(input.privateRoot);
159
+ if (inside(workspace, privateRoot) || inside(privateRoot, workspace)) throw new Error("Npm private root must be separate from its workspace");
160
+ let nodeExecutable: string | undefined, npmCliScript: string | undefined;
161
+ if (!input.vmOnly) {
162
+ if (!input.nodeExecutable || !input.npmCliScript || !isAbsolute(input.nodeExecutable) || !isAbsolute(input.npmCliScript)) throw new Error("Host npm toolchain paths must be absolute");
163
+ nodeExecutable = await realpath(input.nodeExecutable); npmCliScript = await realpath(input.npmCliScript);
164
+ if (inside(workspace, nodeExecutable) || inside(workspace, npmCliScript)
165
+ || !(await lstat(nodeExecutable)).isFile() || !(await lstat(npmCliScript)).isFile()) throw new Error("Host npm toolchain must be regular files outside the workspace");
166
+ }
167
+ await assertNoProjectNpmrc(workspace);
168
+ const manifest = await readRegular(join(workspace, "package.json"), MAX_LOCK_BYTES);
169
+ const lock = await readRegular(join(workspace, "package-lock.json"), MAX_LOCK_BYTES);
170
+ const tarballs = lockedTarballs(lock);
171
+ const tarLimit = limit(input.maxTarballBytes, DEFAULT_TARBALL_LIMIT);
172
+ const totalLimit = limit(input.maxTotalBytes, DEFAULT_TOTAL_LIMIT);
173
+ const directory = await mkdtemp(join(privateRoot, `npm-${randomUUID()}-`));
174
+ const cleanupToken = randomUUID();
175
+ const cachePath = join(directory, "cache"), snapshotPath = join(directory, "inputs"), home = join(directory, "home"), userConfig = join(directory, "user.npmrc"), globalConfig = join(directory, "global.npmrc");
176
+ try {
177
+ await mkdir(home, { mode: 0o700 });
178
+ await mkdir(snapshotPath, { mode: 0o700 });
179
+ await mkdir(cachePath, { mode: 0o700 });
180
+ await writeFile(join(snapshotPath, "package.json"), manifest, { flag: "wx", mode: 0o600 });
181
+ await writeFile(join(snapshotPath, "package-lock.json"), lock, { flag: "wx", mode: 0o600 });
182
+ await writeFile(join(directory, ".goal-npm-owner"), cleanupToken, { flag: "wx", mode: 0o600 });
183
+ await writeFile(userConfig, "", { flag: "wx", mode: 0o600 });
184
+ await writeFile(globalConfig, "", { flag: "wx", mode: 0o600 });
185
+ let total = 0;
186
+ for (const tarball of tarballs) {
187
+ const data = await download(tarball.url, input.fetch ?? fetch, Math.min(tarLimit, totalLimit - total), input.signal);
188
+ const digest = createHash("sha512").update(data).digest();
189
+ if (!timingSafeEqual(digest, Buffer.from(tarball.hex, "hex"))) throw new Error("Npm tarball integrity mismatch");
190
+ total += data.byteLength;
191
+ const path = join(cachePath, "_cacache", "content-v2", "sha512", tarball.hex.slice(0, 2), tarball.hex.slice(2, 4), tarball.hex.slice(4));
192
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
193
+ await writeFile(path, data, { flag: "wx", mode: 0o600 });
194
+ }
195
+ await assertNoProjectNpmrc(workspace);
196
+ if (sha256(await readRegular(join(workspace, "package.json"), MAX_LOCK_BYTES)) !== sha256(manifest)
197
+ || sha256(await readRegular(join(workspace, "package-lock.json"), MAX_LOCK_BYTES)) !== sha256(lock)) throw new Error("Npm manifests changed during preparation");
198
+ return { version: 1, workspace, privateRoot, directory, cleanupToken, cachePath, snapshotPath, lockDigest: sha256(lock), manifestDigest: sha256(manifest), tarballs: tarballs.length, bytes: total,
199
+ argv: nodeExecutable && npmCliScript ? [nodeExecutable, npmCliScript, "ci", "--offline", "--ignore-scripts", "--no-audit", "--no-fund", "--no-progress", "--cache", cachePath, "--userconfig", userConfig, "--globalconfig", globalConfig] : [],
200
+ // Host must replace the process environment with this exact allowlist,
201
+ // not merge it with its own credentials, NODE_OPTIONS or npm_config_*.
202
+ environment: { HOME: home, PATH: "", npm_config_userconfig: userConfig, npm_config_globalconfig: globalConfig } };
203
+ } catch (error) { await rm(directory, { recursive: true, force: true }); throw error; }
204
+ }
205
+
206
+ /** Host must call immediately before execution, with the workspace fenced. */
207
+ export async function revalidateNpmOfflineInstall(prepared: PreparedNpmInstall): Promise<void> {
208
+ if (prepared.version !== 1 || prepared.snapshotPath !== join(prepared.directory, "inputs") || await realpath(prepared.workspace) !== prepared.workspace) throw new Error("Npm workspace identity changed");
209
+ await assertNoProjectNpmrc(prepared.workspace);
210
+ const manifest = await readRegular(join(prepared.workspace, "package.json"), MAX_LOCK_BYTES);
211
+ const lock = await readRegular(join(prepared.workspace, "package-lock.json"), MAX_LOCK_BYTES);
212
+ if (sha256(manifest) !== prepared.manifestDigest || sha256(lock) !== prepared.lockDigest) throw new Error("Npm manifests changed before installation");
213
+ const snapshotManifest = await readRegular(join(prepared.snapshotPath, "package.json"), MAX_LOCK_BYTES);
214
+ const snapshotLock = await readRegular(join(prepared.snapshotPath, "package-lock.json"), MAX_LOCK_BYTES);
215
+ if (sha256(snapshotManifest) !== prepared.manifestDigest || sha256(snapshotLock) !== prepared.lockDigest) throw new Error("Npm private inputs changed before installation");
216
+ }
217
+
218
+ /** Verify that a model has not changed the inputs of an already installed
219
+ * dependency tree. The caller must ensure no model writer is still running. */
220
+ export async function assertNpmInputsUnchanged(workspace: string, proof: { manifestDigest: string; lockDigest: string }): Promise<void> {
221
+ await assertNoProjectNpmrc(workspace);
222
+ const manifest = await readRegular(join(workspace, "package.json"), MAX_LOCK_BYTES);
223
+ const lock = await readRegular(join(workspace, "package-lock.json"), MAX_LOCK_BYTES);
224
+ if (sha256(manifest) !== proof.manifestDigest || sha256(lock) !== proof.lockDigest) throw new Error("GOAL_NPM_INPUTS_MODIFIED");
225
+ }
226
+
227
+ /** Prepare a separate VM workspace for the downloaded inputs. The caller must
228
+ * mount protectedPaths read-only, disable network, and verify the VM's seal
229
+ * receipt before reading output. This function does not install or import
230
+ * node_modules and does not establish a workspace lock. */
231
+ export async function createNpmVmWorkspace(prepared: PreparedNpmInstall): Promise<NpmVmWorkspace> {
232
+ await revalidateNpmOfflineInstall(prepared);
233
+ const workspace = join(prepared.directory, "vm-workspace");
234
+ await mkdir(workspace, { mode: 0o700 });
235
+ try {
236
+ const manifest = await readRegular(join(prepared.snapshotPath, "package.json"), MAX_LOCK_BYTES);
237
+ const lock = await readRegular(join(prepared.snapshotPath, "package-lock.json"), MAX_LOCK_BYTES);
238
+ if (sha256(manifest) !== prepared.manifestDigest || sha256(lock) !== prepared.lockDigest) throw new Error("Npm private inputs changed during staging");
239
+ await writeFile(join(workspace, "package.json"), manifest, { flag: "wx", mode: 0o444 });
240
+ await writeFile(join(workspace, "package-lock.json"), lock, { flag: "wx", mode: 0o444 });
241
+ const controls = join(workspace, ".zapcode");
242
+ await mkdir(controls, { mode: 0o755 });
243
+ await cp(prepared.cachePath, join(controls, "cache"), { recursive: true, errorOnExist: true, force: false });
244
+ await verifyStagedCache(join(controls, "cache"), lock);
245
+ await makeReadableCache(join(controls, "cache"));
246
+ await writeFile(join(controls, "user.npmrc"), "", { flag: "wx", mode: 0o444 });
247
+ await writeFile(join(controls, "global.npmrc"), "", { flag: "wx", mode: 0o444 });
248
+ return { workspace, protectedPaths: [".zapcode", "package.json", "package-lock.json"],
249
+ argv: ["/usr/bin/env", "-i", "HOME=/tmp", "PATH=/usr/bin:/bin", "/usr/bin/npm", "ci", "--offline", "--ignore-scripts", "--no-audit", "--no-fund", "--no-progress", "--logs-max=0", "--cache", "/workspace/.zapcode/cache", "--userconfig", "/workspace/.zapcode/user.npmrc", "--globalconfig", "/workspace/.zapcode/global.npmrc"] };
250
+ } catch (error) {
251
+ await rm(workspace, { recursive: true, force: true });
252
+ throw error;
253
+ }
254
+ }
255
+
256
+ /** Host-only integration contract. The lock must exclude every Goal operation
257
+ * that can read or write this workspace, including child agents, until the
258
+ * callback settles, with exclusive ownership of the source and both parent
259
+ * directories. publishNoReplace must be the OS atomic no-replace rename
260
+ * primitive, without a copy fallback. It does not prove source path identity.
261
+ * Neither capability is model-controlled. */
262
+ export interface NpmImportCapabilities {
263
+ withExclusiveWorkspace<T>(workspace: string, action: () => Promise<T>): Promise<T>;
264
+ publishNoReplace(source: string, destination: string): Promise<void>;
265
+ }
266
+
267
+ /** Import only after the caller has authenticated the strict VM receipt for
268
+ * this exact execution. A private journal remains after a process interruption;
269
+ * parent directories are not fsynced, so power-loss recovery is not promised.
270
+ * Recovery must itself run under the same lock. */
271
+ export async function importNpmVmWorkspace(prepared: PreparedNpmInstall, stage: NpmVmWorkspace,
272
+ receipt: { state: "sealed"; executionId: string } | undefined, expectedExecutionId: string,
273
+ capabilities: NpmImportCapabilities): Promise<void> {
274
+ if (!receipt || receipt.state !== "sealed" || !expectedExecutionId || receipt.executionId !== expectedExecutionId) throw new Error("Npm VM process seal is unconfirmed");
275
+ if (stage.workspace !== join(prepared.directory, "vm-workspace") || await realpath(stage.workspace) !== stage.workspace) throw new Error("Invalid npm VM workspace");
276
+ await capabilities.withExclusiveWorkspace(prepared.workspace, async () => {
277
+ await revalidateNpmOfflineInstall(prepared);
278
+ const target = join(prepared.workspace, "node_modules");
279
+ try { await lstat(target); throw new Error("node_modules already exists; refusing to replace it"); }
280
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
281
+ // An interrupted prior import is never silently reused or removed.
282
+ try { await lstat(join(prepared.directory, COPY_MERGE_JOURNAL)); throw new Error("Npm import requires explicit recovery"); }
283
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
284
+ const modules = join(stage.workspace, "node_modules");
285
+ const tree = await scanCopyTree(modules);
286
+ const transaction = join(prepared.workspace, `.zap-copy-merge-${randomUUID()}`);
287
+ await mkdir(transaction, { mode: 0o700 });
288
+ let journaled = false;
289
+ try {
290
+ const staged = join(transaction, "new-0");
291
+ await materializeCopyTree(modules, staged, tree);
292
+ const after = await copyPathOid(staged);
293
+ if (!after) throw new Error("Npm staged output disappeared");
294
+ const journal: CopyMergeJournal = { version: 1, root: prepared.workspace, transaction,
295
+ artifactIds: [`npm:${expectedExecutionId}`], operations: [{ path: "node_modules", modeOnly: false, before: null, after }], state: "applying" };
296
+ await writeCopyMergeJournal(prepared.directory, journal);
297
+ journaled = true;
298
+ await revalidateNpmOfflineInstall(prepared);
299
+ await capabilities.publishNoReplace(staged, target);
300
+ journal.state = "committed";
301
+ await writeCopyMergeJournal(prepared.directory, journal);
302
+ await removeOwnedCopyTree(transaction);
303
+ await rm(join(prepared.directory, COPY_MERGE_JOURNAL));
304
+ } catch (error) {
305
+ if (!journaled) await removeOwnedCopyTree(transaction);
306
+ // Once intent is durable, even an error from the publish callback may
307
+ // follow a completed rename; retain the journal for explicit recovery.
308
+ throw error;
309
+ }
310
+ });
311
+ }
312
+
313
+ export async function recoverNpmVmImport(prepared: PreparedNpmInstall, capabilities: NpmImportCapabilities): Promise<void> {
314
+ await capabilities.withExclusiveWorkspace(prepared.workspace, async () => { await recoverCopyMerge(prepared.workspace, prepared.directory); });
315
+ }
316
+
317
+ async function verifyStagedCache(cache: string, lock: Uint8Array): Promise<void> {
318
+ const expected = new Map(lockedTarballs(lock).map(({ hex }) => [join("_cacache", "content-v2", "sha512", hex.slice(0, 2), hex.slice(2, 4), hex.slice(4)), hex]));
319
+ let files = 0;
320
+ const visit = async (path: string, rel: string): Promise<void> => {
321
+ const info = await lstat(path);
322
+ if (info.isSymbolicLink()) throw new Error("Npm cache must not contain symlinks");
323
+ if (info.isDirectory()) {
324
+ for (const entry of await readdir(path)) await visit(join(path, entry), join(rel, entry));
325
+ return;
326
+ }
327
+ if (!info.isFile()) throw new Error("Npm cache must contain only regular files");
328
+ const hex = expected.get(rel);
329
+ if (!hex) throw new Error("Npm cache contains an unexpected file");
330
+ const bytes = await readRegular(path, DEFAULT_TARBALL_LIMIT);
331
+ if (createHash("sha512").update(bytes).digest("hex") !== hex) throw new Error("Npm staged cache integrity mismatch");
332
+ files += 1;
333
+ };
334
+ await visit(cache, "");
335
+ if (files !== expected.size) throw new Error("Npm staged cache is incomplete");
336
+ }
337
+
338
+ async function makeReadableCache(path: string): Promise<void> {
339
+ const info = await lstat(path);
340
+ if (info.isSymbolicLink()) throw new Error("Npm cache must not contain symlinks");
341
+ if (info.isDirectory()) {
342
+ await chmod(path, 0o755);
343
+ for (const entry of await readdir(path)) await makeReadableCache(join(path, entry));
344
+ return;
345
+ }
346
+ if (!info.isFile()) throw new Error("Npm cache must contain only regular files");
347
+ await chmod(path, 0o444);
348
+ }
349
+
350
+ /** The Host must establish process termination before removing the cache. */
351
+ export async function cleanupNpmOfflineInstall(prepared: PreparedNpmInstall, trustedPrivateRoot: string): Promise<void> {
352
+ const root = await realpath(trustedPrivateRoot);
353
+ const info = await lstat(prepared.directory);
354
+ if (root !== prepared.privateRoot || dirname(prepared.directory) !== root || !info.isDirectory() || info.isSymbolicLink()
355
+ || !/^npm-[0-9a-f-]{36}-[A-Za-z0-9]{6}$/.test(prepared.directory.slice(root.length + 1))
356
+ || Buffer.from(await readRegular(join(prepared.directory, ".goal-npm-owner"), 128)).toString("utf8") !== prepared.cleanupToken) {
357
+ throw new Error("Invalid Host-owned npm preparation");
358
+ }
359
+ try { await lstat(join(prepared.directory, COPY_MERGE_JOURNAL)); throw new Error("Npm import requires explicit recovery before cleanup"); }
360
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
361
+ await rm(prepared.directory, { recursive: true, force: true });
362
+ }
@@ -0,0 +1,34 @@
1
+ import type { GoalRecord, GoalTask } from "./contracts.js";
2
+
3
+ export type GoalAction = { kind: "plan" | "snapshot" | "verify_final" | "deliver" }
4
+ | { kind: "execute" | "verify" | "integrate"; task: GoalTask }
5
+ | { kind: "stop"; status: "awaiting_acceptance" | "blocked" | "paused"; reason: string };
6
+
7
+ /** Pure scheduling policy. The controller alone owns effects and receipts. */
8
+ export function nextGoalAction(goal: Readonly<GoalRecord>): GoalAction {
9
+ if (!goal.planRevision) return { kind: "plan" };
10
+ if (goal.permissionMode === "plan") return { kind: "stop", status: "paused", reason: "GOAL_PLAN_REQUIRES_EXECUTION_AUTHORIZATION" };
11
+ const task = goal.tasks.find(t => t.status !== "passed" && t.dependencies.every(id => goal.tasks.some(dep => dep.id === id && dep.status === "passed")));
12
+ if (task) {
13
+ if (task.status === "blocked") return { kind: "stop", status: "awaiting_acceptance", reason: task.receipt?.detail ?? "TASK_REQUIRES_ACCEPTANCE" };
14
+ if (task.status === "pending" || task.status === "repairing") return { kind: "execute", task };
15
+ if (task.status !== "verifying") return { kind: "stop", status: "blocked", reason: "GOAL_TASK_RECOVERY_REQUIRED" };
16
+ if (task.receipt && task.receipt.status !== "passed") return { kind: "stop", status: "awaiting_acceptance", reason: task.receipt.detail ?? "TASK_REQUIRES_ACCEPTANCE" };
17
+ return { kind: task.receipt ? "integrate" : "verify", task };
18
+ }
19
+ if (goal.tasks.some(t => t.status !== "passed")) return { kind: "stop", status: "blocked", reason: "GOAL_DEPENDENCY_BLOCKED" };
20
+ if (!goal.finalCandidate) return { kind: "snapshot" };
21
+ if (!goal.finalReceipt) return { kind: "verify_final" };
22
+ if (goal.finalReceipt.status !== "passed") return { kind: "stop", status: "awaiting_acceptance", reason: goal.finalReceipt.detail ?? "FINAL_ACCEPTANCE_NOT_PASSED" };
23
+ return { kind: "deliver" };
24
+ }
25
+
26
+ /** Each completed phase emits the next scheduling opportunity. Yielding to
27
+ * the event loop lets queued user control win before starting new work. */
28
+ export async function driveGoalSchedule(step: () => Promise<GoalRecord>): Promise<GoalRecord> {
29
+ for (;;) {
30
+ await new Promise<void>(resolve => setImmediate(resolve));
31
+ const goal = await step();
32
+ if (goal.status !== "running") return goal;
33
+ }
34
+ }
@@ -0,0 +1,173 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, mkdirSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import type { GoalRecord, GoalStatus } from "./contracts.js";
6
+
7
+ /** Durable Host-owned records. BEGIN IMMEDIATE serializes cross-process claims and CAS. */
8
+ export class GoalStore {
9
+ private readonly db: Database;
10
+ constructor(path: string, private readonly options: { requireLedger?: boolean } = {}) {
11
+ if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
12
+ this.db = new Database(path, { create: true, strict: true });
13
+ if (path !== ":memory:") chmodSync(path, 0o600);
14
+ this.db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL");
15
+ this.db.exec("CREATE TABLE IF NOT EXISTS goals (id TEXT PRIMARY KEY, revision INTEGER NOT NULL, record TEXT NOT NULL)");
16
+ this.db.exec("CREATE TABLE IF NOT EXISTS goal_budget_extensions (id TEXT PRIMARY KEY, goal_id TEXT NOT NULL, at INTEGER NOT NULL, old_limits TEXT NOT NULL, new_limits TEXT NOT NULL)");
17
+ }
18
+ close(): void { this.db.close(); }
19
+ create(input: { objective: string; cwd: string; sessionId?: string; deadlineAt?: number; deliveryPolicy?: "artifact" | "workspace"; machineCheck?: "bun" | "npm" | "pytest" | "go"; dependencyInstall?: "npm"; permissionMode?: "default" | "acceptEdits" | "plan" | "bypassPermissions" }): GoalRecord {
20
+ if (!input.objective.trim() || !input.cwd || (input.deadlineAt !== undefined && (!Number.isSafeInteger(input.deadlineAt) || input.deadlineAt <= Date.now())) || (input.dependencyInstall !== undefined && input.dependencyInstall !== "npm")) throw new Error("INVALID_GOAL");
21
+ const now = Date.now();
22
+ const value: GoalRecord = { id: `goal_${randomUUID()}`, objective: input.objective, deliveryPolicy: input.deliveryPolicy ?? "workspace", permissionMode: input.permissionMode ?? "default", ...(input.machineCheck ? { machineCheck: input.machineCheck } : {}), ...(input.dependencyInstall ? { dependencyInstall: input.dependencyInstall } : {}), cwd: input.cwd, ...(input.sessionId ? { sessionId: input.sessionId } : {}), stateRevision: 1, specRevision: 1, planRevision: 0, status: "created", createdAt: now, updatedAt: now, ...(input.deadlineAt === undefined ? {} : { deadlineAt: input.deadlineAt }), ownerEpoch: 0, tasks: [] };
23
+ this.db.query("INSERT INTO goals(id,revision,record) VALUES(?,?,?)").run(value.id, value.stateRevision, JSON.stringify(value));
24
+ return value;
25
+ }
26
+ get(id: string): GoalRecord | undefined {
27
+ const row = this.db.query<{revision: number; record: string}, [string]>("SELECT revision,record FROM goals WHERE id=?").get(id);
28
+ if (!row) return undefined;
29
+ const state = JSON.parse(row.record) as GoalRecord;
30
+ if (state.id !== id || state.stateRevision !== row.revision) throw new Error("CORRUPT_GOAL_STATE");
31
+ return state;
32
+ }
33
+ list(cwd?: string): GoalRecord[] {
34
+ const rows = this.db.query<{record: string}, []>("SELECT record FROM goals ORDER BY rowid DESC").all();
35
+ return rows.map(row => JSON.parse(row.record) as GoalRecord).filter(goal => !cwd || goal.cwd === cwd);
36
+ }
37
+ private transaction<T>(fn: () => T): T {
38
+ this.db.exec("BEGIN IMMEDIATE");
39
+ try { const result = fn(); this.db.exec("COMMIT"); return result; }
40
+ catch (error) { this.db.exec("ROLLBACK"); throw error; }
41
+ }
42
+ private save(previous: GoalRecord, next: GoalRecord): GoalRecord {
43
+ next.stateRevision = previous.stateRevision + 1;
44
+ next.updatedAt = Date.now();
45
+ const result = this.db.query("UPDATE goals SET revision=?,record=? WHERE id=? AND revision=?").run(next.stateRevision, JSON.stringify(next), next.id, previous.stateRevision) as { changes: number };
46
+ const changed = result.changes;
47
+ if (changed !== 1) throw new Error("GOAL_REVISION_CONFLICT");
48
+ return structuredClone(next);
49
+ }
50
+ claim(id: string, instanceId: string, pid: number, forRecovery = false, automatic = false): GoalRecord {
51
+ return this.transaction(() => {
52
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
53
+ if (goal.owner) throw new Error("GOAL_OWNER_ACTIVE_OR_UNRESOLVED");
54
+ if (automatic && (goal.control || !(goal.status === "created" || goal.status === "paused" && goal.stopReason === "RECONCILED_SAFE_TO_RESUME"))) throw new Error("GOAL_AUTOMATIC_CONTINUATION_SUPPRESSED");
55
+ if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error("GOAL_TERMINAL");
56
+ if (goal.inFlight && !forRecovery) throw new Error("GOAL_RECOVERY_REQUIRED");
57
+ if (forRecovery && !goal.inFlight) throw new Error("GOAL_NO_RECOVERY_REQUIRED");
58
+ const next = structuredClone(goal); next.ownerEpoch++; next.owner = { instanceId, pid }; next.status = "running"; next.stopReason = undefined; next.failure = undefined; next.control = undefined;
59
+ // The Goal and its ledger reside in the same Host database. Advancing
60
+ // both epochs under this transaction prevents a crash or SQLite error
61
+ // from stranding a Goal at a revision its meter will never accept.
62
+ const table = this.db.query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table' AND name='goal_budget_accounts'").get();
63
+ if (table) {
64
+ const changed = this.db.query("UPDATE goal_budget_accounts SET epoch=? WHERE goal_id=? AND epoch=?")
65
+ .run(next.ownerEpoch, id, goal.ownerEpoch) as { changes: number };
66
+ if (changed.changes !== 1) throw new Error("GOAL_BUDGET_EPOCH_CONFLICT");
67
+ } else if (this.options.requireLedger) throw new Error("GOAL_BUDGET_ACCOUNT_MISSING");
68
+ return this.save(goal, next);
69
+ });
70
+ }
71
+ update(id: string, epoch: number, instanceId: string, fn: (value: GoalRecord) => void): GoalRecord {
72
+ return this.transaction(() => {
73
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
74
+ if (goal.ownerEpoch !== epoch || goal.owner?.instanceId !== instanceId) throw new Error("GOAL_STALE_OWNER");
75
+ const next = structuredClone(goal); fn(next);
76
+ if (next.id !== goal.id || next.ownerEpoch !== goal.ownerEpoch || next.owner?.instanceId !== goal.owner.instanceId || next.specRevision !== goal.specRevision || next.objective !== goal.objective || next.deliveryPolicy !== goal.deliveryPolicy || next.machineCheck !== goal.machineCheck || next.dependencyInstall !== goal.dependencyInstall || next.permissionMode !== goal.permissionMode || next.cwd !== goal.cwd || next.sessionId !== goal.sessionId || next.deadlineAt !== goal.deadlineAt) throw new Error("GOAL_IMMUTABLE_FIELD");
77
+ return this.save(goal, next);
78
+ });
79
+ }
80
+ release(id: string, epoch: number, instanceId: string, status: GoalStatus, reason?: string): GoalRecord {
81
+ return this.transaction(() => {
82
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
83
+ if (goal.ownerEpoch !== epoch || goal.owner?.instanceId !== instanceId) throw new Error("GOAL_STALE_OWNER");
84
+ const next = structuredClone(goal); next.owner = undefined; next.status = status; next.stopReason = reason;
85
+ return this.save(goal, next);
86
+ });
87
+ }
88
+ /** A user-requested extension updates Goal and ledger in the same SQLite transaction. */
89
+ extendBudget(id: string, delta: { tokens?: number; modelCalls?: number; providerAttempts?: number; toolCalls?: number; minutes?: number }): GoalRecord {
90
+ if (!Object.values(delta).some(value => value !== undefined) || Object.values(delta).some(value => value !== undefined && (!Number.isSafeInteger(value) || value <= 0))) throw new Error("INVALID_GOAL_BUDGET_EXTENSION");
91
+ return this.transaction(() => {
92
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
93
+ if (goal.owner) throw new Error("GOAL_OWNER_ACTIVE_OR_UNRESOLVED");
94
+ if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error("GOAL_TERMINAL");
95
+ const account = this.db.query<{epoch: number; limits_json: string}, [string]>("SELECT epoch, limits_json FROM goal_budget_accounts WHERE goal_id=?").get(id);
96
+ if (!account || account.epoch !== goal.ownerEpoch) throw new Error("GOAL_BUDGET_EPOCH_CONFLICT");
97
+ const limits = JSON.parse(account.limits_json) as Record<string, unknown>; const nextLimits = structuredClone(limits);
98
+ const add = (key: string, amount: number | undefined) => {
99
+ if (amount === undefined) return;
100
+ const prior = nextLimits[key];
101
+ if (typeof prior !== "number" || !Number.isSafeInteger(prior) || !Number.isSafeInteger(prior + amount)) throw new Error("GOAL_BUDGET_LIMIT_UNAVAILABLE");
102
+ nextLimits[key] = prior + amount;
103
+ };
104
+ add("maxTokens", delta.tokens); add("maxModelCalls", delta.modelCalls); add("maxProviderAttempts", delta.providerAttempts); add("maxToolCalls", delta.toolCalls);
105
+ if (delta.minutes !== undefined) add("deadlineAt", delta.minutes * 60_000);
106
+ const next = structuredClone(goal);
107
+ if (delta.minutes !== undefined) {
108
+ if (typeof nextLimits.deadlineAt !== "number") throw new Error("GOAL_BUDGET_LIMIT_UNAVAILABLE");
109
+ next.deadlineAt = nextLimits.deadlineAt;
110
+ }
111
+ this.db.query("UPDATE goal_budget_accounts SET limits_json=? WHERE goal_id=? AND epoch=?").run(JSON.stringify(nextLimits), id, account.epoch);
112
+ this.db.query("INSERT INTO goal_budget_extensions(id,goal_id,at,old_limits,new_limits) VALUES(?,?,?,?,?)")
113
+ .run(randomUUID(), id, Date.now(), account.limits_json, JSON.stringify(nextLimits));
114
+ return this.save(goal, next);
115
+ });
116
+ }
117
+ /** Foreground input may interrupt only Goals created by this chat. */
118
+ pauseForInput(cwd: string, sessionId: string): string[] {
119
+ return this.transaction(() => {
120
+ const ids: string[] = [];
121
+ for (const goal of this.list(cwd)) {
122
+ if (goal.sessionId !== sessionId || goal.control || !["created", "running"].includes(goal.status)) continue;
123
+ const next = structuredClone(goal); next.yieldRequested = true;
124
+ if (!next.owner && !next.inFlight) { next.status = "paused"; next.yieldRequested = undefined; next.stopReason = "USER_INPUT_PENDING"; }
125
+ this.save(goal, next); ids.push(goal.id);
126
+ }
127
+ return ids;
128
+ });
129
+ }
130
+ /** Explicit user resumption retries only indeterminate verification against
131
+ * the retained candidate; failed worker evidence stays available for repair. */
132
+ prepareResume(id: string): GoalRecord {
133
+ return this.transaction(() => {
134
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
135
+ if (goal.owner) throw new Error("GOAL_OWNER_ACTIVE_OR_UNRESOLVED");
136
+ if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error("GOAL_TERMINAL");
137
+ const next = structuredClone(goal);
138
+ // Never erase unresolved effects or their evidence at this boundary.
139
+ if (!next.inFlight) {
140
+ for (const task of next.tasks) if (task.status === "blocked" && ["error", "unverified"].includes(task.receipt?.status ?? "")) {
141
+ task.status = "verifying"; task.receipt = undefined;
142
+ }
143
+ if (next.finalReceipt && next.finalReceipt.status !== "passed") {
144
+ next.finalReceipt = undefined;
145
+ }
146
+ next.progress = undefined;
147
+ }
148
+ next.status = "created"; next.stopReason = undefined; next.yieldRequested = undefined;
149
+ return this.save(goal, next);
150
+ });
151
+ }
152
+ /** User control requests are persisted separately from owner transitions. */
153
+ requestControl(id: string, control: "pause" | "cancel"): GoalRecord {
154
+ return this.transaction(() => {
155
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
156
+ if (["completed", "cancelled", "failed"].includes(goal.status)) throw new Error("GOAL_TERMINAL");
157
+ const next = structuredClone(goal); next.control = control;
158
+ if (!next.owner && !next.inFlight) { next.status = control === "pause" ? "paused" : "cancelled"; next.control = undefined; }
159
+ return this.save(goal, next);
160
+ });
161
+ }
162
+ /** Caller must independently establish prior writer and its children are stopped. */
163
+ recoverOwner(id: string, expectedInstanceId: string, stopped: boolean): GoalRecord {
164
+ if (!stopped) throw new Error("GOAL_OWNER_STOP_UNCONFIRMED");
165
+ return this.transaction(() => {
166
+ const goal = this.get(id); if (!goal) throw new Error("GOAL_NOT_FOUND");
167
+ if (goal.owner?.instanceId !== expectedInstanceId) throw new Error("GOAL_OWNER_CHANGED");
168
+ const next = structuredClone(goal); next.owner = undefined; next.status = "blocked";
169
+ next.stopReason = next.inFlight ? "INTERRUPTED_OPERATION_REQUIRES_RECONCILIATION" : "INTERRUPTED_OWNER";
170
+ return this.save(goal, next);
171
+ });
172
+ }
173
+ }