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
@@ -135,6 +135,8 @@ export function isToolAuthorization(
135
135
  }
136
136
 
137
137
  export interface ToolExecutorOptions {
138
+ /** Host-owned workspace execution fence, shared across every participant. */
139
+ workspaceGate?: WorkspaceExecutionGate;
138
140
  /** Fallback for tools without a declared timeout. To impose a hard host
139
141
  * ceiling, supply an executionBroker with explicit timeout limits. */
140
142
  timeoutMs?: number;
@@ -157,7 +159,7 @@ export interface ToolExecutorOptions {
157
159
  onExecutionLifecycle?: ToolExecutionLifecycleHandler;
158
160
  /** Synchronous host admission after authorization, before lifecycle/handler.
159
161
  * Throwing can only prevent execution; it never grants permission. */
160
- admitExecution?: () => void;
162
+ admitExecution?: (toolName: string) => void;
161
163
  /**
162
164
  * Compatibility escape hatch for trusted embedders that intentionally run
163
165
  * confirm tools without an approval callback. Defaults to false so bare SDK
@@ -178,6 +180,14 @@ export interface ToolExecutorOptions {
178
180
  onTrackEdit?: CheckpointEditTracker;
179
181
  }
180
182
 
183
+ export interface WorkspaceExecutionGate {
184
+ authorize<T>(workspace: string, action: () => T | Promise<T>, signal?: AbortSignal): Promise<T>;
185
+ execute(workspace: string, authorization: ToolAuthorization, action: () => Promise<ToolResult>, signal?: AbortSignal): Promise<ToolResult>;
186
+ /** Mark the current Host-owned execution uncertain before presentation code
187
+ * can replace its result. This does not depend on tool/model metadata. */
188
+ markUnconfirmed(): void;
189
+ }
190
+
181
191
  type WriteFingerprint = NonNullable<NonNullable<ToolResult["runtime"]>["writeEvidence"]>["paths"][number]["before"];
182
192
 
183
193
  const WRITE_EVIDENCE_HASH_LIMIT_BYTES = 1024 * 1024;
@@ -213,7 +223,7 @@ export class ToolExecutor {
213
223
  private _onApproval?: ApprovalCallback;
214
224
  private _onApprovalLifecycle?: ApprovalLifecycleHandler;
215
225
  private _onExecutionLifecycle?: ToolExecutionLifecycleHandler;
216
- private _admitExecution?: () => void;
226
+ private _admitExecution?: (toolName: string) => void;
217
227
  private _allowConfirmWithoutApproval: boolean;
218
228
  private _postProcess?: PostProcessCallback;
219
229
  private readonly _resultGuard?: ToolResultGuard;
@@ -224,6 +234,7 @@ export class ToolExecutor {
224
234
  private _actor?: AgentIdentity;
225
235
  private _workspace: WorkspaceIdentity;
226
236
  private _executionBroker: ExecutionBroker;
237
+ private _workspaceGate?: WorkspaceExecutionGate;
227
238
  private _interactive: boolean;
228
239
  /** Serializes concurrent approval requests so UI only shows one at a time. */
229
240
  private approvalQueue: ApprovalCoordinator;
@@ -240,6 +251,7 @@ export class ToolExecutor {
240
251
  this._policyEngine = options.policyEngine ?? new DefaultToolPolicyEngine();
241
252
  this._actor = options.actor;
242
253
  this._executionBroker = options.executionBroker ?? new DefaultExecutionBroker();
254
+ this._workspaceGate = options.workspaceGate;
243
255
  const sandboxStatus = this._executionBroker.sandboxStatus();
244
256
  this._workspace = {
245
257
  root: options.workspace?.root ?? this._cwd,
@@ -247,6 +259,10 @@ export class ToolExecutor {
247
259
  mode: options.workspace?.mode ?? "root",
248
260
  ...(options.workspace?.privateGitDirectory
249
261
  ? { privateGitDirectory: options.workspace.privateGitDirectory } : {}),
262
+ ...(options.workspace?.privateGitIdentity
263
+ ? { privateGitIdentity: { ...options.workspace.privateGitIdentity } } : {}),
264
+ ...(options.workspace?.protectedWorkspacePaths
265
+ ? { protectedWorkspacePaths: [...options.workspace.protectedWorkspacePaths] } : {}),
250
266
  sandbox: options.workspace?.sandbox
251
267
  ?? (sandboxStatus.available ? "enforced" : "none"),
252
268
  };
@@ -280,6 +296,13 @@ export class ToolExecutor {
280
296
  get approvalCoordinator(): ApprovalCoordinator { return this.approvalQueue; }
281
297
  get policyEngine(): ToolPolicyEngine { return this._policyEngine; }
282
298
  get executionBroker(): ExecutionBroker { return this._executionBroker; }
299
+ get executionAdmission(): ToolExecutorOptions["admitExecution"] { return this._admitExecution; }
300
+ get workspaceGate(): WorkspaceExecutionGate | undefined { return this._workspaceGate; }
301
+ get workspace(): Readonly<WorkspaceIdentity> { return { ...this._workspace,
302
+ ...(this._workspace.protectedWorkspacePaths ? { protectedWorkspacePaths: [...this._workspace.protectedWorkspacePaths] } : {}) }; }
303
+
304
+ /** Bind a Host-owned workspace boundary without changing grants or policy. */
305
+ withWorkspace(workspace: WorkspaceIdentity): ToolExecutor { return this.clone(this.registry, { workspace }); }
283
306
 
284
307
  /** Clone while retaining lifecycle hooks, broker and the shared approval queue. */
285
308
  withRuntimePolicy(policyEngine: ToolPolicyEngine, checkpointMode: ToolExecutorOptions["checkpointMode"], requireApproval = false): ToolExecutor {
@@ -291,6 +314,7 @@ export class ToolExecutor {
291
314
  timeoutMs: this._timeoutMs, checkpointMode: this._checkpointMode,
292
315
  cwd: this._cwd, policyEngine: this._policyEngine, actor: this._actor,
293
316
  workspace: this._workspace, executionBroker: this._executionBroker,
317
+ workspaceGate: this._workspaceGate,
294
318
  interactive: this._interactive, onApproval: this._onApproval,
295
319
  onApprovalLifecycle: this._onApprovalLifecycle, onExecutionLifecycle: this._onExecutionLifecycle,
296
320
  admitExecution: this._admitExecution,
@@ -303,9 +327,9 @@ export class ToolExecutor {
303
327
  withRegistry(registry: ToolRegistry): ToolExecutor { return this.clone(registry); }
304
328
 
305
329
  /** Compose restrictive, synchronous admission without creating a started receipt. */
306
- withExecutionAdmission(admit: () => void): ToolExecutor {
330
+ withExecutionAdmission(admit: (toolName: string) => void): ToolExecutor {
307
331
  const existing = this._admitExecution;
308
- return this.clone(this.registry, { admitExecution: () => { existing?.(); admit(); } });
332
+ return this.clone(this.registry, { admitExecution: name => { existing?.(name); admit(name); } });
309
333
  }
310
334
 
311
335
  /** Clone this executor while composing a runtime lifecycle observer. */
@@ -319,6 +343,7 @@ export class ToolExecutor {
319
343
  actor: this._actor,
320
344
  workspace: this._workspace,
321
345
  executionBroker: this._executionBroker,
346
+ workspaceGate: this._workspaceGate,
322
347
  interactive: this._interactive,
323
348
  onApproval: this._onApproval,
324
349
  onApprovalLifecycle: async (event) => {
@@ -344,6 +369,7 @@ export class ToolExecutor {
344
369
  actor: this._actor,
345
370
  workspace: this._workspace,
346
371
  executionBroker: this._executionBroker,
372
+ workspaceGate: this._workspaceGate,
347
373
  interactive: this._interactive,
348
374
  onApproval: this._onApproval,
349
375
  onApprovalLifecycle: this._onApprovalLifecycle,
@@ -381,6 +407,13 @@ export class ToolExecutor {
381
407
  !["isolated-write", "root-integration"].includes(effects.workspace.mode);
382
408
  }
383
409
 
410
+ /** Metadata-only planning hint. It never resolves filesystem paths or grants
411
+ * permission; the Host's gated authorization remains authoritative. */
412
+ isStaticallyReadOnly(name: string): boolean {
413
+ const known = this.registry.resolveName(name);
414
+ return known ? this.registry.get(known)?.definition.readOnly === true : false;
415
+ }
416
+
384
417
  resolveEffects(name: string, args: Record<string, unknown> = {}): ToolEffects {
385
418
  const known = this.registry.resolveName(name);
386
419
  return resolveDefinitionEffects(known ? this.registry.get(known)?.definition : undefined, args, this._cwd);
@@ -391,6 +424,14 @@ export class ToolExecutor {
391
424
  args: Record<string, unknown>,
392
425
  signal?: AbortSignal,
393
426
  context?: Readonly<ToolExecutionContext>,
427
+ ): ToolAuthorization | ToolResult | Promise<ToolAuthorization | ToolResult> {
428
+ if (this._workspaceGate) return this._workspaceGate.authorize(this._workspace.root,
429
+ () => this.authorizeUngated(name, args, signal, context), signal);
430
+ return this.authorizeUngated(name, args, signal, context);
431
+ }
432
+
433
+ private authorizeUngated(
434
+ name: string, args: Record<string, unknown>, signal?: AbortSignal, context?: Readonly<ToolExecutionContext>,
394
435
  ): ToolAuthorization | ToolResult | Promise<ToolAuthorization | ToolResult> {
395
436
  // A near-miss spelling is repaired; everything downstream sees the real name.
396
437
  const repaired = this.registry.resolveName(name);
@@ -468,6 +509,14 @@ export class ToolExecutor {
468
509
  async executeAuthorized(
469
510
  authorization: ToolAuthorization,
470
511
  signal?: AbortSignal,
512
+ ): Promise<ToolResult> {
513
+ if (this._workspaceGate) return this._workspaceGate.execute(this._workspace.root, authorization,
514
+ () => this.executeAuthorizedUngated(authorization, signal), signal);
515
+ return this.executeAuthorizedUngated(authorization, signal);
516
+ }
517
+
518
+ private async executeAuthorizedUngated(
519
+ authorization: ToolAuthorization, signal?: AbortSignal,
471
520
  ): Promise<ToolResult> {
472
521
  const { name, args: parsedArgs, grant, context } = authorization;
473
522
  if (signal?.aborted) {
@@ -483,7 +532,7 @@ export class ToolExecutor {
483
532
  failure: operationFailure("POLICY_DENIED", "executor", context?.toolCallId) };
484
533
  }
485
534
 
486
- this._admitExecution?.();
535
+ this._admitExecution?.(name);
487
536
 
488
537
  const executionId = context?.toolCallId
489
538
  ? `execution:${context.toolCallId}`
@@ -705,6 +754,15 @@ export class ToolExecutor {
705
754
  ];
706
755
 
707
756
  let result = await Promise.race(raceTargets);
757
+ const brokerSeal = result.runtime?.processSeal;
758
+ // Inspect the authoritative broker result before result guards or
759
+ // postprocessors can replace it. A timed-out handler may still write.
760
+ if (this._workspaceGate && (signal?.aborted
761
+ || ["CANCELLED", "DEADLINE_EXCEEDED"].includes(result.failure?.code ?? "")
762
+ || (effects.process.length > 0 && (result.runtime?.processSeal?.state !== "sealed"
763
+ || result.runtime.processSeal.executionId !== executionId)))) {
764
+ this._workspaceGate.markUnconfirmed();
765
+ }
708
766
  brokerObservation = result.runtime?.execution;
709
767
  serviceEvidence = { ...(result.runtime?.service ? { service: result.runtime.service } : {}),
710
768
  ...(result.runtime?.serviceOperation ? { serviceOperation: result.runtime.serviceOperation } : {}) };
@@ -728,6 +786,12 @@ export class ToolExecutor {
728
786
  ...((brokerObservation || commandReceipt) ? { runtime: { ...result.runtime, ...(brokerObservation ? { execution: brokerObservation } : {}), ...(commandReceipt ? { command: commandReceipt } : {}) } } : {}),
729
787
  };
730
788
  }
789
+ // Presentation callbacks may remove or invent fields. For gated process
790
+ // calls only the exact broker-authored receipt may leave this boundary.
791
+ if (this._workspaceGate && effects.process.length > 0) {
792
+ const { processSeal: _formattedSeal, ...rest } = result.runtime ?? {};
793
+ result.runtime = { ...rest, ...(brokerSeal?.state === "sealed" && brokerSeal.executionId === executionId ? { processSeal: brokerSeal } : {}) };
794
+ }
731
795
  const { service: _service, serviceOperation: _operation, ...formattedRuntime } = result.runtime ?? {};
732
796
  result.runtime = {
733
797
  ...formattedRuntime,
@@ -749,8 +813,17 @@ export class ToolExecutor {
749
813
  };
750
814
  }
751
815
  // Recheck formatter additions before any result leaves the executor.
752
- return normalizeToolFailure(this.guardResult(name, parsedArgs, observations.retain(normalizeToolFailure(result, executionId))), executionId);
816
+ let final = normalizeToolFailure(this.guardResult(name, parsedArgs, observations.retain(normalizeToolFailure(result, executionId))), executionId);
817
+ // The final guard runs after postprocessing and may also replace runtime
818
+ // fields. Restore only the original, correctly bound broker receipt.
819
+ if (this._workspaceGate && effects.process.length > 0) {
820
+ const { processSeal: _formattedSeal, ...rest } = final.runtime ?? {};
821
+ final = { ...final, runtime: { ...rest, ...(brokerSeal?.state === "sealed" && brokerSeal.executionId === executionId ? { processSeal: brokerSeal } : {}) } };
822
+ }
823
+ return final;
753
824
  } catch (err) {
825
+ if (this._workspaceGate && (signal?.aborted || (err instanceof ExecutionBoundaryError
826
+ && ["CANCELLED", "DEADLINE_EXCEEDED"].includes(err.failure.code)))) this._workspaceGate.markUnconfirmed();
754
827
  return this.guardResult(name, parsedArgs, observations.retain({ ...executionFailureResult(err, executionId),
755
828
  runtime: { effects, ...serviceEvidence, ...(brokerObservation ? { execution: brokerObservation } : {}) },
756
829
  }));
@@ -130,6 +130,8 @@ export interface ToolResult {
130
130
  /** Runtime metadata for audit/UI. Only bounded command/check status fields
131
131
  * are projected into model-visible results; the rest stays host-side. */
132
132
  runtime?: {
133
+ /** Broker-authored evidence only after every launched process was sealed. */
134
+ processSeal?: { state: "sealed"; executionId: string };
133
135
  /** Actual refusals observed by this command's filtering proxy. */
134
136
  networkDenials?: Array<{ host: string; reason: string }>;
135
137
  /** Host-generated duplicate notice; no tool execution or fresh content occurred. */
@@ -22,10 +22,14 @@ export async function futureRealpath(path: string): Promise<string> {
22
22
 
23
23
  /** Only absence of Git or a repository selects copy isolation. Permission,
24
24
  * corrupt repository and other Git failures must retain their diagnostics. */
25
- export async function workspaceContext(root: string, tempRoot?: string, copy = false) {
25
+ export async function workspaceContext(root: string, tempRoot?: string, copy = false, trustedGit = false) {
26
26
  const realRoot = await realpath(root);
27
- const git = (cwd: string, args: string[]) => exec("git", args, {
28
- cwd, encoding: "utf8", env: { ...process.env, LC_ALL: "C" },
27
+ // Goal must not resolve a repository-controlled executable via PATH or
28
+ // inherit Git configuration injection variables during repository discovery.
29
+ const git = (cwd: string, args: string[]) => exec(trustedGit ? "/usr/bin/git" : "git", args, {
30
+ cwd, encoding: "utf8", env: trustedGit
31
+ ? { PATH: "/usr/bin:/bin", HOME: "/nonexistent", LC_ALL: "C", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" }
32
+ : { ...process.env, LC_ALL: "C" },
29
33
  });
30
34
  if (!copy) {
31
35
  let repo: string | undefined;
@@ -33,7 +37,7 @@ export async function workspaceContext(root: string, tempRoot?: string, copy = f
33
37
  repo = (await git(realRoot, ["rev-parse", "--show-toplevel"])).stdout.trim();
34
38
  } catch (error) {
35
39
  const failure = error as NodeJS.ErrnoException & { stderr?: string };
36
- if (failure.code !== "ENOENT" && !failure.stderr?.includes("not a git repository")) throw error;
40
+ if ((trustedGit || failure.code !== "ENOENT") && !failure.stderr?.includes("not a git repository")) throw error;
37
41
  }
38
42
  if (repo) {
39
43
  const repoRoot = await realpath(repo);
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
3
3
  import { chmod, lstat, mkdir, open, readdir, readlink, realpath, rm, symlink } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { isWithin } from "./context.js";
6
+ import type { PrivateGitBinding } from "./types.js";
6
7
 
7
8
  export type CopyEntry =
8
9
  | { kind: "file"; mode: number; hash: string; bytes: number }
@@ -107,13 +108,24 @@ async function fileEntry(path: string, mode: number): Promise<CopyEntry> {
107
108
  /** Never follows directory links. Hashing is streamed, including large inputs.
108
109
  * source=true excludes private/control files from the initial snapshot only;
109
110
  * introducing one in a child is rejected rather than silently losing edits. */
110
- export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>): Promise<CopyTree> {
111
+ export async function scanCopyTree(root: string, source = false, validateLinks = true, omitEnvironments = source, excludedEnvironments?: Set<string>, privateGit?: PrivateGitBinding): Promise<CopyTree> {
111
112
  const info = await lstat(root);
112
113
  if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`Unsafe copy workspace root: ${root}`);
114
+ const validatePrivateGit = async () => {
115
+ if (!privateGit) return;
116
+ const expected = join(await realpath(root), ".git");
117
+ if (privateGit.directory !== expected) throw new Error("Private Git binding does not belong to copy workspace");
118
+ const stat = await lstat(expected, { bigint: true });
119
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev.toString() !== privateGit.device || stat.ino.toString() !== privateGit.inode) {
120
+ throw new Error("Private Git directory identity changed");
121
+ }
122
+ };
123
+ await validatePrivateGit();
113
124
  const tree: CopyTree = Object.create(null);
114
125
  async function walk(prefix: string): Promise<void> {
115
126
  for (const name of (await readdir(join(root, prefix))).sort()) {
116
127
  const path = prefix ? `${prefix}/${name}` : name;
128
+ if (path === ".git" && privateGit) { await validatePrivateGit(); continue; }
117
129
  if (source && name.startsWith(".zap-copy-merge-")) {
118
130
  throw new Error(`Interrupted copy merge requires recovery before continuing: ${join(root, path)}`);
119
131
  }
@@ -155,6 +167,7 @@ export async function scanCopyTree(root: string, source = false, validateLinks =
155
167
  }
156
168
  }
157
169
  await walk("");
170
+ await validatePrivateGit();
158
171
  return tree;
159
172
  }
160
173
 
@@ -33,6 +33,8 @@ import { futureRealpath, isWithin, workspaceContext } from "./context.js";
33
33
  import { changedCopyPaths, copyTreeOid, materializeCopyTree, removeOwnedCopyTree, scanCopyTree } from "./copy.js";
34
34
  import { COPY_MERGE_JOURNAL } from "../merge/copy-transaction.js";
35
35
  import { agentIndexPaths, copyAgentIndex } from "./git-index.js";
36
+ import { assertPrivateGitHistoryMatches, capturePrivateGitHistory, materializePrivateGitMetadata } from "../goal/git-history-snapshot.js";
37
+ import { withPersistentGitOperation } from "../goal/git-operation-owner.js";
36
38
 
37
39
  const execFileAsync = promisify(execFile);
38
40
 
@@ -103,6 +105,13 @@ async function copySnapshotEntry(sourceRoot: string, targetRoot: string, path: s
103
105
 
104
106
  export interface WorkspaceManagerOptions {
105
107
  root: string;
108
+ /** Fail closed if initialization discovers a Git backend. */
109
+ forbidGit?: boolean;
110
+ /** Host-only Goal hybrid: copy source files and attach independently
111
+ * reconstructed metadata. Commits stay private and are never delivered. */
112
+ copyWithPrivateGit?: { ownerDirectory: string; snapshotRepository: string };
113
+ /** Snapshot the Host-bound parent clone when a Goal child is acquired. */
114
+ capturePrivateGitFromRoot?: { ownerDirectory: string; sourceBinding: import("./types.js").PrivateGitBinding };
106
115
  tempRoot?: string;
107
116
  onLifecycle?: WorkspaceLifecycleHandler;
108
117
  owner?: WorkspaceOwnerIdentity;
@@ -123,6 +132,9 @@ export interface HydrateWorkspaceInput {
123
132
  export class WorkspaceManager {
124
133
  readonly root: string;
125
134
  private tempRoot?: string;
135
+ private forbidGit: boolean;
136
+ private copyWithPrivateGit?: WorkspaceManagerOptions["copyWithPrivateGit"];
137
+ private capturePrivateGitFromRoot?: WorkspaceManagerOptions["capturePrivateGitFromRoot"];
126
138
  private batchRoot?: string;
127
139
  private workspaceTempRoot?: string;
128
140
  private repoRoot?: string;
@@ -141,6 +153,9 @@ export class WorkspaceManager {
141
153
 
142
154
  constructor(options: WorkspaceManagerOptions) {
143
155
  this.root = resolve(options.root);
156
+ this.forbidGit = options.forbidGit ?? false;
157
+ this.copyWithPrivateGit = options.copyWithPrivateGit;
158
+ this.capturePrivateGitFromRoot = options.capturePrivateGitFromRoot;
144
159
  this.tempRoot = options.tempRoot ? resolve(options.tempRoot) : undefined;
145
160
  this.onLifecycle = options.onLifecycle;
146
161
  this.owner = options.owner ?? {
@@ -179,6 +194,7 @@ export class WorkspaceManager {
179
194
  timestamp: Date.now(),
180
195
  });
181
196
  let repoPath: string;
197
+ let privateGit: WorkspaceLease["privateGit"];
182
198
  try {
183
199
  await this.initialize();
184
200
  repoPath = join(this.batchRoot!, "runs", workspaceId);
@@ -187,6 +203,7 @@ export class WorkspaceManager {
187
203
  const tree = await scanCopyTree(this.templatePath!);
188
204
  if (copyTreeOid(tree) !== this.baseOid) throw new Error("Copy workspace baseline was modified");
189
205
  await materializeCopyTree(this.templatePath!, repoPath, tree);
206
+ if (this.copyWithPrivateGit) privateGit = await materializePrivateGitMetadata(this.copyWithPrivateGit.snapshotRepository, repoPath, this.copyWithPrivateGit.ownerDirectory);
190
207
  } else {
191
208
  await git(this.batchRoot!, ["clone", "--local", "--no-hardlinks", this.templatePath!, repoPath]);
192
209
  await git(repoPath, ["checkout", "-b", `zap-agent-${safeRunId(runId)}`]);
@@ -216,6 +233,7 @@ export class WorkspaceManager {
216
233
  repoPath,
217
234
  baseOid: this.baseOid,
218
235
  batchPath: this.batchRoot,
236
+ ...(privateGit ? { privateGit } : {}),
219
237
  };
220
238
  this.leases.set(lease.workspaceId, lease);
221
239
  await this.onLifecycle?.({ type: "workspace_acquired", lease, timestamp: Date.now() });
@@ -310,6 +328,17 @@ export class WorkspaceManager {
310
328
  return artifact;
311
329
  }
312
330
 
331
+ /** Repair owns the still-private lease and may restore its frozen Git
332
+ * history after replacing the file snapshot. Never touches source Git. */
333
+ async restorePrivateGit(lease: WorkspaceLease, snapshotRepository: string): Promise<WorkspaceLease> {
334
+ const recorded = this.leases.get(lease.workspaceId);
335
+ if (!this.copyWithPrivateGit || !recorded || JSON.stringify(recorded) !== JSON.stringify(lease) || lease.mode !== "isolated-copy") throw new Error("Unknown private Git repair lease");
336
+ const privateGit = await materializePrivateGitMetadata(snapshotRepository, lease.path, this.copyWithPrivateGit.ownerDirectory);
337
+ const updated = { ...lease, privateGit };
338
+ this.leases.set(updated.workspaceId, updated);
339
+ return updated;
340
+ }
341
+
313
342
  getArtifact(artifactId: string): AgentArtifact | undefined {
314
343
  const artifact = this.artifacts.get(artifactId);
315
344
  return artifact ? structuredClone(artifact) : undefined;
@@ -323,7 +352,7 @@ export class WorkspaceManager {
323
352
  const baseline = await scanCopyTree(this.templatePath!);
324
353
  if (copyTreeOid(baseline) !== lease.baseOid) throw new Error("Copy workspace baseline was modified");
325
354
  const excludedEnvironments = new Set<string>();
326
- const result = await scanCopyTree(lease.path, false, true, true, excludedEnvironments);
355
+ const result = await scanCopyTree(lease.path, false, true, true, excludedEnvironments, lease.privateGit);
327
356
  for (const path of excludedEnvironments) {
328
357
  if (Object.hasOwn(baseline, path)) {
329
358
  throw new Error(`Cannot exclude existing snapshot path as a Python environment: ${path}. Create the environment in a new directory instead.`);
@@ -340,6 +369,17 @@ export class WorkspaceManager {
340
369
  });
341
370
  if (!existing) await materializeCopyTree(lease.path, resultPath, result);
342
371
  if (copyTreeOid(await scanCopyTree(resultPath)) !== resultOid) throw new Error("Copy artifact was modified");
372
+ let privateGitHistory: AgentArtifact["privateGitHistory"];
373
+ if (lease.privateGit && this.copyWithPrivateGit) {
374
+ const history = join(artifactRoot, "git-history");
375
+ await withPersistentGitOperation(this.copyWithPrivateGit.ownerDirectory, async () => {
376
+ await capturePrivateGitHistory(lease.path, history);
377
+ await assertPrivateGitHistoryMatches(lease.path, join(history, "repository.git"));
378
+ });
379
+ if (copyTreeOid(await scanCopyTree(lease.path, false, true, true, undefined, lease.privateGit)) !== resultOid) throw new Error("Copy workspace changed during Git history freezing");
380
+ const repository = join(history, "repository.git");
381
+ privateGitHistory = { repository, treeHash: copyTreeOid(await scanCopyTree(repository)) };
382
+ }
343
383
  const changedPaths = changedCopyPaths(baseline, result);
344
384
  const artifact: AgentArtifact = {
345
385
  mode: "isolated-copy", artifactId, runId: lease.runId, workspaceId: lease.workspaceId,
@@ -347,6 +387,7 @@ export class WorkspaceManager {
347
387
  changedPaths,
348
388
  // Copy diffs include binary files and directories; line counts are not computed.
349
389
  diffStat: { additions: 0, deletions: 0, files: changedPaths.length },
390
+ ...(privateGitHistory ? { privateGitHistory } : {}),
350
391
  };
351
392
  this.artifacts.set(artifactId, structuredClone(artifact));
352
393
  await this.onLifecycle?.({ type: "artifact_created", lease, artifact, timestamp: Date.now() });
@@ -372,8 +413,9 @@ export class WorkspaceManager {
372
413
  }
373
414
 
374
415
  const copy = input.leases[0].mode === "isolated-copy";
416
+ if (!copy && this.forbidGit) throw new Error("Goal Git workspaces are unavailable: host Git execution is not sealed");
375
417
  if (input.leases.some((lease) => lease.mode !== input.leases[0].mode)) throw new Error("Mixed workspace backends");
376
- const context = await workspaceContext(this.root, this.tempRoot, copy);
418
+ const context = await workspaceContext(this.root, this.tempRoot, copy, this.forbidGit);
377
419
  if (context.mode !== input.leases[0].mode) throw new Error("Recorded workspace backend is unavailable");
378
420
  await mkdir(context.workspaceTempRoot, { recursive: true, mode: 0o700 });
379
421
  const realTempRoot = await realpath(context.workspaceTempRoot);
@@ -397,6 +439,7 @@ export class WorkspaceManager {
397
439
  if ((lease.mode !== "isolated-git" && lease.mode !== "isolated-copy") || !lease.repoPath || !lease.baseOid) {
398
440
  throw new Error(`Workspace lease ${lease.workspaceId} is not hydratable`);
399
441
  }
442
+ if (copy && this.copyWithPrivateGit && !lease.privateGit) throw new Error("Private Git workspace binding is missing");
400
443
  const realRepoPath = await realpath(lease.repoPath);
401
444
  if (dirname(realRepoPath) !== runsPath) {
402
445
  throw new Error(`Workspace lease ${lease.workspaceId} escaped the recorded batch`);
@@ -405,6 +448,7 @@ export class WorkspaceManager {
405
448
  if (await realpath(lease.path) !== expectedWorkspacePath) {
406
449
  throw new Error(`Workspace lease ${lease.workspaceId} has an invalid workspace path`);
407
450
  }
451
+ if (lease.privateGit) await scanCopyTree(lease.path, false, true, true, undefined, lease.privateGit);
408
452
  // A private clone's metadata is writable by its Agent. Validate commits
409
453
  // against the host snapshot/artifact below, never against this directory.
410
454
  }
@@ -431,6 +475,11 @@ export class WorkspaceManager {
431
475
  || JSON.stringify(changedCopyPaths(baseline, result)) !== JSON.stringify(artifact.changedPaths)) {
432
476
  throw new Error("Copy artifact content or changed paths were modified");
433
477
  }
478
+ if (artifact.privateGitHistory) {
479
+ const expected = join(realBatch, "artifacts", artifact.artifactId, "git-history", "repository.git");
480
+ if (artifact.privateGitHistory.repository !== expected || await realpath(expected) !== expected
481
+ || copyTreeOid(await scanCopyTree(expected)) !== artifact.privateGitHistory.treeHash) throw new Error("Private Git artifact was modified");
482
+ }
434
483
  } else {
435
484
  if (await realpath(artifact.repoPath) !== artifact.repoPath) throw new Error("Git artifact escaped its recorded path");
436
485
  await artifactGit(artifact.repoPath, ["cat-file", "-e", `${artifact.resultOid}^{commit}`]);
@@ -466,6 +515,7 @@ export class WorkspaceManager {
466
515
  const baseline = await scanCopyTree(this.templatePath!);
467
516
  if (copyTreeOid(baseline) !== this.baseOid) throw new Error("Copy workspace baseline was modified");
468
517
  await materializeCopyTree(this.templatePath!, path, baseline);
518
+ if (this.copyWithPrivateGit) await materializePrivateGitMetadata(this.copyWithPrivateGit.snapshotRepository, path, this.copyWithPrivateGit.ownerDirectory);
469
519
  } else await git(this.batchRoot!, ["clone", "--local", "--no-hardlinks", this.templatePath!, path]);
470
520
  return { path, baseOid: this.baseOid! };
471
521
  }
@@ -533,7 +583,8 @@ export class WorkspaceManager {
533
583
  }
534
584
 
535
585
  private async initializeOnce(): Promise<void> {
536
- const context = await workspaceContext(this.root, this.tempRoot);
586
+ const context = await workspaceContext(this.root, this.tempRoot, !!this.copyWithPrivateGit || !!this.capturePrivateGitFromRoot, this.forbidGit);
587
+ if (context.mode === "isolated-git" && this.forbidGit) throw new Error("Goal Git workspaces are unavailable: host Git execution is not sealed");
537
588
  this.mode = context.mode;
538
589
  this.repoRoot = context.repoRoot;
539
590
  this.rootRelative = context.rootRelative;
@@ -568,8 +619,21 @@ export class WorkspaceManager {
568
619
  });
569
620
  this.templatePath = join(this.batchRoot, "snapshot");
570
621
  if (this.mode === "isolated-copy") {
622
+ if (this.capturePrivateGitFromRoot) {
623
+ const { ownerDirectory, sourceBinding } = this.capturePrivateGitFromRoot;
624
+ const before = await scanCopyTree(this.repoRoot, true, true, true, undefined, sourceBinding);
625
+ const history = join(this.batchRoot, "parent-git-history");
626
+ await withPersistentGitOperation(ownerDirectory, async () => {
627
+ await capturePrivateGitHistory(this.repoRoot!, history);
628
+ await assertPrivateGitHistoryMatches(this.repoRoot!, join(history, "repository.git"));
629
+ });
630
+ const after = await scanCopyTree(this.repoRoot, true, true, true, undefined, sourceBinding);
631
+ if (copyTreeOid(before) !== copyTreeOid(after)) throw new Error("Parent workspace changed during child Git capture");
632
+ this.copyWithPrivateGit = { ownerDirectory, snapshotRepository: join(history, "repository.git") };
633
+ }
571
634
  const tree = await scanCopyTree(this.repoRoot, true);
572
635
  await materializeCopyTree(this.repoRoot, this.templatePath, tree);
636
+ if (copyTreeOid(await scanCopyTree(this.repoRoot, true)) !== copyTreeOid(tree)) throw new Error("Copy workspace changed during snapshot");
573
637
  this.baseOid = copyTreeOid(tree);
574
638
  return;
575
639
  }
@@ -1,5 +1,12 @@
1
1
  export type WorkspaceMode = "shared-readonly" | "isolated-git" | "isolated-copy";
2
2
 
3
+ /** Host-recorded identity, never accepted from model tool arguments. */
4
+ export interface PrivateGitBinding {
5
+ directory: string;
6
+ device: string;
7
+ inode: string;
8
+ }
9
+
3
10
  export interface WorkspaceLease {
4
11
  workspaceId: string;
5
12
  runId: string;
@@ -8,6 +15,8 @@ export interface WorkspaceLease {
8
15
  repoPath?: string;
9
16
  baseOid?: string;
10
17
  batchPath?: string;
18
+ /** Host-created private metadata, excluded from delivered file artifacts. */
19
+ privateGit?: PrivateGitBinding;
11
20
  }
12
21
 
13
22
  export interface AgentArtifact {
@@ -26,6 +35,8 @@ export interface AgentArtifact {
26
35
  deletions: number;
27
36
  files: number;
28
37
  };
38
+ /** Private commit history is retained as evidence, never applied to the source repository. */
39
+ privateGitHistory?: { repository: string; treeHash: string };
29
40
  }
30
41
 
31
42
  export interface MergeResult {