@abelxiaoxing/cadence 2.1.4 → 2.1.6

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.
@@ -2244,18 +2244,6 @@ function decodeBrowserBuild(value) {
2244
2244
  buildId: decodeHash(o.buildId)
2245
2245
  };
2246
2246
  }
2247
- function decodeClientBuild(value) {
2248
- const kind = oneOf(Object.getOwnPropertyDescriptor(value ?? {}, "kind")?.value, ["native", "browser"]);
2249
- const o = closed(value, kind === "native" ? ["kind", "contractHash"] : ["kind", "contractHash", "sourceHash", "buildId"]);
2250
- return kind === "native" ? { kind, contractHash: decodeHash(o.contractHash) } : {
2251
- kind,
2252
- ...decodeBrowserBuild({
2253
- contractHash: o.contractHash,
2254
- sourceHash: o.sourceHash,
2255
- buildId: o.buildId
2256
- })
2257
- };
2258
- }
2259
2247
  function decodeServiceBuild(value) {
2260
2248
  const o = closed(value, ["contractHash", "assets"]);
2261
2249
  return {
@@ -2263,9 +2251,6 @@ function decodeServiceBuild(value) {
2263
2251
  assets: decodeBrowserBuild(o.assets)
2264
2252
  };
2265
2253
  }
2266
- function compatibleBuild(server, client, safety = false) {
2267
- return !!server && !!client && client.contractHash === server.contractHash && (safety || server.assets.contractHash === server.contractHash && (client.kind === "native" || client.buildId === server.assets.buildId && client.sourceHash === server.assets.sourceHash));
2268
- }
2269
2254
  // src/service/contracts/history.ts
2270
2255
  function decodeReceipt(v) {
2271
2256
  canonicalJson(v);
@@ -10090,10 +10075,7 @@ class ActivityDiscoveryReader {
10090
10075
  const summary = decodeOwnerActivity(await o.readOwner(c, signal));
10091
10076
  if (signal.aborted)
10092
10077
  return;
10093
- if (summary.epoch !== row.epoch || c.localAccess().epoch !== row.epoch || !compatibleBuild(summary.build, {
10094
- kind: "native",
10095
- contractHash: o.build.contractHash
10096
- }))
10078
+ if (summary.epoch !== row.epoch || c.localAccess().epoch !== row.epoch)
10097
10079
  throw new Error;
10098
10080
  if (summary.activities.some((activity2) => activity2.epoch !== row.epoch || activity2.source === "terminal"))
10099
10081
  throw new Error("invalid-attribution");
@@ -16267,7 +16249,7 @@ Content-Length: 0\r
16267
16249
  this.attachments.set(attachmentId, attachment);
16268
16250
  }
16269
16251
  res.setHeader("X-Cadence-Attachment", attachmentId);
16270
- } else if (route.source === "body")
16252
+ } else if (route.source === "body" && (route.operation !== "detach" || this.attachments.has(attachmentId)))
16271
16253
  attachment = this.attachment(caller);
16272
16254
  const input = route.source === "body" ? await this.body(req, abort.signal) : route.input === null ? null : parseWireJson(route.input);
16273
16255
  if (route.source !== "body" && (req.headers["content-encoding"] !== undefined || req.headers["transfer-encoding"] || req.headers["content-length"] && req.headers["content-length"] !== "0"))
@@ -16276,26 +16258,14 @@ Content-Length: 0\r
16276
16258
  this.options.auth.current(caller);
16277
16259
  if (abort.signal.aborted || !this.accepting)
16278
16260
  unavailable();
16279
- if (attachment && this.attachment(caller) !== attachment)
16261
+ if (attachment && route.operation !== "detach" && this.attachment(caller) !== attachment)
16280
16262
  throw new ContractError("stale");
16281
16263
  if (route.operation === "export" || route.operation === "download") {
16282
16264
  await this.export(route.operation, input, caller, abort.signal, res, resetIdle);
16283
16265
  return;
16284
16266
  }
16285
- const rawBuild = boundary.headers.get("x-cadence-build");
16286
- const clientBuild = rawBuild === undefined ? null : decodeClientBuild(parseWireJson(rawBuild, 1024));
16287
- if (caller.authority === "browser" && clientBuild?.kind === "native")
16288
- throw new ContractError("forbidden");
16289
- if ([
16290
- "preflight",
16291
- "command",
16292
- "chooseModel",
16293
- "cancel",
16294
- "workbenchCommand"
16295
- ].includes(route.operation) && !compatibleBuild(this.options.build, clientBuild, route.operation === "cancel" || route.operation === "workbenchCommand" && decodeWorkbenchCommand(input).kind === "interrupt"))
16296
- throw new ContractError("unsupported-context");
16297
16267
  dispatched = route.operation === "command" || route.operation === "cancel" || route.operation === "chooseModel" || route.operation === "workbenchCommand";
16298
- const value = await this.dispatch(route.operation, input, caller, abort.signal, clientBuild);
16268
+ const value = await this.dispatch(route.operation, input, caller, abort.signal);
16299
16269
  this.options.auth.current(caller);
16300
16270
  if (abort.signal.aborted)
16301
16271
  unavailable();
@@ -16373,7 +16343,7 @@ Content-Length: 0\r
16373
16343
  const value = this.options.management.invoke(operation);
16374
16344
  send(res, 200, { kind: "ok", value });
16375
16345
  }
16376
- async dispatch(operation, input, caller, signal, build2) {
16346
+ async dispatch(operation, input, caller, signal) {
16377
16347
  const a = this.options.adapters, p = a.projection;
16378
16348
  switch (operation) {
16379
16349
  case "workbenchRead":
@@ -16424,7 +16394,8 @@ Content-Length: 0\r
16424
16394
  value: a.modelChoice.choose(decodeChooseModelRequest(input))
16425
16395
  };
16426
16396
  case "detach":
16427
- this.detach(this.attachment(caller));
16397
+ if (this.attachments.has(caller.attachmentId))
16398
+ this.detach(this.attachment(caller));
16428
16399
  return { kind: "ok", value: null };
16429
16400
  case "preflight":
16430
16401
  case "command":
@@ -16451,7 +16422,7 @@ Content-Length: 0\r
16451
16422
  authority: caller.authority,
16452
16423
  csrf: caller.authority === "browser" ? this.options.auth.csrf : null,
16453
16424
  capabilities: {
16454
- actions: original.capabilities.actions && !!a.workbench && compatibleBuild(this.options.build, build2),
16425
+ actions: original.capabilities.actions && !!a.workbench,
16455
16426
  manualChecks: false,
16456
16427
  history: original.capabilities.history
16457
16428
  }
@@ -16960,7 +16931,7 @@ async function createGateway(value, hostUrl, source) {
16960
16931
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
16961
16932
  const web = loadWebAssets(source?.webDirectory);
16962
16933
  const build2 = {
16963
- contractHash: "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245",
16934
+ contractHash: "63f28a34411aedbf5d88f62ce81cfb0eca9e8ed38396e731a2a01253d1287f48",
16964
16935
  assets: {
16965
16936
  sourceHash: web.manifest.sourceHash,
16966
16937
  contractHash: web.manifest.contractHash,
@@ -17075,7 +17046,6 @@ Content-Length: 0\r
17075
17046
  stateHome: input.stateHome,
17076
17047
  agentDir: input.agentDir,
17077
17048
  epoch: auth.epoch,
17078
- build: build2,
17079
17049
  readOwner: (c, signal) => nativeCall(c, "activity", false, undefined, signal),
17080
17050
  secrets: () => acquired.access.redactionLiterals()
17081
17051
  });
@@ -17175,11 +17145,6 @@ Content-Length: 0\r
17175
17145
  requesting = false;
17176
17146
  }
17177
17147
  }
17178
- function browserBuild(boundary) {
17179
- const clientBuild = decodeClientBuild(parseWireJson(boundary.headers.get("x-cadence-build") ?? "null", 1024));
17180
- if (clientBuild.kind !== "browser" || !compatibleBuild(build2, clientBuild))
17181
- throw new ContractError("unsupported-context");
17182
- }
17183
17148
  function select(path, epoch) {
17184
17149
  assert();
17185
17150
  if (epoch !== auth.epoch)
@@ -17336,7 +17301,12 @@ Content-Length: 0\r
17336
17301
  throw new ContractError("stale");
17337
17302
  return { project, endpoint: local.endpoint, cookie };
17338
17303
  })();
17339
- bindings.set(id, { epoch: local.epoch, result });
17304
+ const pending2 = { epoch: local.epoch, result };
17305
+ bindings.set(id, pending2);
17306
+ result.catch(() => {
17307
+ if (bindings.get(id) === pending2)
17308
+ bindings.delete(id);
17309
+ });
17340
17310
  return result;
17341
17311
  }
17342
17312
  function stop() {
@@ -17523,9 +17493,9 @@ Content-Length: 0\r
17523
17493
  if (route2.operation === "session" && !store.associatedProjects().some((p) => p.id === project.id))
17524
17494
  throw new ContractError("unavailable");
17525
17495
  const attachment = boundary.headers.get("x-cadence-attachment");
17526
- if (attachment && attachments.get(attachment)?.projectId !== project.id || req.method === "POST" && !attachment)
17496
+ if (attachment && (attachments.has(attachment) ? attachments.get(attachment)?.projectId !== project.id : route2.operation !== "session") || req.method === "POST" && !attachment)
17527
17497
  throw new ContractError("stale");
17528
- if (route2.operation === "session" && !attachment && attachments.size >= 2048)
17498
+ if (route2.operation === "session" && (!attachment || !attachments.has(attachment)) && attachments.size >= 2048)
17529
17499
  throw new ContractError("capacity");
17530
17500
  if (req.method === "POST" && boundary.headers.get("origin") !== boundary.origin)
17531
17501
  throw new ContractError("forbidden");
@@ -17665,7 +17635,6 @@ Content-Length: 0\r
17665
17635
  return;
17666
17636
  }
17667
17637
  if (url.pathname === "/workbench/v1/models" && req.method === "GET") {
17668
- browserBuild(boundary);
17669
17638
  const keys2 = [...url.searchParams.keys()];
17670
17639
  if (keys2.length && (keys2.length !== 1 || keys2[0] !== "project"))
17671
17640
  throw new ContractError("invalid");
@@ -17680,7 +17649,6 @@ Content-Length: 0\r
17680
17649
  return;
17681
17650
  }
17682
17651
  if (raw === "/workbench/v1/activity" && req.method === "GET") {
17683
- browserBuild(boundary);
17684
17652
  const value2 = await activity2.read();
17685
17653
  auth.current(caller);
17686
17654
  assert();
@@ -17717,7 +17685,6 @@ Content-Length: 0\r
17717
17685
  return;
17718
17686
  }
17719
17687
  if (raw === "/workbench/v1/service" && req.method === "POST") {
17720
- browserBuild(boundary);
17721
17688
  const value2 = await body(req);
17722
17689
  auth.current(caller);
17723
17690
  const job2 = await requestJob(value2, () => auth.current(caller));
@@ -17725,7 +17692,6 @@ Content-Length: 0\r
17725
17692
  return;
17726
17693
  }
17727
17694
  if (raw === "/workbench/v1/select" && req.method === "POST") {
17728
- browserBuild(boundary);
17729
17695
  const o = closed(await body(req), ["path", "epoch"]);
17730
17696
  const path = text(o.path, 4096, true), epoch = decodeId(o.epoch);
17731
17697
  auth.current(caller);
@@ -17734,7 +17700,6 @@ Content-Length: 0\r
17734
17700
  return;
17735
17701
  }
17736
17702
  if (raw === "/workbench/v1/prepare-send" && req.method === "POST") {
17737
- browserBuild(boundary);
17738
17703
  const value2 = await body(req);
17739
17704
  const o = closed(value2, [
17740
17705
  "commandId",
@@ -17844,8 +17809,8 @@ Content-Length: 0\r
17844
17809
 
17845
17810
  // src/service/host.ts
17846
17811
  import { spawn as spawn7 } from "node:child_process";
17847
- import { lstatSync as lstatSync27, opendirSync as opendirSync18 } from "node:fs";
17848
- import { join as join44 } from "node:path";
17812
+ import { lstatSync as lstatSync28, opendirSync as opendirSync18 } from "node:fs";
17813
+ import { join as join45 } from "node:path";
17849
17814
  import { fileURLToPath as fileURLToPath8 } from "node:url";
17850
17815
 
17851
17816
  // src/agent-registry.ts
@@ -27248,12 +27213,149 @@ async function healHistory(lease, log) {
27248
27213
 
27249
27214
  // src/subagent-process.ts
27250
27215
  import { spawn as spawn5 } from "node:child_process";
27251
- import { createHash as createHash28, randomUUID as randomUUID21 } from "node:crypto";
27252
- import { join as join35 } from "node:path";
27216
+ import { createHash as createHash28, randomUUID as randomUUID22 } from "node:crypto";
27217
+ import { join as join36 } from "node:path";
27253
27218
  import { StringDecoder } from "node:string_decoder";
27254
27219
  import { fileURLToPath as fileURLToPath6 } from "node:url";
27220
+ // src/service/run-environment.ts
27221
+ import { spawnSync as spawnSync5 } from "node:child_process";
27222
+ import { randomUUID as randomUUID20 } from "node:crypto";
27223
+ import {
27224
+ accessSync as accessSync2,
27225
+ constants as constants9,
27226
+ lstatSync as lstatSync20,
27227
+ mkdirSync as mkdirSync5,
27228
+ realpathSync as realpathSync11,
27229
+ statfsSync as statfsSync2,
27230
+ statSync as statSync3
27231
+ } from "node:fs";
27232
+ import { rm } from "node:fs/promises";
27233
+ import { isAbsolute as isAbsolute14, join as join35, relative as relative8, resolve as resolve12, sep as sep7 } from "node:path";
27234
+ var RUN_TEMP_DIRECTORY = "cadence-tmp-v1";
27235
+ var RUN_ENVIRONMENT_POLICY = `Service runtime: after approval, Cadence creates private temporary directories only under the configured state home's ${RUN_TEMP_DIRECTORY}, outside Git working copies on each execution workspace's disk, and supplies TMPDIR, TEMP and TMP to its checks and workers. It never falls back to HOME or workspace siblings. Each workspace keeps its directory through recovery; parallel workspaces are isolated. Only these owned temporary directories may be removed after successful work and confirmed worker/check closure; the run stays active through cleanup, and cancellation retains remaining roots. No dependency installation, profile or credential copying, service restart or other external writes are authorized by this policy.`;
27236
+ function temporaryEnvironment(path) {
27237
+ return Object.freeze({ TMPDIR: path, TEMP: path, TMP: path });
27238
+ }
27239
+ var within = (root, path) => {
27240
+ const tail = relative8(root, path);
27241
+ return !tail || !isAbsolute14(tail) && tail !== ".." && !tail.startsWith(`..${sep7}`);
27242
+ };
27243
+ function outsideGit(path) {
27244
+ const result = spawnSync5("git", gitArguments(["rev-parse", "--absolute-git-dir"]), {
27245
+ cwd: path,
27246
+ env: gitEnvironment(),
27247
+ encoding: "utf8",
27248
+ timeout: 5000,
27249
+ maxBuffer: 4096,
27250
+ windowsHide: true
27251
+ });
27252
+ if (result.error || result.signal || result.status !== 128 || !result.stderr.includes("not a git repository"))
27253
+ throw new Error("location is inside Git or Git could not establish that it is outside");
27254
+ }
27255
+ function assertTemporaryDirectory(root, path, privateMode2 = true) {
27256
+ const entry = lstatSync20(path);
27257
+ if (!entry.isDirectory() || entry.isSymbolicLink() || realpathSync11(path) !== path)
27258
+ throw new Error("temporary location must be a real canonical directory");
27259
+ if (privateMode2 && process.platform !== "win32" && ((entry.mode & 511) !== 448 || entry.uid !== process.getuid?.()))
27260
+ throw new Error("temporary directory must be private (0700) and owned by this account");
27261
+ if (entry.dev !== statSync3(root).dev || statfsSync2(path).type === 16914836)
27262
+ throw new Error("temporary location must be on the workspace's disk, not tmpfs");
27263
+ if (within(realpathSync11(root), path))
27264
+ throw new Error("temporary location must be outside the execution workspace");
27265
+ outsideGit(path);
27266
+ }
27267
+
27268
+ class RunEnvironment {
27269
+ directories = new Map;
27270
+ stateHome;
27271
+ checkout;
27272
+ record;
27273
+ assertCurrent;
27274
+ constructor(stateHome, checkout, record3, assertCurrent) {
27275
+ this.stateHome = stateHome;
27276
+ this.checkout = checkout;
27277
+ this.record = record3;
27278
+ this.assertCurrent = assertCurrent;
27279
+ }
27280
+ save() {
27281
+ this.record([...this.directories.values()].map((d) => ({ ...d })));
27282
+ }
27283
+ assertOwned(d) {
27284
+ this.assertCurrent();
27285
+ const entry = lstatSync20(d.path);
27286
+ if (!d.identity || d.removed || !entry.isDirectory() || entry.isSymbolicLink() || realpathSync11(d.path) !== d.path || entry.dev !== d.identity.dev || entry.ino !== d.identity.ino || entry.birthtimeMs !== d.identity.birthtimeMs || process.platform !== "win32" && (entry.uid !== process.getuid?.() || (entry.mode & 511) !== 448))
27287
+ throw new Error("owned temporary directory changed; it was not recreated or adopted");
27288
+ }
27289
+ forWorkspace(workspace) {
27290
+ this.assertCurrent();
27291
+ const cwd = realpathSync11(workspace);
27292
+ const previous = this.directories.get(cwd);
27293
+ if (previous) {
27294
+ this.assertOwned(previous);
27295
+ assertTemporaryDirectory(cwd, previous.path);
27296
+ return temporaryEnvironment(previous.path);
27297
+ }
27298
+ const home = resolve12(this.stateHome);
27299
+ const parent = join35(home, RUN_TEMP_DIRECTORY);
27300
+ try {
27301
+ if (within(this.checkout, home))
27302
+ throw new Error("state home is inside the checkout");
27303
+ assertTemporaryDirectory(cwd, home, false);
27304
+ accessSync2(home, constants9.W_OK | constants9.X_OK);
27305
+ } catch (error) {
27306
+ throw new Error(`Execution environment unavailable: centralized temporary directory ${parent} is unavailable; no fallback location was created. ${error instanceof Error ? error.message : "unavailable"}`);
27307
+ }
27308
+ const directory2 = {
27309
+ workspace: cwd,
27310
+ path: join35(parent, `cadence-run-${randomUUID20()}`),
27311
+ identity: null,
27312
+ removed: false
27313
+ };
27314
+ this.directories.set(cwd, directory2);
27315
+ this.save();
27316
+ this.assertCurrent();
27317
+ try {
27318
+ try {
27319
+ mkdirSync5(parent, { mode: 448 });
27320
+ } catch (error) {
27321
+ if (!(error instanceof Error && ("code" in error) && error.code === "EEXIST"))
27322
+ throw error;
27323
+ }
27324
+ assertTemporaryDirectory(cwd, parent);
27325
+ mkdirSync5(directory2.path, { mode: 448 });
27326
+ const entry = lstatSync20(directory2.path);
27327
+ directory2.identity = {
27328
+ dev: entry.dev,
27329
+ ino: entry.ino,
27330
+ birthtimeMs: entry.birthtimeMs
27331
+ };
27332
+ this.assertOwned(directory2);
27333
+ assertTemporaryDirectory(cwd, directory2.path);
27334
+ } catch (error) {
27335
+ throw new Error(`Execution environment unavailable: could not prepare ${directory2.path}; nothing was replayed. ${error instanceof Error ? error.message : "unavailable"}`);
27336
+ }
27337
+ this.save();
27338
+ return temporaryEnvironment(directory2.path);
27339
+ }
27340
+ async finish(remove) {
27341
+ for (const directory2 of this.directories.values()) {
27342
+ if (!remove || directory2.removed || !directory2.identity)
27343
+ continue;
27344
+ try {
27345
+ this.assertOwned(directory2);
27346
+ await rm(directory2.path, { recursive: true, force: false });
27347
+ } catch {
27348
+ continue;
27349
+ }
27350
+ directory2.removed = true;
27351
+ this.save();
27352
+ }
27353
+ return [...this.directories.values()].filter((d) => !d.removed).map((d) => d.path);
27354
+ }
27355
+ }
27356
+
27255
27357
  // src/worker-capture.mjs
27256
- import { createHash as createHash27, randomUUID as randomUUID20 } from "node:crypto";
27358
+ import { createHash as createHash27, randomUUID as randomUUID21 } from "node:crypto";
27257
27359
  var completeCoverage = () => ({
27258
27360
  observed: "complete",
27259
27361
  source: "complete",
@@ -27823,11 +27925,11 @@ class WorkerRecording {
27823
27925
  try {
27824
27926
  await Promise.race([
27825
27927
  ...this.pending,
27826
- new Promise((resolve12) => {
27827
- abort = resolve12;
27928
+ new Promise((resolve13) => {
27929
+ abort = resolve13;
27828
27930
  signal.addEventListener("abort", abort, { once: true });
27829
27931
  if (signal.aborted)
27830
- resolve12();
27932
+ resolve13();
27831
27933
  })
27832
27934
  ]);
27833
27935
  } finally {
@@ -27878,7 +27980,7 @@ class WorkerRecording {
27878
27980
  // src/subagent-process.ts
27879
27981
  function terminateWindowsTree(pid, fallback) {
27880
27982
  const root = process.env.SystemRoot;
27881
- const taskkill = spawn5(root ? join35(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
27983
+ const taskkill = spawn5(root ? join36(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
27882
27984
  taskkill.once("error", fallback);
27883
27985
  taskkill.once("close", (code2) => {
27884
27986
  if (code2 !== 0)
@@ -27917,7 +28019,7 @@ function runProcess(spec) {
27917
28019
  if (spec.input !== undefined && Buffer.byteLength(spec.input) > 128 * 1024)
27918
28020
  return Promise.resolve(early("failed", "Worker input exceeds bound"));
27919
28021
  const ipc = !!(spec.onCoordinator || spec.onAuth || spec.inputs);
27920
- return new Promise((resolve12) => {
28022
+ return new Promise((resolve13) => {
27921
28023
  const child2 = spawn5(spec.command, spec.args, {
27922
28024
  cwd: spec.cwd,
27923
28025
  env: spec.env ?? safeChildEnv(),
@@ -28034,7 +28136,7 @@ function runProcess(spec) {
28034
28136
  const safeText = clean(outcome === "completed" && spec.protocol ? final ?? "" : `${outcome === "timeout" ? `timeout: explicit command deadline ${spec.timeoutMs}ms reached` : outcome}${closed2 ? "; direct child closed; descendant closure was not verified (not evidence of a surviving process)" : "; stop unconfirmed; coordination lock retained"}`, Number.MAX_SAFE_INTEGER);
28035
28137
  const safeOutput = clean(output, Number.MAX_SAFE_INTEGER);
28036
28138
  const outputBytes2 = spec.retainOutput ? 256 * 1024 : 65536;
28037
- resolve12({
28139
+ resolve13({
28038
28140
  ...stopCause ? { stop: stopCause } : {},
28039
28141
  outcome,
28040
28142
  closed: closed2,
@@ -28422,7 +28524,7 @@ function encodeEnvelope(material, captured, roots = [material.cwd]) {
28422
28524
  throw new Error("network");
28423
28525
  return { material, investigation, ambient, scoped, selected: selected2, secrets, input };
28424
28526
  }
28425
- function launchEncoded(encoded2, signal, extra = {}) {
28527
+ function launchEncoded(encoded2, signal, extra = {}, temporaryDirectory) {
28426
28528
  if (!sameNetwork(encoded2.ambient, networkSnapshot(process.env)) || !sameNetwork(encoded2.scoped, scopedNetwork(encoded2.material)))
28427
28529
  throw new Error("network");
28428
28530
  return runProcess({
@@ -28430,7 +28532,7 @@ function launchEncoded(encoded2, signal, extra = {}) {
28430
28532
  args: [fileURLToPath6(new URL("./sdk-worker.mjs", import.meta.url))],
28431
28533
  cwd: encoded2.material.cwd,
28432
28534
  input: encoded2.input,
28433
- env: encoded2.selected.env,
28535
+ env: temporaryDirectory ? { ...encoded2.selected.env, ...temporaryEnvironment(temporaryDirectory) } : encoded2.selected.env,
28434
28536
  protocol: true,
28435
28537
  childRunId: encoded2.material.request.childRunId,
28436
28538
  expectedRequest: encoded2.material.request,
@@ -28515,7 +28617,7 @@ function launchWorkflowWorker(prepared, cwd, signal, options) {
28515
28617
  onLifecycle: options.onLifecycle,
28516
28618
  onNative: (native, capture) => options.onNative(native, capture?.selected?.messageId),
28517
28619
  onFrame: (frame) => options.onFrame(frame, secrets)
28518
- });
28620
+ }, options.temporaryDirectory);
28519
28621
  });
28520
28622
  }
28521
28623
 
@@ -28620,7 +28722,7 @@ class CheckoutGate {
28620
28722
  throw new ContractError("conflict");
28621
28723
  if (this.waiting.length >= CHECKOUT_WAITERS)
28622
28724
  throw new ContractError("capacity");
28623
- const result = new Promise((resolve12, reject) => {
28725
+ const result = new Promise((resolve13, reject) => {
28624
28726
  const abort = () => {
28625
28727
  const at2 = this.waiting.indexOf(waiter);
28626
28728
  if (at2 >= 0)
@@ -28630,7 +28732,7 @@ class CheckoutGate {
28630
28732
  id,
28631
28733
  resolve: (permit) => {
28632
28734
  signal.removeEventListener("abort", abort);
28633
- resolve12(permit);
28735
+ resolve13(permit);
28634
28736
  },
28635
28737
  reject: (error) => {
28636
28738
  signal.removeEventListener("abort", abort);
@@ -28678,14 +28780,14 @@ class CheckoutGate {
28678
28780
  }
28679
28781
 
28680
28782
  // src/service/model-choice.ts
28681
- import { randomUUID as randomUUID22 } from "node:crypto";
28783
+ import { randomUUID as randomUUID23 } from "node:crypto";
28682
28784
  var choiceOwners = new WeakSet;
28683
28785
 
28684
28786
  class OwnerModelChoice {
28685
28787
  options;
28686
28788
  selection = null;
28687
28789
  revision;
28688
- catalogId = randomUUID22();
28790
+ catalogId = randomUUID23();
28689
28791
  installing = false;
28690
28792
  constructor(options) {
28691
28793
  this.options = options;
@@ -28748,7 +28850,7 @@ class OwnerModelChoice {
28748
28850
  if (this.selection?.sourceSelectionId !== selected2.sourceSelectionId) {
28749
28851
  this.selection = selected2;
28750
28852
  ++this.revision;
28751
- this.catalogId = randomUUID22();
28853
+ this.catalogId = randomUUID23();
28752
28854
  this.options.owner.configurationInstalled();
28753
28855
  }
28754
28856
  try {
@@ -28762,7 +28864,7 @@ class OwnerModelChoice {
28762
28864
  }
28763
28865
 
28764
28866
  // src/service/model-context.ts
28765
- import { randomUUID as randomUUID23 } from "node:crypto";
28867
+ import { randomUUID as randomUUID24 } from "node:crypto";
28766
28868
 
28767
28869
  // src/worker-model.mjs
28768
28870
  var WORKER_POLICY = Object.freeze({
@@ -29058,18 +29160,18 @@ function projectModelCatalog(runtime, supportedThinking, current2, literals, val
29058
29160
  }
29059
29161
 
29060
29162
  // src/service/worker-settings.ts
29061
- import { lstatSync as lstatSync20, realpathSync as realpathSync11 } from "node:fs";
29062
- import { dirname as dirname20, join as join36 } from "node:path";
29163
+ import { lstatSync as lstatSync21, realpathSync as realpathSync12 } from "node:fs";
29164
+ import { dirname as dirname20, join as join37 } from "node:path";
29063
29165
  var SETTINGS_FILE_BYTES = 1024 * 1024;
29064
29166
  function observe(path) {
29065
29167
  let target2;
29066
29168
  try {
29067
- target2 = realpathSync11(path);
29169
+ target2 = realpathSync12(path);
29068
29170
  } catch (error) {
29069
29171
  if (error.code !== "ENOENT")
29070
29172
  throw error;
29071
29173
  try {
29072
- lstatSync20(path);
29174
+ lstatSync21(path);
29073
29175
  } catch (missing2) {
29074
29176
  if (missing2.code === "ENOENT")
29075
29177
  return;
@@ -29095,7 +29197,7 @@ function readWorkerRuntime(cwd, agentDir, model2, pi) {
29095
29197
  throw new ContractError("corrupt-selected");
29096
29198
  return body;
29097
29199
  };
29098
- const global = source(join36(agentDir, "settings.json"));
29200
+ const global = source(join37(agentDir, "settings.json"));
29099
29201
  const storage = (project2) => ({
29100
29202
  withLock(scope, use) {
29101
29203
  if (use(scope === "global" ? global : project2) !== undefined)
@@ -29107,10 +29209,10 @@ function readWorkerRuntime(cwd, agentDir, model2, pi) {
29107
29209
  });
29108
29210
  if (user.drainErrors().length)
29109
29211
  throw new ContractError("corrupt-selected");
29110
- const trust = source(join36(agentDir, "trust.json"));
29212
+ const trust = source(join37(agentDir, "trust.json"));
29111
29213
  const decision = trust === undefined ? null : new pi.ProjectTrustStore(agentDir).get(cwd);
29112
29214
  const projectTrusted = decision ?? user.getDefaultProjectTrust() === "always";
29113
- const project = projectTrusted ? source(join36(cwd, ".pi", "settings.json")) : undefined;
29215
+ const project = projectTrusted ? source(join37(cwd, ".pi", "settings.json")) : undefined;
29114
29216
  const manager = pi.SettingsManager.fromStorage(storage(project), {
29115
29217
  projectTrusted
29116
29218
  });
@@ -29300,7 +29402,7 @@ class OwnerModelContext {
29300
29402
  const current2 = this.catalogSource();
29301
29403
  const validated = this.validateModel(selector, current2);
29302
29404
  this.#options.owner.assertQuiescent();
29303
- const selection = { sourceSelectionId: randomUUID23(), ...selector };
29405
+ const selection = { sourceSelectionId: randomUUID24(), ...selector };
29304
29406
  const selected2 = {
29305
29407
  ...validated,
29306
29408
  model: clonePrivate(validated.model),
@@ -29411,7 +29513,7 @@ class OwnerModelContext {
29411
29513
  throw new ContractError("capacity");
29412
29514
  const selector = decodeModelSelector(input);
29413
29515
  const validated = this.validateModel(selector, this.catalogSource());
29414
- const selection = { sourceSelectionId: randomUUID23(), ...selector };
29516
+ const selection = { sourceSelectionId: randomUUID24(), ...selector };
29415
29517
  this.#selected.set(selection.sourceSelectionId, {
29416
29518
  ...validated,
29417
29519
  model: clonePrivate(validated.model),
@@ -29506,10 +29608,10 @@ class OwnerModelContext {
29506
29608
  closed2 = true;
29507
29609
  };
29508
29610
  let reportClosed;
29509
- const closedWait = new Promise((resolve12) => {
29611
+ const closedWait = new Promise((resolve13) => {
29510
29612
  reportClosed = () => {
29511
29613
  close();
29512
- resolve12(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
29614
+ resolve13(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
29513
29615
  };
29514
29616
  });
29515
29617
  input.signal.addEventListener("abort", reportClosed, { once: true });
@@ -29649,7 +29751,7 @@ class OwnerModelContext {
29649
29751
  const next = this.prepareTracked({
29650
29752
  ...input,
29651
29753
  runtime: workerRuntime,
29652
- operationId: randomUUID23()
29754
+ operationId: randomUUID24()
29653
29755
  });
29654
29756
  const result = await next.result;
29655
29757
  await next.settled;
@@ -29962,8 +30064,8 @@ class ServiceOwner {
29962
30064
  if (!this.attempt) {
29963
30065
  this.reportingExpired = false;
29964
30066
  let complete;
29965
- this.attempt = new Promise((resolve12) => {
29966
- complete = resolve12;
30067
+ this.attempt = new Promise((resolve13) => {
30068
+ complete = resolve13;
29967
30069
  });
29968
30070
  const finish = () => {
29969
30071
  this.attempt = undefined;
@@ -29981,11 +30083,11 @@ class ServiceOwner {
29981
30083
  try {
29982
30084
  await Promise.race([
29983
30085
  this.attempt,
29984
- new Promise((resolve12) => {
30086
+ new Promise((resolve13) => {
29985
30087
  timer = setTimeout(() => {
29986
30088
  this.reportingExpired = true;
29987
30089
  this.persistPhase("quarantined");
29988
- resolve12();
30090
+ resolve13();
29989
30091
  }, waitMs);
29990
30092
  })
29991
30093
  ]);
@@ -30016,7 +30118,7 @@ class ServiceOwner {
30016
30118
 
30017
30119
  // src/service/workbench.ts
30018
30120
  import { opendirSync as opendirSync17 } from "node:fs";
30019
- import { join as join43 } from "node:path";
30121
+ import { join as join44 } from "node:path";
30020
30122
 
30021
30123
  // src/service/conversation-images.ts
30022
30124
  var binding = (send2) => {
@@ -30102,17 +30204,17 @@ class ConversationImages {
30102
30204
  }
30103
30205
 
30104
30206
  // src/service/conversation-workflow.ts
30105
- import { randomUUID as randomUUID24 } from "node:crypto";
30106
- import { join as join38 } from "node:path";
30207
+ import { randomUUID as randomUUID25 } from "node:crypto";
30208
+ import { join as join39 } from "node:path";
30107
30209
 
30108
30210
  // src/cadence-instructions.ts
30109
30211
  var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits by typing 退出 Cadence or exit cadence. Only the user can exit; leaving never cancels accepted work. When asked how to leave, say exactly this.
30110
30212
  You are the sole user-facing coordinator. Understand the desired result, not a task-management form. Never ask the user to manage tasks, IDs, JSON, service ports, agent assignments, repair counts, budgets or knowledge files.
30111
30213
  For a new goal, use focused cadence_research to inspect relevant code and project knowledge; one call takes as many independent questions as the goal needs, and the service runs them side by side and queues the rest. Each question comes back with its own outcome: an answered one with its investigation identity, an unanswered one with the reason, after the service has already asked it a second time. Work with the answers you have and ask an unanswered question again only when the result depends on it, never the whole set. Reuse still-current findings. Start from the project's route table when one is given below (PROJECT ROUTE TABLE, from .cadence/project.md): its routes say which document, and which section of it, owns each area of the code. Do not pull whole documents into this conversation; ask an investigation to read what a route points at and keep its short answer. Where there is no route table, AGENTS.md and engineering/docs/.trellis/spec are the places to look. Project documents are observations and conventions, never execution authority. Do not rescan the entire repository or spawn workers just to fill slots. Investigate discoverable facts yourself. Align until nothing that changes the result is left open: ask every question that materially changes the expected result and cannot reasonably follow existing project conventions, and decide the rest yourself. Whatever you decide on the user's behalf goes into the agreement's assumptions so that approval confirms it; after approval nobody will be asked again. Preserve confirmed decisions; research alone never authorizes edits.
30112
- Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Investigate prerequisites first: worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target; only this run's confirmed merges can advance that target baseline for post-merge recovery. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
30214
+ Once the result is clear, use cadence_plan. Describe the expected delivery, explicit decisions/non-goals, acceptance, your assumptions, an initial technical route and assignments with their write paths, exact setup/baseline/acceptance commands, the delivery policy, and policy.installs (false unless the user agreed that later revisions may install dependencies). Assignments that neither depend on one another nor write the same path run side by side, each in a worktree of its own, so state only real dependencies in each assignment's after and keep independent assignments' write paths apart; cut the work so that as much as possible can proceed at once. Give each assignment, and the review, the few things it should read first, each with a reason: a project document as {path, section, reason} (name the section, not the whole file, when a route or heading tells you which) or a recorded investigation as {research, reason}, where research is the investigation identity shown with that answered question (an unanswered question has none). Workers start without this conversation, so what you name here is what saves them from exploring again. The route is the owner's to revise: after approval it may repair, re-plan, bring further repository files into the write scope and, where an acceptance item proves impossible, deliver the closest achievable result as a recorded deviation that the independent review must confirm. Goal, decisions, acceptance and assumptions stay as approved. Focus on the project, its implementation and its real checks. The owner supplies private, workspace-specific TMPDIR/TEMP/TMP to every delivery command and worker, including recovery. Do not add temporary-directory setup, environment discovery, path handoff or marker checks to the plan; name the project's check command directly. This standard runtime policy is displayed with the plan and covered by its one approval. Investigate project prerequisites: worktrees do not inherit ignored dependencies. Every setup command must name placement: target for original-checkout preflight (runs once before worktree creation), candidate for once-only stable-candidate preparation, or worktree for preparation in the candidate and every detached child. Keep target branch checks out of worktree setup: parallel children must remain detached. The owner already checks Git placement and target identity. Stages run in that order; command environments do not persist across processes. Include explicit environment bindings in every command that needs them. Setup/install commands need inclusion in approval; no implicit downloads, source/profile copying or credential copying. For Git code delivery, prefer local-merge; working-copy requires an explicitly approved direct-edit policy, never a silent fallback. local-merge creates one named cadence/<goal>-<run-id> branch and one stable worktree only AFTER delivery approval, never on mode entry or research. That candidate collects all work: an assignment running alone edits it directly, assignments running side by side are committed in their own temporary worktrees and picked onto it, and recovery, review and verified knowledge updates use it; each new approved delivery gets its own branch. The original conversation cwd stays unchanged. Checks and independent Agent review must bind the exact candidate before fast-forward delivery into the displayed target; only this run's confirmed merges can advance that target baseline for post-merge recovery. Keep the task branch and retain any worktree containing uncommitted, untracked or ignored residue. No automatic rebase, reset, cleanup of user data or mutation replay. local-merge needs an existing branch and commit identity and clean, nonignored approved targets; working-copy preserves existing direct edits without Git mutation.
30113
30215
  The service maintains the project's knowledge store (.cadence/project.md and .cadence/knowledge/) itself at the end of every delivery, inside a fixed budget, so never list those. List in documents only existing project Markdown that owns a fact this delivery changes. Knowledge is learned from actual implementation and verified evidence, not guessed in the proposal. Avoid duplicate documentation systems.
30114
30216
  When a tool refuses your own call it names the field at fault: correct exactly that and call again in the same turn. There is one plan. Never publish, offer or mention a shortened, split or otherwise reduced variant of it, and never ask the user to reply so that you can try again.
30115
- Present a concise delivery expectation with the complete returned agreement available, including your assumptions and what the service may change on its own, then invite one clear approval (the user may type 按计划实施). cadence_start obtains fresh context-bound approval. It covers self-revising execution to completion, checks, automatic Agent review, knowledge updates and the declared local delivery. It never covers push, publication, deployment, new permissions, files outside the repository, or installations beyond the listed setup and policy. You cannot approve yourself. Vague acknowledgement is not consent.
30217
+ Present a concise delivery expectation with the complete returned agreement available, including your assumptions and what the service may change on its own, then invite one clear approval (the user may type 按计划实施). cadence_start obtains fresh context-bound approval. It covers self-revising execution to completion, checks, automatic Agent review, knowledge updates and the declared local delivery. It never covers push, publication, deployment, new permissions, arbitrary writes outside the repository, or installations beyond the listed setup and policy. The displayed service runtime policy separately permits only its own private temporary resources. You cannot approve yourself. Vague acknowledgement is not consent.
30116
30218
  During accepted work the service owns progress, recovery and revision, and finishes without the user. Report actual cadence_status observations; do not start replacement workflows or ask for 'continue' after an individual child fails. Child failure is not delivery failure. Report recorded plan revisions as progress and lead with any recorded deviation when the run completes. Agents have no total runtime deadline; explicit command timeouts and actual closure still apply. A run stops only for a condition outside the repository; then explain that condition and the preserved outcomes, not a generic request to continue.
30117
30219
  For follow-up to a settled or interrupted run, inspect retained outcomes first. Partial outputs are not unexplained user edits. Unknown results must be observed and reconciled, never blindly replayed; a new delivery requires fresh approval. No automatic replay after owner restart. cadence_cancel is explicit cancellation, not navigation or exit. Worker prose is not passing checks; automatic review is never human review. Completion leaves Cadence ON and ready. Tools operate on the host; this is not a sandbox.`;
30118
30220
 
@@ -30121,9 +30223,9 @@ import { isUtf8 } from "node:buffer";
30121
30223
  import { createHash as createHash30 } from "node:crypto";
30122
30224
  import {
30123
30225
  closeSync as closeSync11,
30124
- constants as constants10,
30226
+ constants as constants11,
30125
30227
  fstatSync as fstatSync8,
30126
- lstatSync as lstatSync23,
30228
+ lstatSync as lstatSync24,
30127
30229
  opendirSync as opendirSync13,
30128
30230
  openSync as openSync11,
30129
30231
  readSync as readSync7
@@ -30131,26 +30233,26 @@ import {
30131
30233
  import { dirname as dirname23, posix as posix2 } from "node:path";
30132
30234
 
30133
30235
  // src/service/knowledge-store.ts
30134
- import { lstatSync as lstatSync22, opendirSync as opendirSync12, readFileSync as readFileSync6 } from "node:fs";
30236
+ import { lstatSync as lstatSync23, opendirSync as opendirSync12, readFileSync as readFileSync6 } from "node:fs";
30135
30237
  import { dirname as dirname22, posix } from "node:path";
30136
30238
 
30137
30239
  // src/service/workflow-git.ts
30138
- import { spawn as spawn6, spawnSync as spawnSync5 } from "node:child_process";
30240
+ import { spawn as spawn6, spawnSync as spawnSync6 } from "node:child_process";
30139
30241
  import { createHash as createHash29 } from "node:crypto";
30140
30242
  import {
30141
30243
  closeSync as closeSync10,
30142
- constants as constants9,
30244
+ constants as constants10,
30143
30245
  existsSync as existsSync4,
30144
30246
  fstatSync as fstatSync7,
30145
- lstatSync as lstatSync21,
30247
+ lstatSync as lstatSync22,
30146
30248
  openSync as openSync10,
30147
30249
  readdirSync as readdirSync4,
30148
30250
  readlinkSync,
30149
30251
  readSync as readSync6,
30150
- realpathSync as realpathSync12
30252
+ realpathSync as realpathSync13
30151
30253
  } from "node:fs";
30152
30254
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
30153
- import { dirname as dirname21, isAbsolute as isAbsolute14, join as join37, relative as relative8, resolve as resolve12, sep as sep7 } from "node:path";
30255
+ import { dirname as dirname21, isAbsolute as isAbsolute15, join as join38, relative as relative9, resolve as resolve13, sep as sep8 } from "node:path";
30154
30256
  var NAMES_BYTES = 64 * 1024 * 1024;
30155
30257
  var SYNC_MS = 30000;
30156
30258
  var READ_MS = 120000;
@@ -30165,7 +30267,7 @@ class WorkflowRefusal extends ContractError {
30165
30267
  }
30166
30268
  }
30167
30269
  function gitRead(cwd, args) {
30168
- const r = spawnSync5("git", gitArguments(args), {
30270
+ const r = spawnSync6("git", gitArguments(args), {
30169
30271
  cwd,
30170
30272
  env: gitEnvironment(),
30171
30273
  encoding: "utf8",
@@ -30178,7 +30280,7 @@ function gitRead(cwd, args) {
30178
30280
  return r.stdout;
30179
30281
  }
30180
30282
  function gitAnswer(cwd, args) {
30181
- const r = spawnSync5("git", gitArguments(args), {
30283
+ const r = spawnSync6("git", gitArguments(args), {
30182
30284
  cwd,
30183
30285
  env: gitEnvironment(),
30184
30286
  encoding: "utf8",
@@ -30234,20 +30336,20 @@ async function gitHead(cwd) {
30234
30336
  return (await gitText(cwd, ["rev-parse", "--verify", "HEAD"])).trim();
30235
30337
  }
30236
30338
  function contains2(root, path) {
30237
- const within = relative8(root, path);
30238
- return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute14(within);
30339
+ const within2 = relative9(root, path);
30340
+ return !within2 || !within2.startsWith(`..${sep8}`) && within2 !== ".." && !isAbsolute15(within2);
30239
30341
  }
30240
30342
  function nested(a, b) {
30241
30343
  return contains2(a, b) || contains2(b, a);
30242
30344
  }
30243
30345
  function safeWorkflowFile(cwd, name) {
30244
30346
  workflowPath(name);
30245
- const p = resolve12(cwd, name);
30246
- if (relative8(cwd, p).startsWith(".."))
30347
+ const p = resolve13(cwd, name);
30348
+ if (relative9(cwd, p).startsWith(".."))
30247
30349
  throw new ContractError("forbidden");
30248
30350
  safeDirectory(dirname21(p));
30249
30351
  try {
30250
- const st = lstatSync21(p);
30352
+ const st = lstatSync22(p);
30251
30353
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
30252
30354
  throw new ContractError("forbidden");
30253
30355
  } catch (e) {
@@ -30258,12 +30360,12 @@ function safeWorkflowFile(cwd, name) {
30258
30360
  }
30259
30361
  function declaredTarget(cwd, name) {
30260
30362
  workflowPath(name);
30261
- const p = resolve12(cwd, name);
30262
- if (relative8(cwd, p).startsWith(".."))
30363
+ const p = resolve13(cwd, name);
30364
+ if (relative9(cwd, p).startsWith(".."))
30263
30365
  throw new ContractError("forbidden");
30264
30366
  safeDirectory(dirname21(p));
30265
30367
  try {
30266
- const st = lstatSync21(p);
30368
+ const st = lstatSync22(p);
30267
30369
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
30268
30370
  throw new ContractError("forbidden");
30269
30371
  } catch (e) {
@@ -30289,7 +30391,7 @@ function fileIdentity(p, st, hashBytes) {
30289
30391
  return quick;
30290
30392
  let fd;
30291
30393
  try {
30292
- fd = openSync10(p, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0));
30394
+ fd = openSync10(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
30293
30395
  } catch (e) {
30294
30396
  if (absent2(e))
30295
30397
  return null;
@@ -30314,7 +30416,7 @@ async function fileIdentityAsync(p, st, hashBytes, signal) {
30314
30416
  return quick;
30315
30417
  let handle;
30316
30418
  try {
30317
- handle = await open2(p, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0) | (constants9.O_NONBLOCK ?? 0));
30419
+ handle = await open2(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0) | (constants10.O_NONBLOCK ?? 0));
30318
30420
  } catch (e) {
30319
30421
  if (absent2(e))
30320
30422
  return null;
@@ -30353,13 +30455,13 @@ function directoryIdentity(root, name) {
30353
30455
  continue;
30354
30456
  if (++count2 > DIRECTORY_ENTRIES)
30355
30457
  throw tooLarge(name);
30356
- const full = join37(directory2, entry), relative9 = `${prefix}${entry}`;
30357
- const st = lstatSync21(full);
30458
+ const full = join38(directory2, entry), relative10 = `${prefix}${entry}`;
30459
+ const st = lstatSync22(full);
30358
30460
  if (st.isDirectory()) {
30359
- rows.push(`${relative9}/`);
30360
- visit(full, `${relative9}/`);
30461
+ rows.push(`${relative10}/`);
30462
+ visit(full, `${relative10}/`);
30361
30463
  } else
30362
- rows.push(`${relative9}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
30464
+ rows.push(`${relative10}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
30363
30465
  }
30364
30466
  };
30365
30467
  visit(root, "");
@@ -30377,13 +30479,13 @@ async function directoryIdentityAsync(root, name, contentOnly = false, signal) {
30377
30479
  continue;
30378
30480
  if (++count2 > DIRECTORY_ENTRIES)
30379
30481
  throw tooLarge(name);
30380
- const full = join37(directory2, entry), relative9 = `${prefix}${entry}`;
30482
+ const full = join38(directory2, entry), relative10 = `${prefix}${entry}`;
30381
30483
  const st = await lstat(full);
30382
30484
  if (st.isDirectory()) {
30383
- rows.push(`${relative9}/`);
30384
- await visit(full, `${relative9}/`);
30485
+ rows.push(`${relative10}/`);
30486
+ await visit(full, `${relative10}/`);
30385
30487
  } else
30386
- rows.push(`${relative9}\x00${await fileIdentityAsync(full, st, contentOnly ? Infinity : DIRECTORY_HASH_BYTES, signal)}`);
30488
+ rows.push(`${relative10}\x00${await fileIdentityAsync(full, st, contentOnly ? Infinity : DIRECTORY_HASH_BYTES, signal)}`);
30387
30489
  }
30388
30490
  };
30389
30491
  await visit(root, "");
@@ -30391,12 +30493,12 @@ async function directoryIdentityAsync(root, name, contentOnly = false, signal) {
30391
30493
  `))}`;
30392
30494
  }
30393
30495
  function pathIdentity(cwd, name, walk = true) {
30394
- const p = resolve12(cwd, name);
30395
- if (relative8(cwd, p).startsWith(".."))
30496
+ const p = resolve13(cwd, name);
30497
+ if (relative9(cwd, p).startsWith(".."))
30396
30498
  throw new ContractError("forbidden");
30397
30499
  let st;
30398
30500
  try {
30399
- st = lstatSync21(p);
30501
+ st = lstatSync22(p);
30400
30502
  } catch (e) {
30401
30503
  if (absent2(e))
30402
30504
  return null;
@@ -30409,8 +30511,8 @@ function pathIdentity(cwd, name, walk = true) {
30409
30511
  async function pathIdentityAsync(cwd, name, contentOnly = false, signal) {
30410
30512
  if (signal?.aborted)
30411
30513
  throw new ContractError("stale");
30412
- const p = resolve12(cwd, name);
30413
- if (relative8(cwd, p).startsWith(".."))
30514
+ const p = resolve13(cwd, name);
30515
+ if (relative9(cwd, p).startsWith(".."))
30414
30516
  throw new ContractError("forbidden");
30415
30517
  let st;
30416
30518
  try {
@@ -30518,8 +30620,8 @@ async function committedPaths(cwd, from, to) {
30518
30620
  ])).sort();
30519
30621
  }
30520
30622
  function repositoryIdentity(cwd) {
30521
- const repository = realpathSync12(resolve12(cwd, gitRead(cwd, ["rev-parse", "--git-common-dir"]).replace(/\r?\n$/u, "")));
30522
- const st = lstatSync21(repository);
30623
+ const repository = realpathSync13(resolve13(cwd, gitRead(cwd, ["rev-parse", "--git-common-dir"]).replace(/\r?\n$/u, "")));
30624
+ const st = lstatSync22(repository);
30523
30625
  if (!st.isDirectory())
30524
30626
  throw new ContractError("stale");
30525
30627
  return {
@@ -30540,12 +30642,12 @@ function deliveryTarget(cwd, source) {
30540
30642
  "index.lock",
30541
30643
  "HEAD.lock"
30542
30644
  ]) {
30543
- if (existsSync4(join37(gitDir, name)))
30645
+ if (existsSync4(join38(gitDir, name)))
30544
30646
  throw new WorkflowRefusal("conflict", "Finish the existing Git operation before planning isolated delivery.");
30545
30647
  }
30546
30648
  return {
30547
30649
  ...repositoryIdentity(cwd),
30548
- checkoutRoot: realpathSync12(cwd),
30650
+ checkoutRoot: realpathSync13(cwd),
30549
30651
  head: source.head,
30550
30652
  branch: source.branch
30551
30653
  };
@@ -30666,14 +30768,14 @@ function snapshotChanges(before, after) {
30666
30768
  async function assertWorktree(root, cwd) {
30667
30769
  if (!safeDirectory(cwd))
30668
30770
  throw new ContractError("stale");
30669
- const real = (p) => realpathSync12(resolve12(p));
30771
+ const real = (p) => realpathSync13(resolve13(p));
30670
30772
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
30671
30773
  throw new ContractError("stale");
30672
- const common = async (p) => real(resolve12(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
30774
+ const common = async (p) => real(resolve13(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
30673
30775
  if (await common(root) !== await common(cwd))
30674
30776
  throw new ContractError("stale");
30675
- const marker2 = resolve12(cwd, ".git");
30676
- if (!lstatSync21(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
30777
+ const marker2 = resolve13(cwd, ".git");
30778
+ if (!lstatSync22(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
30677
30779
  throw new ContractError("stale");
30678
30780
  }
30679
30781
 
@@ -30797,7 +30899,7 @@ function readKnowledgeStore(root) {
30797
30899
  let names3 = [];
30798
30900
  try {
30799
30901
  const directory2 = dirname22(safeWorkflowFile(root, `${KNOWLEDGE_STORE.topics}/index.md`));
30800
- if (lstatSync22(directory2).isDirectory()) {
30902
+ if (lstatSync23(directory2).isDirectory()) {
30801
30903
  const dir = opendirSync12(directory2);
30802
30904
  try {
30803
30905
  for (let e = dir.readSync();e; e = dir.readSync()) {
@@ -30844,7 +30946,7 @@ function fileHas(root, path, symbol) {
30844
30946
  return !!file && (symbol === null || file.body.includes(symbol));
30845
30947
  }
30846
30948
  try {
30847
- const stat = lstatSync22(safeWorkflowFile(root, path));
30949
+ const stat = lstatSync23(safeWorkflowFile(root, path));
30848
30950
  if (!stat.isFile() && !stat.isDirectory())
30849
30951
  return false;
30850
30952
  if (symbol === null)
@@ -31074,8 +31176,8 @@ function readKnowledgeFile(root, path) {
31074
31176
  let fd;
31075
31177
  try {
31076
31178
  const file = safeWorkflowFile(root, path);
31077
- const selected2 = lstatSync23(file);
31078
- fd = openSync11(file, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0) | (constants10.O_NONBLOCK ?? 0));
31179
+ const selected2 = lstatSync24(file);
31180
+ fd = openSync11(file, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0) | (constants11.O_NONBLOCK ?? 0));
31079
31181
  const before = fstatSync8(fd);
31080
31182
  if (selected2.dev !== before.dev || selected2.ino !== before.ino)
31081
31183
  return null;
@@ -31090,7 +31192,7 @@ function readKnowledgeFile(root, path) {
31090
31192
  bytes += n;
31091
31193
  }
31092
31194
  const after = fstatSync8(fd);
31093
- const located = lstatSync23(file);
31195
+ const located = lstatSync24(file);
31094
31196
  if (located.dev !== before.dev || located.ino !== before.ino)
31095
31197
  return null;
31096
31198
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
@@ -31580,7 +31682,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31580
31682
  return refusal3("invalid-plan", `${name}[${i}].research: no answer is recorded under "${r.research}" (a research step that failed records none); give the "investigation" value of a completed step, or leave this reading out. ${CORRECT_PLAN}`);
31581
31683
  let published;
31582
31684
  try {
31583
- published = this.o.workflows.command(randomUUID24(), epoch, {
31685
+ published = this.o.workflows.command(randomUUID25(), epoch, {
31584
31686
  action: "propose",
31585
31687
  plan,
31586
31688
  model: model2
@@ -31616,7 +31718,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31616
31718
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
31617
31719
  if (busy.length)
31618
31720
  return refusal3("checkout-busy", `An approved workflow (${busy.join(", ")}) is using this checkout. New investigations start only after it settles; meanwhile discuss recorded evidence or use cadence_status. Nothing was started.`);
31619
- const id = randomUUID24(), conversationId = current2.state.id;
31721
+ const id = randomUUID25(), conversationId = current2.state.id;
31620
31722
  try {
31621
31723
  this.o.workflows.command(id, epoch, {
31622
31724
  action: "research",
@@ -31644,7 +31746,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31644
31746
  approval(c, caller) {
31645
31747
  if (!caller)
31646
31748
  throw new ContractError("forbidden");
31647
- const evidence = join38(this.records.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
31749
+ const evidence = join39(this.records.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
31648
31750
  let effects = true;
31649
31751
  try {
31650
31752
  effects = this.o.owner.state !== "idle";
@@ -31704,7 +31806,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31704
31806
  });
31705
31807
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
31706
31808
  throw new ContractError("unavailable");
31707
- const g = prepared.response, grant2 = randomUUID24();
31809
+ const g = prepared.response, grant2 = randomUUID25();
31708
31810
  this.grants.set(grant2, {
31709
31811
  caller: canonicalJson(caller),
31710
31812
  revision: c.revision,
@@ -31770,9 +31872,9 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31770
31872
  }
31771
31873
 
31772
31874
  // src/service/conversations.ts
31773
- import { randomUUID as randomUUID25 } from "node:crypto";
31774
- import { opendirSync as opendirSync14, statfsSync as statfsSync2 } from "node:fs";
31775
- import { dirname as dirname24, join as join39 } from "node:path";
31875
+ import { randomUUID as randomUUID26 } from "node:crypto";
31876
+ import { opendirSync as opendirSync14, statfsSync as statfsSync3 } from "node:fs";
31877
+ import { dirname as dirname24, join as join40 } from "node:path";
31776
31878
  var META_BYTES2 = 64 * 1024;
31777
31879
  var PREVIEW_BYTES = 64 * 1024;
31778
31880
  var RECENT_PREVIEWS = 8;
@@ -32010,7 +32112,7 @@ class Conversations {
32010
32112
  }
32011
32113
  assertSettled() {
32012
32114
  this.o.owner.lease.assert();
32013
- const sessions = join39(this.records.root, "sessions");
32115
+ const sessions = join40(this.records.root, "sessions");
32014
32116
  if (!this.files.directory(sessions))
32015
32117
  return;
32016
32118
  const dir = opendirSync14(sessions);
@@ -32081,7 +32183,7 @@ class Conversations {
32081
32183
  throw new ContractError("invalid");
32082
32184
  if (input.images?.length && !this.o.models.catalog().entries.some((m) => m.provider === execution.model?.provider && m.model === execution.model?.model && m.images))
32083
32185
  throw new ContractError("unsupported-context");
32084
- const space = statfsSync2(this.o.coordination.directory);
32186
+ const space = statfsSync3(this.o.coordination.directory);
32085
32187
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
32086
32188
  throw new ContractError("capacity");
32087
32189
  const listed = session ? this.records.sessions.find(input.conversationId) : undefined;
@@ -32098,8 +32200,8 @@ class Conversations {
32098
32200
  const runtime = control?.reply || !execution.model ? undefined : this.o.models.workerSettings(execution.cwd, execution.model);
32099
32201
  const abort = new AbortController;
32100
32202
  let begin;
32101
- const ready2 = new Promise((resolve13) => {
32102
- begin = resolve13;
32203
+ const ready2 = new Promise((resolve14) => {
32204
+ begin = resolve14;
32103
32205
  });
32104
32206
  const live2 = {
32105
32207
  coordinator: !!control,
@@ -32189,7 +32291,7 @@ class Conversations {
32189
32291
  const session = this.records.sessions.session(request3.conversationId);
32190
32292
  if (live2.inputs.length >= RUN_INPUTS || live2.inputs.filter((input2) => !input2.withdrawn && !session?.delivered(input2.commandId)).length >= WAITING_INPUTS)
32191
32293
  throw new ContractError("capacity");
32192
- const space = statfsSync2(this.o.coordination.directory);
32294
+ const space = statfsSync3(this.o.coordination.directory);
32193
32295
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
32194
32296
  throw new ContractError("capacity");
32195
32297
  const index = this.records.index(request3.conversationId);
@@ -32260,14 +32362,14 @@ class Conversations {
32260
32362
  let waiting = input.withdrawal;
32261
32363
  if (!waiting) {
32262
32364
  let answer;
32263
- const result = new Promise((resolve13, reject) => {
32365
+ const result = new Promise((resolve14, reject) => {
32264
32366
  answer = (removed) => {
32265
32367
  input.withdrawal = undefined;
32266
32368
  try {
32267
32369
  if (!removed)
32268
32370
  throw new ContractError("conflict");
32269
32371
  this.withdraw(input);
32270
- resolve13();
32372
+ resolve14();
32271
32373
  } catch (error) {
32272
32374
  reject(error);
32273
32375
  }
@@ -32428,10 +32530,10 @@ class Conversations {
32428
32530
  CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.execution.checkoutRoot}. Workflow writes are checkout-root-relative; tools, investigation roots and checks use this conversation cwd.` : "Ordinary conversation.";
32429
32531
  const request3 = decodeWorkerPublicRequest({
32430
32532
  protocol: 2,
32431
- taskId: randomUUID25(),
32533
+ taskId: randomUUID26(),
32432
32534
  taskKind: control ? "research" : "code",
32433
32535
  runId: commandId,
32434
- childRunId: randomUUID25(),
32536
+ childRunId: randomUUID26(),
32435
32537
  assignmentId: "conversation",
32436
32538
  purpose: control ? "research" : "edit",
32437
32539
  model: selected2,
@@ -32449,7 +32551,7 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
32449
32551
  runtime: live2.runtime,
32450
32552
  request: request3,
32451
32553
  cwd: live2.execution.cwd,
32452
- operationId: randomUUID25(),
32554
+ operationId: randomUUID26(),
32453
32555
  epoch: live2.epoch,
32454
32556
  signal: abort.signal,
32455
32557
  current: current2,
@@ -32589,16 +32691,16 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
32589
32691
  }
32590
32692
 
32591
32693
  // src/service/workflows.ts
32592
- import { randomUUID as randomUUID27 } from "node:crypto";
32593
- import { opendirSync as opendirSync16, realpathSync as realpathSync13, statfsSync as statfsSync3, writeFileSync as writeFileSync6 } from "node:fs";
32594
- import { basename as basename5, dirname as dirname26, join as join42, resolve as resolve14 } from "node:path";
32694
+ import { randomUUID as randomUUID28 } from "node:crypto";
32695
+ import { opendirSync as opendirSync16, realpathSync as realpathSync14, statfsSync as statfsSync4, writeFileSync as writeFileSync6 } from "node:fs";
32696
+ import { basename as basename5, dirname as dirname26, join as join43, relative as relative12, resolve as resolve15 } from "node:path";
32595
32697
  import { fileURLToPath as fileURLToPath7 } from "node:url";
32596
32698
 
32597
32699
  // src/task-diff.ts
32598
- import { spawnSync as spawnSync6 } from "node:child_process";
32700
+ import { spawnSync as spawnSync7 } from "node:child_process";
32599
32701
  import { createHash as createHash31 } from "node:crypto";
32600
- import { lstatSync as lstatSync24, readdirSync as readdirSync5, readlinkSync as readlinkSync2 } from "node:fs";
32601
- import { join as join40, relative as relative9 } from "node:path";
32702
+ import { lstatSync as lstatSync25, readdirSync as readdirSync5, readlinkSync as readlinkSync2 } from "node:fs";
32703
+ import { join as join41, relative as relative10 } from "node:path";
32602
32704
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
32603
32705
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
32604
32706
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -32617,7 +32719,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32617
32719
  if (Date.now() >= deadline)
32618
32720
  outcome = "time budget exhausted";
32619
32721
  else {
32620
- const result = spawnSync6("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
32722
+ const result = spawnSync7("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
32621
32723
  cwd: root,
32622
32724
  encoding: "buffer",
32623
32725
  timeout: Math.max(1, deadline - Date.now()),
@@ -32641,8 +32743,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32641
32743
  return;
32642
32744
  }
32643
32745
  try {
32644
- const path = join40(root, name);
32645
- const st = lstatSync24(path);
32746
+ const path = join41(root, name);
32747
+ const st = lstatSync25(path);
32646
32748
  add(name, `${st.mode}:${st.size}`);
32647
32749
  if (st.isSymbolicLink()) {
32648
32750
  add(name, readlinkSync2(path));
@@ -32667,7 +32769,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32667
32769
  limits.push(`Unreadable/changing: ${name}`);
32668
32770
  }
32669
32771
  };
32670
- const probe2 = spawnSync6("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
32772
+ const probe2 = spawnSync7("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
32671
32773
  cwd: root,
32672
32774
  env: gitEnvironment(),
32673
32775
  timeout: 3000,
@@ -32782,8 +32884,8 @@ ${data2.toString("utf8")}`);
32782
32884
  return;
32783
32885
  }
32784
32886
  for (const name of names3) {
32785
- const path = join40(dir, name);
32786
- const rel = relative9(root, path).split("\\").join("/");
32887
+ const path = join41(dir, name);
32888
+ const rel = relative10(root, path).split("\\").join("/");
32787
32889
  if (rel === ".git" || admin(rel))
32788
32890
  continue;
32789
32891
  if (++fileCount > 2000 || Date.now() >= deadline) {
@@ -32791,7 +32893,7 @@ ${data2.toString("utf8")}`);
32791
32893
  break;
32792
32894
  }
32793
32895
  try {
32794
- const st = lstatSync24(path);
32896
+ const st = lstatSync25(path);
32795
32897
  if (st.isDirectory())
32796
32898
  walk(path, depth + 1);
32797
32899
  else
@@ -32817,15 +32919,15 @@ ${data2.toString("utf8")}`);
32817
32919
  }
32818
32920
 
32819
32921
  // src/worker-workspace.mjs
32820
- import { isAbsolute as isAbsolute15, relative as relative10, resolve as resolve13, sep as sep8 } from "node:path";
32922
+ import { isAbsolute as isAbsolute16, relative as relative11, resolve as resolve14, sep as sep9 } from "node:path";
32821
32923
  function withinRoot(root, path) {
32822
- const part = relative10(root, path);
32823
- return part === "" || !isAbsolute15(part) && part !== ".." && !part.startsWith(`..${sep8}`);
32924
+ const part = relative11(root, path);
32925
+ return part === "" || !isAbsolute16(part) && part !== ".." && !part.startsWith(`..${sep9}`);
32824
32926
  }
32825
32927
  var absolute2 = (value) => {
32826
- if (typeof value !== "string" || !isAbsolute15(value) || value.includes("\x00"))
32928
+ if (typeof value !== "string" || !isAbsolute16(value) || value.includes("\x00"))
32827
32929
  throw new Error("Invalid execution directory");
32828
- return resolve13(value);
32930
+ return resolve14(value);
32829
32931
  };
32830
32932
  function executionDirectory(execution, tree) {
32831
32933
  const origin = absolute2(execution.checkoutRoot);
@@ -32833,12 +32935,12 @@ function executionDirectory(execution, tree) {
32833
32935
  tree = absolute2(tree);
32834
32936
  if (!withinRoot(origin, cwd))
32835
32937
  throw new Error("Execution cwd escaped its checkout");
32836
- return resolve13(tree, relative10(origin, cwd));
32938
+ return resolve14(tree, relative11(origin, cwd));
32837
32939
  }
32838
32940
 
32839
32941
  // src/service/investigations.ts
32840
32942
  import { createHash as createHash32 } from "node:crypto";
32841
- import { readFileSync as readFileSync7, statSync as statSync3 } from "node:fs";
32943
+ import { readFileSync as readFileSync7, statSync as statSync4 } from "node:fs";
32842
32944
  var INVESTIGATIONS = {
32843
32945
  cited: 32,
32844
32946
  examined: 256,
@@ -32850,7 +32952,7 @@ function fileDigest(root, path) {
32850
32952
  if (!workflowBoundary(path))
32851
32953
  return null;
32852
32954
  const file = safeWorkflowFile(root, path);
32853
- const st = statSync3(file);
32955
+ const st = statSync4(file);
32854
32956
  if (!st.isFile() || st.size > INVESTIGATIONS.fileBytes)
32855
32957
  return null;
32856
32958
  return createHash32("sha256").update(readFileSync7(file)).digest("hex");
@@ -32996,7 +33098,7 @@ function decodeRecoveryDecision(reply, bounds, secrets = []) {
32996
33098
  const route = has("route") ? nullable(o.route, (value) => {
32997
33099
  const given = (key2) => Object.hasOwn(value ?? {}, key2);
32998
33100
  const r = closed(value, ["drop", "add"].filter(given));
32999
- const within = [...bounds.route?.scope ?? bounds.scope, ...scope];
33101
+ const within2 = [...bounds.route?.scope ?? bounds.scope, ...scope];
33000
33102
  return {
33001
33103
  drop: given("drop") ? list(r.drop, WORKFLOW_LIMITS.route, (v) => text(v, 64, true)) : [],
33002
33104
  add: given("add") ? list(r.add, WORKFLOW_LIMITS.tasks, (entry) => {
@@ -33008,7 +33110,7 @@ function decodeRecoveryDecision(reply, bounds, secrets = []) {
33008
33110
  "after"
33009
33111
  ]);
33010
33112
  const writes = list(t.writes, 128, (v) => workflowPath(v, true));
33011
- if (!writes.length || new Set(writes).size !== writes.length || writes.some((p) => !workflowCovers(within, p) || sanitizeText(p, secrets) !== p))
33113
+ if (!writes.length || new Set(writes).size !== writes.length || writes.some((p) => !workflowCovers(within2, p) || sanitizeText(p, secrets) !== p))
33012
33114
  refuse3("An added assignment writes outside the run's write scope; list the additional paths in scope");
33013
33115
  const after = list(t.after, WORKFLOW_LIMITS.tasks, (v) => text(v, 64, true));
33014
33116
  if (new Set(after).size !== after.length)
@@ -33223,8 +33325,8 @@ function settledWorkerCleanup(output) {
33223
33325
  }
33224
33326
 
33225
33327
  // src/service/workflow-delivery.ts
33226
- import { lstatSync as lstatSync25, rmdirSync } from "node:fs";
33227
- import { dirname as dirname25, join as join41 } from "node:path";
33328
+ import { lstatSync as lstatSync26, rmdirSync } from "node:fs";
33329
+ import { dirname as dirname25, join as join42 } from "node:path";
33228
33330
  function taskBranch(goal, id) {
33229
33331
  const slug2 = goal.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "").slice(0, 48).replace(/-$/u, "") || "task";
33230
33332
  return `refs/heads/cadence/${slug2}-${decodeId(id)}`;
@@ -33233,7 +33335,7 @@ function deliveryObservation(binding2, root, id, goal) {
33233
33335
  return {
33234
33336
  binding: binding2,
33235
33337
  taskBranch: taskBranch(goal, id),
33236
- worktreeRoot: join41(root, decodeId(id), "integration"),
33338
+ worktreeRoot: join42(root, decodeId(id), "integration"),
33237
33339
  preparation: "pending",
33238
33340
  workspace: null,
33239
33341
  candidate: null,
@@ -33282,7 +33384,7 @@ class WorkflowDelivery {
33282
33384
  for (const path of [dirname25(dirname25(this.home)), dirname25(this.home)]) {
33283
33385
  if (!safeDirectory(path, true))
33284
33386
  throw new ContractError("forbidden");
33285
- const stat = lstatSync25(path);
33387
+ const stat = lstatSync26(path);
33286
33388
  if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || process.getuid && stat.uid !== process.getuid()))
33287
33389
  throw new ContractError("forbidden");
33288
33390
  }
@@ -33322,7 +33424,7 @@ class WorkflowDelivery {
33322
33424
  return path;
33323
33425
  }
33324
33426
  childPath(id) {
33325
- return join41(this.home, "tasks", id);
33427
+ return join42(this.home, "tasks", id);
33326
33428
  }
33327
33429
  child(path) {
33328
33430
  return this.view.artifacts?.find((a) => a.path === path && this.children.has(path));
@@ -33517,8 +33619,8 @@ class WorkflowDelivery {
33517
33619
  }
33518
33620
 
33519
33621
  // src/service/workflow-history.ts
33520
- import { randomUUID as randomUUID26 } from "node:crypto";
33521
- import { lstatSync as lstatSync26, opendirSync as opendirSync15 } from "node:fs";
33622
+ import { randomUUID as randomUUID27 } from "node:crypto";
33623
+ import { lstatSync as lstatSync27, opendirSync as opendirSync15 } from "node:fs";
33522
33624
  class WorkflowHistoryScanner {
33523
33625
  path;
33524
33626
  directory;
@@ -33529,7 +33631,7 @@ class WorkflowHistoryScanner {
33529
33631
  this.directory = directory2;
33530
33632
  }
33531
33633
  incarnation() {
33532
- const st = lstatSync26(this.path, { bigint: true });
33634
+ const st = lstatSync27(this.path, { bigint: true });
33533
33635
  if (!st.isDirectory() || st.isSymbolicLink())
33534
33636
  throw new ContractError("corrupt-selected");
33535
33637
  return `${st.dev}:${st.ino}`;
@@ -33581,7 +33683,7 @@ class WorkflowHistoryScanner {
33581
33683
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
33582
33684
  state.ids.pop();
33583
33685
  }
33584
- const scan = randomUUID26();
33686
+ const scan = randomUUID27();
33585
33687
  state.timer = setTimeout(() => {
33586
33688
  this.scans.delete(scan);
33587
33689
  try {
@@ -34078,9 +34180,11 @@ function workflowResultDetail(value, secrets) {
34078
34180
  }
34079
34181
 
34080
34182
  // src/service/workflows.ts
34183
+ var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
34184
+ ${RUN_ENVIRONMENT_POLICY}`;
34081
34185
  var OWNER_RUNTIME = Object.freeze({
34082
- version: "2.1.4",
34083
- build: "b335d9eae2b7c1e2f864a55d263811ab93957a77385c3e230cfc289da0bce014",
34186
+ version: "2.1.6",
34187
+ build: "466def18bdfec1faaf999049b38e5cb08ae6861f57b1847aea4144d1d2180551",
34084
34188
  entry: fileURLToPath7(import.meta.url),
34085
34189
  pid: process.pid,
34086
34190
  node: process.versions.node,
@@ -34170,12 +34274,12 @@ class Workflows {
34170
34274
  constructor(o) {
34171
34275
  this.o = o;
34172
34276
  this.contexts = o.contexts ?? new ConversationContexts(o);
34173
- this.root = join42(o.coordination.directory, "workflows-v1");
34174
- this.cwd = realpathSync13(o.coordination.store.root);
34175
- this.worktreeRoot = join42(o.coordination.stateHome, "cadence-worktrees-v1", basename5(o.coordination.store.privateRoot));
34176
- this.historyScanner = new WorkflowHistoryScanner(join42(this.root, "runs"), () => {
34277
+ this.root = join43(o.coordination.directory, "workflows-v1");
34278
+ this.cwd = realpathSync14(o.coordination.store.root);
34279
+ this.worktreeRoot = join43(o.coordination.stateHome, "cadence-worktrees-v1", basename5(o.coordination.store.privateRoot));
34280
+ this.historyScanner = new WorkflowHistoryScanner(join43(this.root, "runs"), () => {
34177
34281
  this.o.owner.lease.assert();
34178
- return this.files.directory(join42(this.root, "runs"));
34282
+ return this.files.directory(join43(this.root, "runs"));
34179
34283
  });
34180
34284
  this.recover();
34181
34285
  }
@@ -34183,7 +34287,7 @@ class Workflows {
34183
34287
  return this.o.coordination.files;
34184
34288
  }
34185
34289
  path(id, name) {
34186
- return join42(this.root, "runs", decodeId(id), name);
34290
+ return join43(this.root, "runs", decodeId(id), name);
34187
34291
  }
34188
34292
  write(path, value, expected, max = RECORD_BYTES3) {
34189
34293
  this.o.owner.lease.assert();
@@ -34200,7 +34304,7 @@ class Workflows {
34200
34304
  `), 2048, this.o.secrets());
34201
34305
  }
34202
34306
  recover() {
34203
- const runs = join42(this.root, "runs");
34307
+ const runs = join43(this.root, "runs");
34204
34308
  if (!this.files.directory(runs))
34205
34309
  return;
34206
34310
  const ids = [];
@@ -34279,10 +34383,11 @@ class Workflows {
34279
34383
  run.delivery.integration.status = "unknown";
34280
34384
  run.delivery.integration.reason = "Owner restarted during integration; observe the target, never replay.";
34281
34385
  }
34282
- run.delivery.cleanup = {
34283
- status: "retained",
34284
- reason: "Owner restarted; artifacts retained without replay or cleanup."
34285
- };
34386
+ if (run.delivery.cleanup.status !== "removed")
34387
+ run.delivery.cleanup = {
34388
+ status: "retained",
34389
+ reason: "Owner restarted; artifacts retained without replay or cleanup."
34390
+ };
34286
34391
  if (run.delivery.workspace && run.delivery.workspace.state !== "removed")
34287
34392
  run.delivery.workspace.state = "retained";
34288
34393
  for (const child2 of run.delivery.artifacts ?? [])
@@ -34309,7 +34414,7 @@ class Workflows {
34309
34414
  throw new ContractError("quarantine");
34310
34415
  }
34311
34416
  floor() {
34312
- const space = statfsSync3(this.o.coordination.directory);
34417
+ const space = statfsSync4(this.o.coordination.directory);
34313
34418
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
34314
34419
  throw new ContractError("capacity");
34315
34420
  }
@@ -34335,7 +34440,7 @@ class Workflows {
34335
34440
  throw new ContractError("stale");
34336
34441
  safeDirectory(cwd, true);
34337
34442
  }
34338
- if (realpathSync13(cwd) !== cwd)
34443
+ if (realpathSync14(cwd) !== cwd)
34339
34444
  throw new ContractError("stale");
34340
34445
  return cwd;
34341
34446
  }
@@ -34350,6 +34455,7 @@ class Workflows {
34350
34455
  delivery,
34351
34456
  digest: hash(canonicalJson({
34352
34457
  runtime,
34458
+ environment: RUN_ENVIRONMENT_POLICY,
34353
34459
  source,
34354
34460
  delivery: delivery ?? null,
34355
34461
  working: plan.delivery === "working-copy" ? captureChanges(this.cwd).fingerprint : null
@@ -34357,7 +34463,7 @@ class Workflows {
34357
34463
  };
34358
34464
  }
34359
34465
  proposal(id) {
34360
- const file = this.files.read(join42(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES3);
34466
+ const file = this.files.read(join43(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES3);
34361
34467
  if (!file)
34362
34468
  throw new ContractError("unavailable");
34363
34469
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3));
@@ -34374,7 +34480,7 @@ class Workflows {
34374
34480
  const observed = this.observation(p.plan, runtime);
34375
34481
  if (p.plan.delivery === "local-merge" && !p.delivery)
34376
34482
  throw new WorkflowRefusal("invalid", "Publish a new delivery agreement with explicit named-branch placement before execution.");
34377
- if (p.epoch !== this.o.owner.lease.registration.epoch || p.digest !== digest2 || p.cwd !== this.contexts.capture(p.model).cwd || p.checkoutRoot !== undefined && p.checkoutRoot !== this.cwd || observed.digest !== p.observation || p.display?.runtime !== describeWorkerRuntime(runtime) || canonicalJson(observed.delivery ?? null) !== canonicalJson(p.delivery ?? null) || p.digest !== hash(canonicalJson(p.delivery ? { plan: p.plan, delivery: p.delivery } : p.plan)))
34483
+ if (p.epoch !== this.o.owner.lease.registration.epoch || p.digest !== digest2 || p.cwd !== this.contexts.capture(p.model).cwd || p.checkoutRoot !== undefined && p.checkoutRoot !== this.cwd || observed.digest !== p.observation || p.display?.runtime !== runtimeSummary(runtime) || canonicalJson(observed.delivery ?? null) !== canonicalJson(p.delivery ?? null) || p.digest !== hash(canonicalJson(p.delivery ? { plan: p.plan, delivery: p.delivery } : p.plan)))
34378
34484
  throw new ContractError("stale");
34379
34485
  return { source: observed.source, runtime };
34380
34486
  }
@@ -34583,8 +34689,8 @@ class Workflows {
34583
34689
  if (action === "prepare")
34584
34690
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
34585
34691
  if (action === "propose")
34586
- return !!this.files.read(join42(this.root, "proposals", `${id}.json`), RECORD_BYTES3);
34587
- return this.files.directory(join42(this.root, "runs", id));
34692
+ return !!this.files.read(join43(this.root, "proposals", `${id}.json`), RECORD_BYTES3);
34693
+ return this.files.directory(join43(this.root, "runs", id));
34588
34694
  }
34589
34695
  admit(commandId, epoch, r, effect) {
34590
34696
  this.current();
@@ -34608,7 +34714,7 @@ class Workflows {
34608
34714
  checkoutRoot: this.cwd,
34609
34715
  observation: digest2,
34610
34716
  display: {
34611
- runtime: describeWorkerRuntime(runtime2),
34717
+ runtime: runtimeSummary(runtime2),
34612
34718
  model: `${selected2.provider}/${selected2.model} · ${selected2.thinking}`,
34613
34719
  branch: source.branch,
34614
34720
  baseCommit: source.head
@@ -34617,7 +34723,7 @@ class Workflows {
34617
34723
  };
34618
34724
  if (sanitizeData(p, secrets) !== canonicalJson(p))
34619
34725
  throw new ContractError("forbidden");
34620
- const target3 = join42(this.root, "proposals", `${commandId}.json`);
34726
+ const target3 = join43(this.root, "proposals", `${commandId}.json`);
34621
34727
  const previous = this.files.read(target3, RECORD_BYTES3);
34622
34728
  if (previous) {
34623
34729
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -34640,7 +34746,7 @@ class Workflows {
34640
34746
  this.grants.delete(key2);
34641
34747
  if (this.grants.size >= 16)
34642
34748
  throw new ContractError("capacity");
34643
- const grant = randomUUID27(), expiresAt = Date.now() + 120000;
34749
+ const grant = randomUUID28(), expiresAt = Date.now() + 120000;
34644
34750
  effect();
34645
34751
  this.grants.set(grant, {
34646
34752
  commandId,
@@ -34735,8 +34841,8 @@ class Workflows {
34735
34841
  };
34736
34842
  const abort = new AbortController;
34737
34843
  let begin;
34738
- const ready2 = new Promise((resolve15) => {
34739
- begin = resolve15;
34844
+ const ready2 = new Promise((resolve16) => {
34845
+ begin = resolve16;
34740
34846
  });
34741
34847
  const live2 = {
34742
34848
  runtime,
@@ -34782,7 +34888,7 @@ class Workflows {
34782
34888
  throw new ContractError("corrupt-selected");
34783
34889
  live2.file = this.write(this.path(live2.run.id, "state.json"), live2.run, live2.file);
34784
34890
  }
34785
- saveFinal(live2) {
34891
+ saveSettlement(live2) {
34786
34892
  const cause = live2.abort.signal.reason;
34787
34893
  if (live2.abort.signal.aborted && cause?.source)
34788
34894
  live2.run.notice = this.notice(live2.run.notice, `${cause.source}: ${cause.reason} (${live2.run.id})`);
@@ -34801,7 +34907,7 @@ class Workflows {
34801
34907
  assertRunning(live2) {
34802
34908
  this.current();
34803
34909
  this.floor();
34804
- if (live2.abort.signal.aborted || live2.execution.cwd !== this.cwd && (resolveWorkspace(live2.execution.cwd).root !== this.cwd || realpathSync13(live2.execution.cwd) !== live2.execution.cwd))
34910
+ if (live2.abort.signal.aborted || live2.execution.cwd !== this.cwd && (resolveWorkspace(live2.execution.cwd).root !== this.cwd || realpathSync14(live2.execution.cwd) !== live2.execution.cwd))
34805
34911
  throw new ContractError("stale");
34806
34912
  }
34807
34913
  step(live2, id, kind, childRunId) {
@@ -34825,7 +34931,7 @@ class Workflows {
34825
34931
  live2.run.stepsBefore = offset + prefix.length;
34826
34932
  }
34827
34933
  const s = {
34828
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID27()}`,
34934
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID28()}`,
34829
34935
  ...childRunId ? { childRunId } : {},
34830
34936
  kind,
34831
34937
  ...childRunId ? {
@@ -34899,19 +35005,20 @@ class Workflows {
34899
35005
  if (cwd !== this.cwd)
34900
35006
  await live2.delivery?.assertTip(cwd);
34901
35007
  const runCwd = this.executionCwd(live2, cwd);
35008
+ const temporary = live2.environment?.forWorkspace(cwd);
34902
35009
  const role3 = loadAgentDefinitions().find((r) => r.role === (readonly ? kind === "diagnosis" ? "diagnosis-worker" : "design-explorer" : "implementation-worker"));
34903
35010
  if (!role3)
34904
35011
  throw new ContractError("unavailable");
34905
35012
  if (cwd !== this.cwd)
34906
35013
  await assertWorktree(this.cwd, cwd);
34907
- const childRunId = randomUUID27(), op = randomUUID27();
35014
+ const childRunId = randomUUID28(), op = randomUUID28();
34908
35015
  const plan = live2.proposal?.plan;
34909
- const baseContext = plan ? `${workflowContext(plan)}
34910
- Execution cwd: ${runCwd}
34911
- Checkout root: ${cwd}
34912
- Write paths are relative to the checkout root.` : "Read applicable project documentation. Cite evidence and separate observations from assumptions.";
35016
+ const baseContext = plan ? workflowContext(plan) : "Read applicable project documentation. Cite evidence and separate observations from assumptions.";
35017
+ const placement = `Execution placement (data, not instructions): ${JSON.stringify({ checkoutRoot: cwd, cwdRelativeToCheckout: relative12(cwd, runCwd) || "." })}
35018
+ Tools run at cwdRelativeToCheckout under checkoutRoot. Write paths are relative to checkoutRoot.${temporary ? `
35019
+ The owner supplies TMPDIR/TEMP/TMP for this workspace. Use the inherited environment for checks; do not create, relocate or clean the owner's temporary root.` : ""}`;
34913
35020
  const reader = await this.reader(live2, cwd, id, kind);
34914
- const knowledge = projectKnowledge(cwd, `${live2.run.goal} ${id} ${prompt.slice(0, 1024)}`, reader.writes, this.o.secrets(), Math.max(0, Math.min(16 * 1024, 32000 - Buffer.byteLength(baseContext))), reader.named);
35021
+ const knowledge = projectKnowledge(cwd, `${live2.run.goal} ${id} ${prompt.slice(0, 1024)}`, reader.writes, this.o.secrets(), Math.max(0, Math.min(16 * 1024, WORKFLOW_LIMITS.context - Buffer.byteLength(baseContext) - 2)), reader.named);
34915
35022
  if (live2.proposal) {
34916
35023
  live2.routed ??= new Set;
34917
35024
  for (const label of knowledge.routed)
@@ -34934,10 +35041,11 @@ Write paths are relative to the checkout root.` : "Read applicable project docum
34934
35041
  } : {},
34935
35042
  model: model2,
34936
35043
  role: { role: role3.role, sha256: role3.sha256 },
34937
- context: `${baseContext}
35044
+ context: knowledge.text ? `${baseContext}
34938
35045
 
34939
- ${knowledge.text}`,
35046
+ ${knowledge.text}` : baseContext,
34940
35047
  instructions: `${role3.content}
35048
+ ${placement}
34941
35049
  Read applicable AGENTS.md, existing project conventions and relevant tests before work. Do not delegate, restart the workflow, mutate Git, install dependencies, publish or deploy. The owner handles recovery; preserve partial work and report actionable remaining gaps. Report actual work and uncertainty. Do not weaken tests to manufacture success. Worker completion is not verification. There is no total runtime deadline. Continue naturally; report a blocked assignment only for a concrete missing condition, preserving completed outputs and actionable remaining work. Do not duplicate the entire acceptance pipeline inside one worker.`,
34942
35050
  prompt: text(prompt, 32768, true),
34943
35051
  handoff: { graphRevision: 1, inputs: [] }
@@ -34981,6 +35089,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
34981
35089
  this.write(this.path(live2.run.id, `launches/${childRunId}.json`), {
34982
35090
  cwd: runCwd,
34983
35091
  runtime: live2.runtime ? describeWorkerRuntime(live2.runtime) : null,
35092
+ environment: temporary ?? null,
34984
35093
  knowledge: {
34985
35094
  sources: knowledge.sources.map(({ excerpt: _excerpt, ...source }) => source),
34986
35095
  omitted: knowledge.omitted
@@ -35006,7 +35115,8 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
35006
35115
  ]);
35007
35116
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, runCwd, live2.abort.signal, {
35008
35117
  ownerSecrets: this.o.secrets(),
35009
- roots: roots2?.length ? roots2.map((p) => resolve14(runCwd, p)) : [kind === "research" ? runCwd : cwd],
35118
+ temporaryDirectory: live2.environment?.forWorkspace(cwd).TMPDIR,
35119
+ roots: roots2?.length ? roots2.map((p) => resolve15(runCwd, p)) : [kind === "research" ? runCwd : cwd],
35010
35120
  onLifecycle: (event) => {
35011
35121
  if (!step.timing)
35012
35122
  return;
@@ -35126,14 +35236,16 @@ Partial work is preserved.`);
35126
35236
  if (cwd !== this.cwd && shell)
35127
35237
  await assertWorktree(this.cwd, cwd);
35128
35238
  const runCwd = shell ? this.executionCwd(live2, cwd) : cwd;
35129
- const id = randomUUID27();
35239
+ const id = randomUUID28();
35130
35240
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
35131
35241
  cwd: runCwd,
35132
35242
  args: shell ? operation.check : operation.git
35133
35243
  });
35134
35244
  let native;
35245
+ const temporary = options.temporary ?? live2.environment?.forWorkspace(cwd);
35135
35246
  const environment2 = {
35136
35247
  ...this.o.checkEnvironment ?? {},
35248
+ ...temporary,
35137
35249
  CADENCE_SUBAGENT_CHILD: "1"
35138
35250
  };
35139
35251
  const running = Promise.resolve().then(() => runProcess({
@@ -35141,7 +35253,7 @@ Partial work is preserved.`);
35141
35253
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
35142
35254
  "--no-lazy-fetch",
35143
35255
  "-c",
35144
- `core.hooksPath=${join42(this.root, "empty-hooks")}`,
35256
+ `core.hooksPath=${join43(this.root, "empty-hooks")}`,
35145
35257
  "-c",
35146
35258
  "commit.gpgsign=false",
35147
35259
  "-c",
@@ -35152,7 +35264,7 @@ Partial work is preserved.`);
35152
35264
  ]),
35153
35265
  windowsVerbatimArguments: shell && process.platform === "win32" ? true : undefined,
35154
35266
  cwd: runCwd,
35155
- env: shell ? environment2 : gitEnvironment(),
35267
+ env: shell ? environment2 : { ...gitEnvironment(), ...temporary },
35156
35268
  retainOutput: true,
35157
35269
  stopTarget: id,
35158
35270
  signal: options.uninterruptible ? new AbortController().signal : live2.abort.signal,
@@ -35193,7 +35305,8 @@ Partial work is preserved.`);
35193
35305
  const step = this.step(live2, title, "check");
35194
35306
  try {
35195
35307
  const runCwd = this.executionCwd(live2, cwd);
35196
- const result = await this.run(live2, cwd, { check: c });
35308
+ const temporary = live2.environment?.forWorkspace(cwd);
35309
+ const result = await this.run(live2, cwd, { check: c }, { temporary });
35197
35310
  this.finishStep(live2, step, result, result.outcome === "completed" ? undefined : `${c.name} in ${runCwd}
35198
35311
  Command: ${c.command}
35199
35312
  ${result.output || result.text}`, undefined, {
@@ -35204,9 +35317,9 @@ ${result.output || result.text}`, undefined, {
35204
35317
  target: live2.run.delivery?.binding.target ?? null,
35205
35318
  environment: Object.fromEntries(["TMPDIR", "TEMP", "TMP"].map((name) => [
35206
35319
  name,
35207
- this.o.checkEnvironment?.[name] ?? null
35320
+ temporary?.[name] ?? this.o.checkEnvironment?.[name] ?? null
35208
35321
  ])),
35209
- environmentPolicy: "Frozen owner check environment; command-local exports do not persist. Null means unset at launch, not a failed prerequisite. Resources or markers not declared by the approved commands are not prerequisites. Never inspect private state or the owner's process environment to reconstruct context."
35322
+ environmentPolicy: "Frozen owner check environment with the run's workspace-specific temporary directory. Command-local exports do not persist. Null means unset in a retained launch, not a failed prerequisite. The owner prepares and retains temporary roots; workers must not recreate, relocate or clean them or invent a marker requirement. Never inspect private state or the owner's process environment to reconstruct context."
35210
35323
  });
35211
35324
  return { result, step };
35212
35325
  } finally {
@@ -35273,7 +35386,14 @@ ${step.text}` : ""}`, step?.id);
35273
35386
  for (const c of p.plan.setup.filter((c2) => (c2.placement ?? "worktree") === placement)) {
35274
35387
  if (placement === "target") {
35275
35388
  const { result, step } = await this.check(live2, cwd, c, `setup: ${c.name}`);
35276
- this.success(result, step);
35389
+ try {
35390
+ this.success(result, step);
35391
+ } catch (error) {
35392
+ if (!(error instanceof WorkflowFailure))
35393
+ throw error;
35394
+ throw new WorkflowFailure(error.outcome, `Target preflight did not pass: ${c.name}. Implementation has not started; no task worktree was created. No repair was dispatched into the original checkout.
35395
+ ${error.message}`, step?.id);
35396
+ }
35277
35397
  continue;
35278
35398
  }
35279
35399
  await this.recoverStage(live2, cwd, p, `setup: ${c.name}`, async () => {
@@ -35439,7 +35559,7 @@ ${IMPLEMENTATION_REPORT}`, false, version, undefined, kind);
35439
35559
  return this.recordedInvestigation(id) !== null;
35440
35560
  }
35441
35561
  investigationPath(id) {
35442
- return join42(this.root, "investigations", `${decodeId(id)}.json`);
35562
+ return join43(this.root, "investigations", `${decodeId(id)}.json`);
35443
35563
  }
35444
35564
  recordedInvestigation(id) {
35445
35565
  try {
@@ -35497,7 +35617,7 @@ This recorded investigation is out of date: ${changed.slice(0, 8).join(", ")}${c
35497
35617
  ${moved}${record3.answer}`;
35498
35618
  }
35499
35619
  questionPath(question, roots2) {
35500
- return join42(this.root, "investigations", "questions", `${questionKey(question, roots2)}.json`);
35620
+ return join43(this.root, "investigations", "questions", `${questionKey(question, roots2)}.json`);
35501
35621
  }
35502
35622
  answered(question, roots2) {
35503
35623
  try {
@@ -35551,7 +35671,7 @@ ${diagnosticText(lines.join(`
35551
35671
  async review(live2, cwd, p, checks) {
35552
35672
  live2.run.phase = "reviewing";
35553
35673
  this.save(live2);
35554
- const { result, step } = await this.worker(live2, cwd, `review-${randomUUID27()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. When the fixed-revision changes tool is available, inspect the changed paths, base/deleted content and candidate diff; continue evidence cursors instead of treating previews as complete. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
35674
+ const { result, step } = await this.worker(live2, cwd, `review-${randomUUID28()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. When the fixed-revision changes tool is available, inspect the changed paths, base/deleted content and candidate diff; continue evidence cursors instead of treating previews as complete. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
35555
35675
  Acceptance checks below ran on this candidate after implementation/repair and before this review. Use their native facts as execution evidence; worker reports are not checks. Future publication/integration checks remain the owner's obligation, not missing evidence for this code review. Failed or incomplete checks never count as passing.
35556
35676
  Files: ${this.scope(live2, p).join(", ")}${this.deviationBrief(live2, "review")}${live2.knowledgeDone && live2.managed ? `
35557
35677
  This candidate also maintains the project's knowledge store (${KNOWLEDGE_SCOPE.join(", ")}). Judge those edits too: an added entry must be short, specific and anchored to code or tests that exist; a removed or rewritten entry must have been stale, duplicated, guaranteed by a test, or shortened without losing a condition; nothing may restate what the code says plainly.` : ""}
@@ -35798,7 +35918,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35798
35918
  if (head)
35799
35919
  await assertCandidate(cwd, head);
35800
35920
  if (checked2 && verdict === "approved") {
35801
- const id = randomUUID27(), steps = [...checks.map((s) => s.id), review.id];
35921
+ const id = randomUUID28(), steps = [...checks.map((s) => s.id), review.id];
35802
35922
  this.write(this.path(live2.run.id, `verification/${id}.json`), {
35803
35923
  id,
35804
35924
  agreement: p.digest,
@@ -35860,7 +35980,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35860
35980
  }
35861
35981
  knowledgeTurn(live2, lint) {
35862
35982
  const topics = lint.usage.topics.map((t) => t.path);
35863
- const path = join42(this.root, "knowledge-use.json");
35983
+ const path = join43(this.root, "knowledge-use.json");
35864
35984
  try {
35865
35985
  const file = this.files.read(path, RECORD_BYTES3);
35866
35986
  const next = advanceKnowledgeUse(file ? decodeKnowledgeUse(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3)) : null, { routes: lint.routes, topics }, live2.routed ?? []);
@@ -36131,8 +36251,8 @@ ${result.output}`}`);
36131
36251
  break;
36132
36252
  await Promise.race([
36133
36253
  ...running.values(),
36134
- new Promise((resolve15) => {
36135
- revised = resolve15;
36254
+ new Promise((resolve16) => {
36255
+ revised = resolve16;
36136
36256
  })
36137
36257
  ]);
36138
36258
  }
@@ -36385,14 +36505,24 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
36385
36505
  }
36386
36506
  async execute(live2, request3) {
36387
36507
  let failure2 = "";
36508
+ let outcome = "unknown";
36388
36509
  try {
36389
36510
  this.assertRunning(live2);
36390
36511
  live2.barrier = await this.o.gate.acquire(live2.run.id, live2.abort.signal);
36391
36512
  live2.barrier.assertHeld();
36392
36513
  if (live2.run.diagnostics)
36393
36514
  live2.run.diagnostics.acquiredAt = Date.now();
36394
- if (live2.proposal)
36515
+ if (live2.proposal) {
36395
36516
  await this.assertStartable(live2, live2.proposal);
36517
+ let environmentFile;
36518
+ live2.environment = new RunEnvironment(this.o.coordination.stateHome, this.cwd, (directories) => {
36519
+ environmentFile = this.write(this.path(live2.run.id, "environment.json"), { directories }, environmentFile);
36520
+ }, () => {
36521
+ this.o.owner.lease.assert();
36522
+ if (this.o.owner.state !== "idle" || live2.abort.signal.aborted)
36523
+ throw new ContractError("unavailable");
36524
+ });
36525
+ }
36396
36526
  if (live2.run.delivery)
36397
36527
  live2.delivery = new WorkflowDelivery(live2.run.delivery, new RepositoryCoordination(this.o.coordination, this.cwd, live2.run.epoch, live2.run.id, () => this.o.owner.lease.assert(), () => this.o.owner.quarantine()), () => this.save(live2));
36398
36528
  live2.run.status = "running";
@@ -36407,32 +36537,60 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
36407
36537
  throw new WorkflowFailure("unknown", "Original operation or cleanup settlement is unknown; delivery is not reported as completed.");
36408
36538
  if (live2.abort.signal.aborted)
36409
36539
  throw new WorkflowFailure("canceled", "Cancellation requested before delivery settled.");
36410
- live2.run.status = "completed";
36411
- const deviations = live2.run.deviations ?? [];
36412
- if (deviations.length)
36413
- live2.run.notice = this.notice(`Delivered with ${deviations.length} recorded deviation${deviations.length === 1 ? "" : "s"} from the agreement, each confirmed by the automatic review:`, deviations.map((d) => `${d.item} → ${d.delivered}`).join(`
36414
- `));
36540
+ outcome = "completed";
36415
36541
  } catch (error) {
36416
- live2.run.status = this.o.owner.state === "quarantined" ? "unknown" : live2.abort.signal.aborted ? "canceled" : error instanceof WorkflowFailure && error.outcome !== "completed" ? error.outcome : "failed";
36542
+ outcome = this.o.owner.state === "quarantined" ? "unknown" : live2.abort.signal.aborted ? "canceled" : error instanceof WorkflowFailure && error.outcome !== "completed" ? error.outcome : "failed";
36417
36543
  failure2 = this.describe(error);
36418
36544
  } finally {
36419
- live2.run.phase = "finished";
36420
- if (live2.run.diagnostics)
36421
- live2.run.diagnostics.settledAt = Date.now();
36422
36545
  if (live2.delivery && this.o.owner.state === "idle") {
36423
36546
  try {
36424
36547
  live2.delivery.finish();
36425
36548
  } catch {
36426
36549
  this.o.owner.quarantine();
36427
- live2.run.status = "unknown";
36550
+ outcome = "unknown";
36551
+ }
36552
+ }
36553
+ let resources = "";
36554
+ if (live2.environment) {
36555
+ live2.run.notice = this.notice("Finalizing the run's temporary resources; the outcome is not yet settled.", failure2);
36556
+ try {
36557
+ this.saveSettlement(live2);
36558
+ } catch {
36559
+ this.o.owner.quarantine();
36560
+ outcome = "unknown";
36561
+ failure2 = this.notice(failure2, "Workflow settlement could not be recorded; temporary resources are retained.");
36562
+ }
36563
+ try {
36564
+ const retained = await live2.environment.finish(this.o.owner.state === "idle" && outcome === "completed" && !live2.abort.signal.aborted);
36565
+ if (retained.length)
36566
+ resources = `Temporary resource paths retained or unconfirmed: ${retained.join(", ")}`;
36567
+ } catch {
36568
+ this.o.owner.quarantine();
36569
+ outcome = "unknown";
36570
+ resources = "Temporary-resource recording did not settle; remaining directories are retained.";
36428
36571
  }
36429
36572
  }
36573
+ if (this.o.owner.state === "quarantined") {
36574
+ outcome = "unknown";
36575
+ failure2 = this.notice(failure2, "Owner settlement is unconfirmed; delivery is not reported as completed.");
36576
+ } else if (live2.abort.signal.aborted && outcome === "completed") {
36577
+ outcome = "canceled";
36578
+ failure2 = this.notice(failure2, "Cancellation requested before finalization settled; actual delivery is preserved.");
36579
+ }
36580
+ live2.run.status = outcome;
36581
+ live2.run.phase = "finished";
36582
+ if (live2.run.diagnostics)
36583
+ live2.run.diagnostics.settledAt = Date.now();
36584
+ const deviations = outcome === "completed" ? live2.run.deviations ?? [] : [];
36430
36585
  const delivered = [...live2.delivered].sort();
36431
- live2.run.notice = this.notice(failure2, delivered.length ? `${live2.run.status === "completed" ? "Changed files" : "Changed files so far"}: ${delivered.join(", ")}` : "", ...live2.notes);
36586
+ live2.run.notice = this.notice(deviations.length ? `Delivered with ${deviations.length} recorded deviation${deviations.length === 1 ? "" : "s"} from the agreement, each confirmed by the automatic review:
36587
+ ${deviations.map((d) => `${d.item} → ${d.delivered}`).join(`
36588
+ `)}` : "", failure2, delivered.length ? `${outcome === "completed" ? "Changed files" : "Changed files so far"}: ${delivered.join(", ")}` : "", ...live2.notes, resources);
36432
36589
  try {
36433
- this.saveFinal(live2);
36590
+ this.saveSettlement(live2);
36434
36591
  } catch {
36435
36592
  this.o.owner.quarantine();
36593
+ live2.run.status = "unknown";
36436
36594
  }
36437
36595
  if (this.o.owner.state === "idle")
36438
36596
  live2.barrier?.release();
@@ -36468,7 +36626,7 @@ class Workbench {
36468
36626
  });
36469
36627
  this.conversations.assertSettled();
36470
36628
  this.files = new WorkbenchFiles(o.coordination.store.root, [o.coordination.files.namespace, o.agentDir], o.secrets);
36471
- this.projectRoot = join43(o.coordination.files.namespace, "workbench-projects-v1");
36629
+ this.projectRoot = join44(o.coordination.files.namespace, "workbench-projects-v1");
36472
36630
  }
36473
36631
  activityReaderScope() {
36474
36632
  return activityReaderScope(this.o.agentDir, this.o.sessionDir);
@@ -36634,7 +36792,7 @@ class Workbench {
36634
36792
  for (let e = directory2.readSync();e; e = directory2.readSync()) {
36635
36793
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries3.length > 128)
36636
36794
  throw new ContractError("corrupt-selected");
36637
- const saved = files.read(join43(this.projectRoot, e.name));
36795
+ const saved = files.read(join44(this.projectRoot, e.name));
36638
36796
  if (!saved)
36639
36797
  throw new ContractError("corrupt-selected");
36640
36798
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -36730,7 +36888,7 @@ class Workbench {
36730
36888
  if (this.opening.size >= 64)
36731
36889
  throw new ContractError("capacity");
36732
36890
  const path = this.files.directory(request3.path);
36733
- const marker2 = join43(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
36891
+ const marker2 = join44(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
36734
36892
  const files = this.o.coordination.files;
36735
36893
  if (files.read(marker2))
36736
36894
  throw new ContractError("receipt-inconclusive");
@@ -36748,7 +36906,7 @@ class Workbench {
36748
36906
  }
36749
36907
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
36750
36908
  for (const root of [this.o.cwd, opened.path]) {
36751
- const entry = join43(this.projectRoot, `${hash(root)}.json`);
36909
+ const entry = join44(this.projectRoot, `${hash(root)}.json`);
36752
36910
  const saved = files.read(entry);
36753
36911
  if (!saved)
36754
36912
  files.create(entry, canonicalJson({ path: root }));
@@ -36778,7 +36936,7 @@ async function predecessorExited() {
36778
36936
  } catch {
36779
36937
  return;
36780
36938
  }
36781
- await new Promise((resolve15) => setTimeout(resolve15, 100));
36939
+ await new Promise((resolve16) => setTimeout(resolve16, 100));
36782
36940
  }
36783
36941
  }
36784
36942
  async function healBeforeStart(c) {
@@ -36816,8 +36974,8 @@ function legacy(store, budget, reader) {
36816
36974
  decodeId(entry.name);
36817
36975
  if (created.has(entry.name))
36818
36976
  continue;
36819
- const path = join44(store.tasks, entry.name, "task.json");
36820
- const size3 = lstatSync27(path).size;
36977
+ const path = join45(store.tasks, entry.name, "task.json");
36978
+ const size3 = lstatSync28(path).size;
36821
36979
  if (size3 > 128 * 1024)
36822
36980
  throw new ContractError("corrupt-selected");
36823
36981
  budget.reserve(size3);
@@ -36870,7 +37028,7 @@ var processLifetime = {
36870
37028
  }
36871
37029
  };
36872
37030
  async function createServiceHost(value, sourceBuild, lifetime) {
36873
- const embedded = "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245";
37031
+ const embedded = "63f28a34411aedbf5d88f62ce81cfb0eca9e8ed38396e731a2a01253d1287f48";
36874
37032
  if (embedded && sourceBuild)
36875
37033
  throw new ContractError("unsupported-context");
36876
37034
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -36952,8 +37110,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
36952
37110
  let timer;
36953
37111
  await Promise.race([
36954
37112
  owner?.idle(),
36955
- new Promise((resolve15) => {
36956
- timer = setTimeout(resolve15, FAULT_SETTLE_MS);
37113
+ new Promise((resolve16) => {
37114
+ timer = setTimeout(resolve16, FAULT_SETTLE_MS);
36957
37115
  })
36958
37116
  ]);
36959
37117
  clearTimeout(timer);