@abelxiaoxing/cadence 2.1.4 → 2.1.5

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.
@@ -17844,8 +17844,8 @@ Content-Length: 0\r
17844
17844
 
17845
17845
  // src/service/host.ts
17846
17846
  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";
17847
+ import { lstatSync as lstatSync28, opendirSync as opendirSync18 } from "node:fs";
17848
+ import { join as join45 } from "node:path";
17849
17849
  import { fileURLToPath as fileURLToPath8 } from "node:url";
17850
17850
 
17851
17851
  // src/agent-registry.ts
@@ -27248,12 +27248,149 @@ async function healHistory(lease, log) {
27248
27248
 
27249
27249
  // src/subagent-process.ts
27250
27250
  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";
27251
+ import { createHash as createHash28, randomUUID as randomUUID22 } from "node:crypto";
27252
+ import { join as join36 } from "node:path";
27253
27253
  import { StringDecoder } from "node:string_decoder";
27254
27254
  import { fileURLToPath as fileURLToPath6 } from "node:url";
27255
+ // src/service/run-environment.ts
27256
+ import { spawnSync as spawnSync5 } from "node:child_process";
27257
+ import { randomUUID as randomUUID20 } from "node:crypto";
27258
+ import {
27259
+ accessSync as accessSync2,
27260
+ constants as constants9,
27261
+ lstatSync as lstatSync20,
27262
+ mkdirSync as mkdirSync5,
27263
+ realpathSync as realpathSync11,
27264
+ statfsSync as statfsSync2,
27265
+ statSync as statSync3
27266
+ } from "node:fs";
27267
+ import { rm } from "node:fs/promises";
27268
+ import { isAbsolute as isAbsolute14, join as join35, relative as relative8, resolve as resolve12, sep as sep7 } from "node:path";
27269
+ var RUN_TEMP_DIRECTORY = "cadence-tmp-v1";
27270
+ 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.`;
27271
+ function temporaryEnvironment(path) {
27272
+ return Object.freeze({ TMPDIR: path, TEMP: path, TMP: path });
27273
+ }
27274
+ var within = (root, path) => {
27275
+ const tail = relative8(root, path);
27276
+ return !tail || !isAbsolute14(tail) && tail !== ".." && !tail.startsWith(`..${sep7}`);
27277
+ };
27278
+ function outsideGit(path) {
27279
+ const result = spawnSync5("git", gitArguments(["rev-parse", "--absolute-git-dir"]), {
27280
+ cwd: path,
27281
+ env: gitEnvironment(),
27282
+ encoding: "utf8",
27283
+ timeout: 5000,
27284
+ maxBuffer: 4096,
27285
+ windowsHide: true
27286
+ });
27287
+ if (result.error || result.signal || result.status !== 128 || !result.stderr.includes("not a git repository"))
27288
+ throw new Error("location is inside Git or Git could not establish that it is outside");
27289
+ }
27290
+ function assertTemporaryDirectory(root, path, privateMode2 = true) {
27291
+ const entry = lstatSync20(path);
27292
+ if (!entry.isDirectory() || entry.isSymbolicLink() || realpathSync11(path) !== path)
27293
+ throw new Error("temporary location must be a real canonical directory");
27294
+ if (privateMode2 && process.platform !== "win32" && ((entry.mode & 511) !== 448 || entry.uid !== process.getuid?.()))
27295
+ throw new Error("temporary directory must be private (0700) and owned by this account");
27296
+ if (entry.dev !== statSync3(root).dev || statfsSync2(path).type === 16914836)
27297
+ throw new Error("temporary location must be on the workspace's disk, not tmpfs");
27298
+ if (within(realpathSync11(root), path))
27299
+ throw new Error("temporary location must be outside the execution workspace");
27300
+ outsideGit(path);
27301
+ }
27302
+
27303
+ class RunEnvironment {
27304
+ directories = new Map;
27305
+ stateHome;
27306
+ checkout;
27307
+ record;
27308
+ assertCurrent;
27309
+ constructor(stateHome, checkout, record3, assertCurrent) {
27310
+ this.stateHome = stateHome;
27311
+ this.checkout = checkout;
27312
+ this.record = record3;
27313
+ this.assertCurrent = assertCurrent;
27314
+ }
27315
+ save() {
27316
+ this.record([...this.directories.values()].map((d) => ({ ...d })));
27317
+ }
27318
+ assertOwned(d) {
27319
+ this.assertCurrent();
27320
+ const entry = lstatSync20(d.path);
27321
+ 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))
27322
+ throw new Error("owned temporary directory changed; it was not recreated or adopted");
27323
+ }
27324
+ forWorkspace(workspace) {
27325
+ this.assertCurrent();
27326
+ const cwd = realpathSync11(workspace);
27327
+ const previous = this.directories.get(cwd);
27328
+ if (previous) {
27329
+ this.assertOwned(previous);
27330
+ assertTemporaryDirectory(cwd, previous.path);
27331
+ return temporaryEnvironment(previous.path);
27332
+ }
27333
+ const home = resolve12(this.stateHome);
27334
+ const parent = join35(home, RUN_TEMP_DIRECTORY);
27335
+ try {
27336
+ if (within(this.checkout, home))
27337
+ throw new Error("state home is inside the checkout");
27338
+ assertTemporaryDirectory(cwd, home, false);
27339
+ accessSync2(home, constants9.W_OK | constants9.X_OK);
27340
+ } catch (error) {
27341
+ throw new Error(`Execution environment unavailable: centralized temporary directory ${parent} is unavailable; no fallback location was created. ${error instanceof Error ? error.message : "unavailable"}`);
27342
+ }
27343
+ const directory2 = {
27344
+ workspace: cwd,
27345
+ path: join35(parent, `cadence-run-${randomUUID20()}`),
27346
+ identity: null,
27347
+ removed: false
27348
+ };
27349
+ this.directories.set(cwd, directory2);
27350
+ this.save();
27351
+ this.assertCurrent();
27352
+ try {
27353
+ try {
27354
+ mkdirSync5(parent, { mode: 448 });
27355
+ } catch (error) {
27356
+ if (!(error instanceof Error && ("code" in error) && error.code === "EEXIST"))
27357
+ throw error;
27358
+ }
27359
+ assertTemporaryDirectory(cwd, parent);
27360
+ mkdirSync5(directory2.path, { mode: 448 });
27361
+ const entry = lstatSync20(directory2.path);
27362
+ directory2.identity = {
27363
+ dev: entry.dev,
27364
+ ino: entry.ino,
27365
+ birthtimeMs: entry.birthtimeMs
27366
+ };
27367
+ this.assertOwned(directory2);
27368
+ assertTemporaryDirectory(cwd, directory2.path);
27369
+ } catch (error) {
27370
+ throw new Error(`Execution environment unavailable: could not prepare ${directory2.path}; nothing was replayed. ${error instanceof Error ? error.message : "unavailable"}`);
27371
+ }
27372
+ this.save();
27373
+ return temporaryEnvironment(directory2.path);
27374
+ }
27375
+ async finish(remove) {
27376
+ for (const directory2 of this.directories.values()) {
27377
+ if (!remove || directory2.removed || !directory2.identity)
27378
+ continue;
27379
+ try {
27380
+ this.assertOwned(directory2);
27381
+ await rm(directory2.path, { recursive: true, force: false });
27382
+ } catch {
27383
+ continue;
27384
+ }
27385
+ directory2.removed = true;
27386
+ this.save();
27387
+ }
27388
+ return [...this.directories.values()].filter((d) => !d.removed).map((d) => d.path);
27389
+ }
27390
+ }
27391
+
27255
27392
  // src/worker-capture.mjs
27256
- import { createHash as createHash27, randomUUID as randomUUID20 } from "node:crypto";
27393
+ import { createHash as createHash27, randomUUID as randomUUID21 } from "node:crypto";
27257
27394
  var completeCoverage = () => ({
27258
27395
  observed: "complete",
27259
27396
  source: "complete",
@@ -27823,11 +27960,11 @@ class WorkerRecording {
27823
27960
  try {
27824
27961
  await Promise.race([
27825
27962
  ...this.pending,
27826
- new Promise((resolve12) => {
27827
- abort = resolve12;
27963
+ new Promise((resolve13) => {
27964
+ abort = resolve13;
27828
27965
  signal.addEventListener("abort", abort, { once: true });
27829
27966
  if (signal.aborted)
27830
- resolve12();
27967
+ resolve13();
27831
27968
  })
27832
27969
  ]);
27833
27970
  } finally {
@@ -27878,7 +28015,7 @@ class WorkerRecording {
27878
28015
  // src/subagent-process.ts
27879
28016
  function terminateWindowsTree(pid, fallback) {
27880
28017
  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 });
28018
+ const taskkill = spawn5(root ? join36(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
27882
28019
  taskkill.once("error", fallback);
27883
28020
  taskkill.once("close", (code2) => {
27884
28021
  if (code2 !== 0)
@@ -27917,7 +28054,7 @@ function runProcess(spec) {
27917
28054
  if (spec.input !== undefined && Buffer.byteLength(spec.input) > 128 * 1024)
27918
28055
  return Promise.resolve(early("failed", "Worker input exceeds bound"));
27919
28056
  const ipc = !!(spec.onCoordinator || spec.onAuth || spec.inputs);
27920
- return new Promise((resolve12) => {
28057
+ return new Promise((resolve13) => {
27921
28058
  const child2 = spawn5(spec.command, spec.args, {
27922
28059
  cwd: spec.cwd,
27923
28060
  env: spec.env ?? safeChildEnv(),
@@ -28034,7 +28171,7 @@ function runProcess(spec) {
28034
28171
  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
28172
  const safeOutput = clean(output, Number.MAX_SAFE_INTEGER);
28036
28173
  const outputBytes2 = spec.retainOutput ? 256 * 1024 : 65536;
28037
- resolve12({
28174
+ resolve13({
28038
28175
  ...stopCause ? { stop: stopCause } : {},
28039
28176
  outcome,
28040
28177
  closed: closed2,
@@ -28422,7 +28559,7 @@ function encodeEnvelope(material, captured, roots = [material.cwd]) {
28422
28559
  throw new Error("network");
28423
28560
  return { material, investigation, ambient, scoped, selected: selected2, secrets, input };
28424
28561
  }
28425
- function launchEncoded(encoded2, signal, extra = {}) {
28562
+ function launchEncoded(encoded2, signal, extra = {}, temporaryDirectory) {
28426
28563
  if (!sameNetwork(encoded2.ambient, networkSnapshot(process.env)) || !sameNetwork(encoded2.scoped, scopedNetwork(encoded2.material)))
28427
28564
  throw new Error("network");
28428
28565
  return runProcess({
@@ -28430,7 +28567,7 @@ function launchEncoded(encoded2, signal, extra = {}) {
28430
28567
  args: [fileURLToPath6(new URL("./sdk-worker.mjs", import.meta.url))],
28431
28568
  cwd: encoded2.material.cwd,
28432
28569
  input: encoded2.input,
28433
- env: encoded2.selected.env,
28570
+ env: temporaryDirectory ? { ...encoded2.selected.env, ...temporaryEnvironment(temporaryDirectory) } : encoded2.selected.env,
28434
28571
  protocol: true,
28435
28572
  childRunId: encoded2.material.request.childRunId,
28436
28573
  expectedRequest: encoded2.material.request,
@@ -28515,7 +28652,7 @@ function launchWorkflowWorker(prepared, cwd, signal, options) {
28515
28652
  onLifecycle: options.onLifecycle,
28516
28653
  onNative: (native, capture) => options.onNative(native, capture?.selected?.messageId),
28517
28654
  onFrame: (frame) => options.onFrame(frame, secrets)
28518
- });
28655
+ }, options.temporaryDirectory);
28519
28656
  });
28520
28657
  }
28521
28658
 
@@ -28620,7 +28757,7 @@ class CheckoutGate {
28620
28757
  throw new ContractError("conflict");
28621
28758
  if (this.waiting.length >= CHECKOUT_WAITERS)
28622
28759
  throw new ContractError("capacity");
28623
- const result = new Promise((resolve12, reject) => {
28760
+ const result = new Promise((resolve13, reject) => {
28624
28761
  const abort = () => {
28625
28762
  const at2 = this.waiting.indexOf(waiter);
28626
28763
  if (at2 >= 0)
@@ -28630,7 +28767,7 @@ class CheckoutGate {
28630
28767
  id,
28631
28768
  resolve: (permit) => {
28632
28769
  signal.removeEventListener("abort", abort);
28633
- resolve12(permit);
28770
+ resolve13(permit);
28634
28771
  },
28635
28772
  reject: (error) => {
28636
28773
  signal.removeEventListener("abort", abort);
@@ -28678,14 +28815,14 @@ class CheckoutGate {
28678
28815
  }
28679
28816
 
28680
28817
  // src/service/model-choice.ts
28681
- import { randomUUID as randomUUID22 } from "node:crypto";
28818
+ import { randomUUID as randomUUID23 } from "node:crypto";
28682
28819
  var choiceOwners = new WeakSet;
28683
28820
 
28684
28821
  class OwnerModelChoice {
28685
28822
  options;
28686
28823
  selection = null;
28687
28824
  revision;
28688
- catalogId = randomUUID22();
28825
+ catalogId = randomUUID23();
28689
28826
  installing = false;
28690
28827
  constructor(options) {
28691
28828
  this.options = options;
@@ -28748,7 +28885,7 @@ class OwnerModelChoice {
28748
28885
  if (this.selection?.sourceSelectionId !== selected2.sourceSelectionId) {
28749
28886
  this.selection = selected2;
28750
28887
  ++this.revision;
28751
- this.catalogId = randomUUID22();
28888
+ this.catalogId = randomUUID23();
28752
28889
  this.options.owner.configurationInstalled();
28753
28890
  }
28754
28891
  try {
@@ -28762,7 +28899,7 @@ class OwnerModelChoice {
28762
28899
  }
28763
28900
 
28764
28901
  // src/service/model-context.ts
28765
- import { randomUUID as randomUUID23 } from "node:crypto";
28902
+ import { randomUUID as randomUUID24 } from "node:crypto";
28766
28903
 
28767
28904
  // src/worker-model.mjs
28768
28905
  var WORKER_POLICY = Object.freeze({
@@ -29058,18 +29195,18 @@ function projectModelCatalog(runtime, supportedThinking, current2, literals, val
29058
29195
  }
29059
29196
 
29060
29197
  // 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";
29198
+ import { lstatSync as lstatSync21, realpathSync as realpathSync12 } from "node:fs";
29199
+ import { dirname as dirname20, join as join37 } from "node:path";
29063
29200
  var SETTINGS_FILE_BYTES = 1024 * 1024;
29064
29201
  function observe(path) {
29065
29202
  let target2;
29066
29203
  try {
29067
- target2 = realpathSync11(path);
29204
+ target2 = realpathSync12(path);
29068
29205
  } catch (error) {
29069
29206
  if (error.code !== "ENOENT")
29070
29207
  throw error;
29071
29208
  try {
29072
- lstatSync20(path);
29209
+ lstatSync21(path);
29073
29210
  } catch (missing2) {
29074
29211
  if (missing2.code === "ENOENT")
29075
29212
  return;
@@ -29095,7 +29232,7 @@ function readWorkerRuntime(cwd, agentDir, model2, pi) {
29095
29232
  throw new ContractError("corrupt-selected");
29096
29233
  return body;
29097
29234
  };
29098
- const global = source(join36(agentDir, "settings.json"));
29235
+ const global = source(join37(agentDir, "settings.json"));
29099
29236
  const storage = (project2) => ({
29100
29237
  withLock(scope, use) {
29101
29238
  if (use(scope === "global" ? global : project2) !== undefined)
@@ -29107,10 +29244,10 @@ function readWorkerRuntime(cwd, agentDir, model2, pi) {
29107
29244
  });
29108
29245
  if (user.drainErrors().length)
29109
29246
  throw new ContractError("corrupt-selected");
29110
- const trust = source(join36(agentDir, "trust.json"));
29247
+ const trust = source(join37(agentDir, "trust.json"));
29111
29248
  const decision = trust === undefined ? null : new pi.ProjectTrustStore(agentDir).get(cwd);
29112
29249
  const projectTrusted = decision ?? user.getDefaultProjectTrust() === "always";
29113
- const project = projectTrusted ? source(join36(cwd, ".pi", "settings.json")) : undefined;
29250
+ const project = projectTrusted ? source(join37(cwd, ".pi", "settings.json")) : undefined;
29114
29251
  const manager = pi.SettingsManager.fromStorage(storage(project), {
29115
29252
  projectTrusted
29116
29253
  });
@@ -29300,7 +29437,7 @@ class OwnerModelContext {
29300
29437
  const current2 = this.catalogSource();
29301
29438
  const validated = this.validateModel(selector, current2);
29302
29439
  this.#options.owner.assertQuiescent();
29303
- const selection = { sourceSelectionId: randomUUID23(), ...selector };
29440
+ const selection = { sourceSelectionId: randomUUID24(), ...selector };
29304
29441
  const selected2 = {
29305
29442
  ...validated,
29306
29443
  model: clonePrivate(validated.model),
@@ -29411,7 +29548,7 @@ class OwnerModelContext {
29411
29548
  throw new ContractError("capacity");
29412
29549
  const selector = decodeModelSelector(input);
29413
29550
  const validated = this.validateModel(selector, this.catalogSource());
29414
- const selection = { sourceSelectionId: randomUUID23(), ...selector };
29551
+ const selection = { sourceSelectionId: randomUUID24(), ...selector };
29415
29552
  this.#selected.set(selection.sourceSelectionId, {
29416
29553
  ...validated,
29417
29554
  model: clonePrivate(validated.model),
@@ -29506,10 +29643,10 @@ class OwnerModelContext {
29506
29643
  closed2 = true;
29507
29644
  };
29508
29645
  let reportClosed;
29509
- const closedWait = new Promise((resolve12) => {
29646
+ const closedWait = new Promise((resolve13) => {
29510
29647
  reportClosed = () => {
29511
29648
  close();
29512
- resolve12(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
29649
+ resolve13(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
29513
29650
  };
29514
29651
  });
29515
29652
  input.signal.addEventListener("abort", reportClosed, { once: true });
@@ -29649,7 +29786,7 @@ class OwnerModelContext {
29649
29786
  const next = this.prepareTracked({
29650
29787
  ...input,
29651
29788
  runtime: workerRuntime,
29652
- operationId: randomUUID23()
29789
+ operationId: randomUUID24()
29653
29790
  });
29654
29791
  const result = await next.result;
29655
29792
  await next.settled;
@@ -29962,8 +30099,8 @@ class ServiceOwner {
29962
30099
  if (!this.attempt) {
29963
30100
  this.reportingExpired = false;
29964
30101
  let complete;
29965
- this.attempt = new Promise((resolve12) => {
29966
- complete = resolve12;
30102
+ this.attempt = new Promise((resolve13) => {
30103
+ complete = resolve13;
29967
30104
  });
29968
30105
  const finish = () => {
29969
30106
  this.attempt = undefined;
@@ -29981,11 +30118,11 @@ class ServiceOwner {
29981
30118
  try {
29982
30119
  await Promise.race([
29983
30120
  this.attempt,
29984
- new Promise((resolve12) => {
30121
+ new Promise((resolve13) => {
29985
30122
  timer = setTimeout(() => {
29986
30123
  this.reportingExpired = true;
29987
30124
  this.persistPhase("quarantined");
29988
- resolve12();
30125
+ resolve13();
29989
30126
  }, waitMs);
29990
30127
  })
29991
30128
  ]);
@@ -30016,7 +30153,7 @@ class ServiceOwner {
30016
30153
 
30017
30154
  // src/service/workbench.ts
30018
30155
  import { opendirSync as opendirSync17 } from "node:fs";
30019
- import { join as join43 } from "node:path";
30156
+ import { join as join44 } from "node:path";
30020
30157
 
30021
30158
  // src/service/conversation-images.ts
30022
30159
  var binding = (send2) => {
@@ -30102,17 +30239,17 @@ class ConversationImages {
30102
30239
  }
30103
30240
 
30104
30241
  // src/service/conversation-workflow.ts
30105
- import { randomUUID as randomUUID24 } from "node:crypto";
30106
- import { join as join38 } from "node:path";
30242
+ import { randomUUID as randomUUID25 } from "node:crypto";
30243
+ import { join as join39 } from "node:path";
30107
30244
 
30108
30245
  // src/cadence-instructions.ts
30109
30246
  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
30247
  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
30248
  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.
30249
+ 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
30250
  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
30251
  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.
30252
+ 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
30253
  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
30254
  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
30255
 
@@ -30121,9 +30258,9 @@ import { isUtf8 } from "node:buffer";
30121
30258
  import { createHash as createHash30 } from "node:crypto";
30122
30259
  import {
30123
30260
  closeSync as closeSync11,
30124
- constants as constants10,
30261
+ constants as constants11,
30125
30262
  fstatSync as fstatSync8,
30126
- lstatSync as lstatSync23,
30263
+ lstatSync as lstatSync24,
30127
30264
  opendirSync as opendirSync13,
30128
30265
  openSync as openSync11,
30129
30266
  readSync as readSync7
@@ -30131,26 +30268,26 @@ import {
30131
30268
  import { dirname as dirname23, posix as posix2 } from "node:path";
30132
30269
 
30133
30270
  // src/service/knowledge-store.ts
30134
- import { lstatSync as lstatSync22, opendirSync as opendirSync12, readFileSync as readFileSync6 } from "node:fs";
30271
+ import { lstatSync as lstatSync23, opendirSync as opendirSync12, readFileSync as readFileSync6 } from "node:fs";
30135
30272
  import { dirname as dirname22, posix } from "node:path";
30136
30273
 
30137
30274
  // src/service/workflow-git.ts
30138
- import { spawn as spawn6, spawnSync as spawnSync5 } from "node:child_process";
30275
+ import { spawn as spawn6, spawnSync as spawnSync6 } from "node:child_process";
30139
30276
  import { createHash as createHash29 } from "node:crypto";
30140
30277
  import {
30141
30278
  closeSync as closeSync10,
30142
- constants as constants9,
30279
+ constants as constants10,
30143
30280
  existsSync as existsSync4,
30144
30281
  fstatSync as fstatSync7,
30145
- lstatSync as lstatSync21,
30282
+ lstatSync as lstatSync22,
30146
30283
  openSync as openSync10,
30147
30284
  readdirSync as readdirSync4,
30148
30285
  readlinkSync,
30149
30286
  readSync as readSync6,
30150
- realpathSync as realpathSync12
30287
+ realpathSync as realpathSync13
30151
30288
  } from "node:fs";
30152
30289
  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";
30290
+ import { dirname as dirname21, isAbsolute as isAbsolute15, join as join38, relative as relative9, resolve as resolve13, sep as sep8 } from "node:path";
30154
30291
  var NAMES_BYTES = 64 * 1024 * 1024;
30155
30292
  var SYNC_MS = 30000;
30156
30293
  var READ_MS = 120000;
@@ -30165,7 +30302,7 @@ class WorkflowRefusal extends ContractError {
30165
30302
  }
30166
30303
  }
30167
30304
  function gitRead(cwd, args) {
30168
- const r = spawnSync5("git", gitArguments(args), {
30305
+ const r = spawnSync6("git", gitArguments(args), {
30169
30306
  cwd,
30170
30307
  env: gitEnvironment(),
30171
30308
  encoding: "utf8",
@@ -30178,7 +30315,7 @@ function gitRead(cwd, args) {
30178
30315
  return r.stdout;
30179
30316
  }
30180
30317
  function gitAnswer(cwd, args) {
30181
- const r = spawnSync5("git", gitArguments(args), {
30318
+ const r = spawnSync6("git", gitArguments(args), {
30182
30319
  cwd,
30183
30320
  env: gitEnvironment(),
30184
30321
  encoding: "utf8",
@@ -30234,20 +30371,20 @@ async function gitHead(cwd) {
30234
30371
  return (await gitText(cwd, ["rev-parse", "--verify", "HEAD"])).trim();
30235
30372
  }
30236
30373
  function contains2(root, path) {
30237
- const within = relative8(root, path);
30238
- return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute14(within);
30374
+ const within2 = relative9(root, path);
30375
+ return !within2 || !within2.startsWith(`..${sep8}`) && within2 !== ".." && !isAbsolute15(within2);
30239
30376
  }
30240
30377
  function nested(a, b) {
30241
30378
  return contains2(a, b) || contains2(b, a);
30242
30379
  }
30243
30380
  function safeWorkflowFile(cwd, name) {
30244
30381
  workflowPath(name);
30245
- const p = resolve12(cwd, name);
30246
- if (relative8(cwd, p).startsWith(".."))
30382
+ const p = resolve13(cwd, name);
30383
+ if (relative9(cwd, p).startsWith(".."))
30247
30384
  throw new ContractError("forbidden");
30248
30385
  safeDirectory(dirname21(p));
30249
30386
  try {
30250
- const st = lstatSync21(p);
30387
+ const st = lstatSync22(p);
30251
30388
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
30252
30389
  throw new ContractError("forbidden");
30253
30390
  } catch (e) {
@@ -30258,12 +30395,12 @@ function safeWorkflowFile(cwd, name) {
30258
30395
  }
30259
30396
  function declaredTarget(cwd, name) {
30260
30397
  workflowPath(name);
30261
- const p = resolve12(cwd, name);
30262
- if (relative8(cwd, p).startsWith(".."))
30398
+ const p = resolve13(cwd, name);
30399
+ if (relative9(cwd, p).startsWith(".."))
30263
30400
  throw new ContractError("forbidden");
30264
30401
  safeDirectory(dirname21(p));
30265
30402
  try {
30266
- const st = lstatSync21(p);
30403
+ const st = lstatSync22(p);
30267
30404
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
30268
30405
  throw new ContractError("forbidden");
30269
30406
  } catch (e) {
@@ -30289,7 +30426,7 @@ function fileIdentity(p, st, hashBytes) {
30289
30426
  return quick;
30290
30427
  let fd;
30291
30428
  try {
30292
- fd = openSync10(p, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0));
30429
+ fd = openSync10(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
30293
30430
  } catch (e) {
30294
30431
  if (absent2(e))
30295
30432
  return null;
@@ -30314,7 +30451,7 @@ async function fileIdentityAsync(p, st, hashBytes, signal) {
30314
30451
  return quick;
30315
30452
  let handle;
30316
30453
  try {
30317
- handle = await open2(p, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0) | (constants9.O_NONBLOCK ?? 0));
30454
+ handle = await open2(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0) | (constants10.O_NONBLOCK ?? 0));
30318
30455
  } catch (e) {
30319
30456
  if (absent2(e))
30320
30457
  return null;
@@ -30353,13 +30490,13 @@ function directoryIdentity(root, name) {
30353
30490
  continue;
30354
30491
  if (++count2 > DIRECTORY_ENTRIES)
30355
30492
  throw tooLarge(name);
30356
- const full = join37(directory2, entry), relative9 = `${prefix}${entry}`;
30357
- const st = lstatSync21(full);
30493
+ const full = join38(directory2, entry), relative10 = `${prefix}${entry}`;
30494
+ const st = lstatSync22(full);
30358
30495
  if (st.isDirectory()) {
30359
- rows.push(`${relative9}/`);
30360
- visit(full, `${relative9}/`);
30496
+ rows.push(`${relative10}/`);
30497
+ visit(full, `${relative10}/`);
30361
30498
  } else
30362
- rows.push(`${relative9}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
30499
+ rows.push(`${relative10}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
30363
30500
  }
30364
30501
  };
30365
30502
  visit(root, "");
@@ -30377,13 +30514,13 @@ async function directoryIdentityAsync(root, name, contentOnly = false, signal) {
30377
30514
  continue;
30378
30515
  if (++count2 > DIRECTORY_ENTRIES)
30379
30516
  throw tooLarge(name);
30380
- const full = join37(directory2, entry), relative9 = `${prefix}${entry}`;
30517
+ const full = join38(directory2, entry), relative10 = `${prefix}${entry}`;
30381
30518
  const st = await lstat(full);
30382
30519
  if (st.isDirectory()) {
30383
- rows.push(`${relative9}/`);
30384
- await visit(full, `${relative9}/`);
30520
+ rows.push(`${relative10}/`);
30521
+ await visit(full, `${relative10}/`);
30385
30522
  } else
30386
- rows.push(`${relative9}\x00${await fileIdentityAsync(full, st, contentOnly ? Infinity : DIRECTORY_HASH_BYTES, signal)}`);
30523
+ rows.push(`${relative10}\x00${await fileIdentityAsync(full, st, contentOnly ? Infinity : DIRECTORY_HASH_BYTES, signal)}`);
30387
30524
  }
30388
30525
  };
30389
30526
  await visit(root, "");
@@ -30391,12 +30528,12 @@ async function directoryIdentityAsync(root, name, contentOnly = false, signal) {
30391
30528
  `))}`;
30392
30529
  }
30393
30530
  function pathIdentity(cwd, name, walk = true) {
30394
- const p = resolve12(cwd, name);
30395
- if (relative8(cwd, p).startsWith(".."))
30531
+ const p = resolve13(cwd, name);
30532
+ if (relative9(cwd, p).startsWith(".."))
30396
30533
  throw new ContractError("forbidden");
30397
30534
  let st;
30398
30535
  try {
30399
- st = lstatSync21(p);
30536
+ st = lstatSync22(p);
30400
30537
  } catch (e) {
30401
30538
  if (absent2(e))
30402
30539
  return null;
@@ -30409,8 +30546,8 @@ function pathIdentity(cwd, name, walk = true) {
30409
30546
  async function pathIdentityAsync(cwd, name, contentOnly = false, signal) {
30410
30547
  if (signal?.aborted)
30411
30548
  throw new ContractError("stale");
30412
- const p = resolve12(cwd, name);
30413
- if (relative8(cwd, p).startsWith(".."))
30549
+ const p = resolve13(cwd, name);
30550
+ if (relative9(cwd, p).startsWith(".."))
30414
30551
  throw new ContractError("forbidden");
30415
30552
  let st;
30416
30553
  try {
@@ -30518,8 +30655,8 @@ async function committedPaths(cwd, from, to) {
30518
30655
  ])).sort();
30519
30656
  }
30520
30657
  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);
30658
+ const repository = realpathSync13(resolve13(cwd, gitRead(cwd, ["rev-parse", "--git-common-dir"]).replace(/\r?\n$/u, "")));
30659
+ const st = lstatSync22(repository);
30523
30660
  if (!st.isDirectory())
30524
30661
  throw new ContractError("stale");
30525
30662
  return {
@@ -30540,12 +30677,12 @@ function deliveryTarget(cwd, source) {
30540
30677
  "index.lock",
30541
30678
  "HEAD.lock"
30542
30679
  ]) {
30543
- if (existsSync4(join37(gitDir, name)))
30680
+ if (existsSync4(join38(gitDir, name)))
30544
30681
  throw new WorkflowRefusal("conflict", "Finish the existing Git operation before planning isolated delivery.");
30545
30682
  }
30546
30683
  return {
30547
30684
  ...repositoryIdentity(cwd),
30548
- checkoutRoot: realpathSync12(cwd),
30685
+ checkoutRoot: realpathSync13(cwd),
30549
30686
  head: source.head,
30550
30687
  branch: source.branch
30551
30688
  };
@@ -30666,14 +30803,14 @@ function snapshotChanges(before, after) {
30666
30803
  async function assertWorktree(root, cwd) {
30667
30804
  if (!safeDirectory(cwd))
30668
30805
  throw new ContractError("stale");
30669
- const real = (p) => realpathSync12(resolve12(p));
30806
+ const real = (p) => realpathSync13(resolve13(p));
30670
30807
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
30671
30808
  throw new ContractError("stale");
30672
- const common = async (p) => real(resolve12(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
30809
+ const common = async (p) => real(resolve13(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
30673
30810
  if (await common(root) !== await common(cwd))
30674
30811
  throw new ContractError("stale");
30675
- const marker2 = resolve12(cwd, ".git");
30676
- if (!lstatSync21(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
30812
+ const marker2 = resolve13(cwd, ".git");
30813
+ if (!lstatSync22(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
30677
30814
  throw new ContractError("stale");
30678
30815
  }
30679
30816
 
@@ -30797,7 +30934,7 @@ function readKnowledgeStore(root) {
30797
30934
  let names3 = [];
30798
30935
  try {
30799
30936
  const directory2 = dirname22(safeWorkflowFile(root, `${KNOWLEDGE_STORE.topics}/index.md`));
30800
- if (lstatSync22(directory2).isDirectory()) {
30937
+ if (lstatSync23(directory2).isDirectory()) {
30801
30938
  const dir = opendirSync12(directory2);
30802
30939
  try {
30803
30940
  for (let e = dir.readSync();e; e = dir.readSync()) {
@@ -30844,7 +30981,7 @@ function fileHas(root, path, symbol) {
30844
30981
  return !!file && (symbol === null || file.body.includes(symbol));
30845
30982
  }
30846
30983
  try {
30847
- const stat = lstatSync22(safeWorkflowFile(root, path));
30984
+ const stat = lstatSync23(safeWorkflowFile(root, path));
30848
30985
  if (!stat.isFile() && !stat.isDirectory())
30849
30986
  return false;
30850
30987
  if (symbol === null)
@@ -31074,8 +31211,8 @@ function readKnowledgeFile(root, path) {
31074
31211
  let fd;
31075
31212
  try {
31076
31213
  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));
31214
+ const selected2 = lstatSync24(file);
31215
+ fd = openSync11(file, constants11.O_RDONLY | (constants11.O_NOFOLLOW ?? 0) | (constants11.O_NONBLOCK ?? 0));
31079
31216
  const before = fstatSync8(fd);
31080
31217
  if (selected2.dev !== before.dev || selected2.ino !== before.ino)
31081
31218
  return null;
@@ -31090,7 +31227,7 @@ function readKnowledgeFile(root, path) {
31090
31227
  bytes += n;
31091
31228
  }
31092
31229
  const after = fstatSync8(fd);
31093
- const located = lstatSync23(file);
31230
+ const located = lstatSync24(file);
31094
31231
  if (located.dev !== before.dev || located.ino !== before.ino)
31095
31232
  return null;
31096
31233
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
@@ -31580,7 +31717,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31580
31717
  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
31718
  let published;
31582
31719
  try {
31583
- published = this.o.workflows.command(randomUUID24(), epoch, {
31720
+ published = this.o.workflows.command(randomUUID25(), epoch, {
31584
31721
  action: "propose",
31585
31722
  plan,
31586
31723
  model: model2
@@ -31616,7 +31753,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31616
31753
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
31617
31754
  if (busy.length)
31618
31755
  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;
31756
+ const id = randomUUID25(), conversationId = current2.state.id;
31620
31757
  try {
31621
31758
  this.o.workflows.command(id, epoch, {
31622
31759
  action: "research",
@@ -31644,7 +31781,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31644
31781
  approval(c, caller) {
31645
31782
  if (!caller)
31646
31783
  throw new ContractError("forbidden");
31647
- const evidence = join38(this.records.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
31784
+ const evidence = join39(this.records.root, decodeSessionId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
31648
31785
  let effects = true;
31649
31786
  try {
31650
31787
  effects = this.o.owner.state !== "idle";
@@ -31704,7 +31841,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31704
31841
  });
31705
31842
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
31706
31843
  throw new ContractError("unavailable");
31707
- const g = prepared.response, grant2 = randomUUID24();
31844
+ const g = prepared.response, grant2 = randomUUID25();
31708
31845
  this.grants.set(grant2, {
31709
31846
  caller: canonicalJson(caller),
31710
31847
  revision: c.revision,
@@ -31770,9 +31907,9 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31770
31907
  }
31771
31908
 
31772
31909
  // 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";
31910
+ import { randomUUID as randomUUID26 } from "node:crypto";
31911
+ import { opendirSync as opendirSync14, statfsSync as statfsSync3 } from "node:fs";
31912
+ import { dirname as dirname24, join as join40 } from "node:path";
31776
31913
  var META_BYTES2 = 64 * 1024;
31777
31914
  var PREVIEW_BYTES = 64 * 1024;
31778
31915
  var RECENT_PREVIEWS = 8;
@@ -32010,7 +32147,7 @@ class Conversations {
32010
32147
  }
32011
32148
  assertSettled() {
32012
32149
  this.o.owner.lease.assert();
32013
- const sessions = join39(this.records.root, "sessions");
32150
+ const sessions = join40(this.records.root, "sessions");
32014
32151
  if (!this.files.directory(sessions))
32015
32152
  return;
32016
32153
  const dir = opendirSync14(sessions);
@@ -32081,7 +32218,7 @@ class Conversations {
32081
32218
  throw new ContractError("invalid");
32082
32219
  if (input.images?.length && !this.o.models.catalog().entries.some((m) => m.provider === execution.model?.provider && m.model === execution.model?.model && m.images))
32083
32220
  throw new ContractError("unsupported-context");
32084
- const space = statfsSync2(this.o.coordination.directory);
32221
+ const space = statfsSync3(this.o.coordination.directory);
32085
32222
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
32086
32223
  throw new ContractError("capacity");
32087
32224
  const listed = session ? this.records.sessions.find(input.conversationId) : undefined;
@@ -32098,8 +32235,8 @@ class Conversations {
32098
32235
  const runtime = control?.reply || !execution.model ? undefined : this.o.models.workerSettings(execution.cwd, execution.model);
32099
32236
  const abort = new AbortController;
32100
32237
  let begin;
32101
- const ready2 = new Promise((resolve13) => {
32102
- begin = resolve13;
32238
+ const ready2 = new Promise((resolve14) => {
32239
+ begin = resolve14;
32103
32240
  });
32104
32241
  const live2 = {
32105
32242
  coordinator: !!control,
@@ -32189,7 +32326,7 @@ class Conversations {
32189
32326
  const session = this.records.sessions.session(request3.conversationId);
32190
32327
  if (live2.inputs.length >= RUN_INPUTS || live2.inputs.filter((input2) => !input2.withdrawn && !session?.delivered(input2.commandId)).length >= WAITING_INPUTS)
32191
32328
  throw new ContractError("capacity");
32192
- const space = statfsSync2(this.o.coordination.directory);
32329
+ const space = statfsSync3(this.o.coordination.directory);
32193
32330
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
32194
32331
  throw new ContractError("capacity");
32195
32332
  const index = this.records.index(request3.conversationId);
@@ -32260,14 +32397,14 @@ class Conversations {
32260
32397
  let waiting = input.withdrawal;
32261
32398
  if (!waiting) {
32262
32399
  let answer;
32263
- const result = new Promise((resolve13, reject) => {
32400
+ const result = new Promise((resolve14, reject) => {
32264
32401
  answer = (removed) => {
32265
32402
  input.withdrawal = undefined;
32266
32403
  try {
32267
32404
  if (!removed)
32268
32405
  throw new ContractError("conflict");
32269
32406
  this.withdraw(input);
32270
- resolve13();
32407
+ resolve14();
32271
32408
  } catch (error) {
32272
32409
  reject(error);
32273
32410
  }
@@ -32428,10 +32565,10 @@ class Conversations {
32428
32565
  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
32566
  const request3 = decodeWorkerPublicRequest({
32430
32567
  protocol: 2,
32431
- taskId: randomUUID25(),
32568
+ taskId: randomUUID26(),
32432
32569
  taskKind: control ? "research" : "code",
32433
32570
  runId: commandId,
32434
- childRunId: randomUUID25(),
32571
+ childRunId: randomUUID26(),
32435
32572
  assignmentId: "conversation",
32436
32573
  purpose: control ? "research" : "edit",
32437
32574
  model: selected2,
@@ -32449,7 +32586,7 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
32449
32586
  runtime: live2.runtime,
32450
32587
  request: request3,
32451
32588
  cwd: live2.execution.cwd,
32452
- operationId: randomUUID25(),
32589
+ operationId: randomUUID26(),
32453
32590
  epoch: live2.epoch,
32454
32591
  signal: abort.signal,
32455
32592
  current: current2,
@@ -32589,16 +32726,16 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
32589
32726
  }
32590
32727
 
32591
32728
  // 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";
32729
+ import { randomUUID as randomUUID28 } from "node:crypto";
32730
+ import { opendirSync as opendirSync16, realpathSync as realpathSync14, statfsSync as statfsSync4, writeFileSync as writeFileSync6 } from "node:fs";
32731
+ import { basename as basename5, dirname as dirname26, join as join43, relative as relative12, resolve as resolve15 } from "node:path";
32595
32732
  import { fileURLToPath as fileURLToPath7 } from "node:url";
32596
32733
 
32597
32734
  // src/task-diff.ts
32598
- import { spawnSync as spawnSync6 } from "node:child_process";
32735
+ import { spawnSync as spawnSync7 } from "node:child_process";
32599
32736
  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";
32737
+ import { lstatSync as lstatSync25, readdirSync as readdirSync5, readlinkSync as readlinkSync2 } from "node:fs";
32738
+ import { join as join41, relative as relative10 } from "node:path";
32602
32739
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
32603
32740
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
32604
32741
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -32617,7 +32754,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32617
32754
  if (Date.now() >= deadline)
32618
32755
  outcome = "time budget exhausted";
32619
32756
  else {
32620
- const result = spawnSync6("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
32757
+ const result = spawnSync7("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
32621
32758
  cwd: root,
32622
32759
  encoding: "buffer",
32623
32760
  timeout: Math.max(1, deadline - Date.now()),
@@ -32641,8 +32778,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32641
32778
  return;
32642
32779
  }
32643
32780
  try {
32644
- const path = join40(root, name);
32645
- const st = lstatSync24(path);
32781
+ const path = join41(root, name);
32782
+ const st = lstatSync25(path);
32646
32783
  add(name, `${st.mode}:${st.size}`);
32647
32784
  if (st.isSymbolicLink()) {
32648
32785
  add(name, readlinkSync2(path));
@@ -32667,7 +32804,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32667
32804
  limits.push(`Unreadable/changing: ${name}`);
32668
32805
  }
32669
32806
  };
32670
- const probe2 = spawnSync6("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
32807
+ const probe2 = spawnSync7("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
32671
32808
  cwd: root,
32672
32809
  env: gitEnvironment(),
32673
32810
  timeout: 3000,
@@ -32782,8 +32919,8 @@ ${data2.toString("utf8")}`);
32782
32919
  return;
32783
32920
  }
32784
32921
  for (const name of names3) {
32785
- const path = join40(dir, name);
32786
- const rel = relative9(root, path).split("\\").join("/");
32922
+ const path = join41(dir, name);
32923
+ const rel = relative10(root, path).split("\\").join("/");
32787
32924
  if (rel === ".git" || admin(rel))
32788
32925
  continue;
32789
32926
  if (++fileCount > 2000 || Date.now() >= deadline) {
@@ -32791,7 +32928,7 @@ ${data2.toString("utf8")}`);
32791
32928
  break;
32792
32929
  }
32793
32930
  try {
32794
- const st = lstatSync24(path);
32931
+ const st = lstatSync25(path);
32795
32932
  if (st.isDirectory())
32796
32933
  walk(path, depth + 1);
32797
32934
  else
@@ -32817,15 +32954,15 @@ ${data2.toString("utf8")}`);
32817
32954
  }
32818
32955
 
32819
32956
  // src/worker-workspace.mjs
32820
- import { isAbsolute as isAbsolute15, relative as relative10, resolve as resolve13, sep as sep8 } from "node:path";
32957
+ import { isAbsolute as isAbsolute16, relative as relative11, resolve as resolve14, sep as sep9 } from "node:path";
32821
32958
  function withinRoot(root, path) {
32822
- const part = relative10(root, path);
32823
- return part === "" || !isAbsolute15(part) && part !== ".." && !part.startsWith(`..${sep8}`);
32959
+ const part = relative11(root, path);
32960
+ return part === "" || !isAbsolute16(part) && part !== ".." && !part.startsWith(`..${sep9}`);
32824
32961
  }
32825
32962
  var absolute2 = (value) => {
32826
- if (typeof value !== "string" || !isAbsolute15(value) || value.includes("\x00"))
32963
+ if (typeof value !== "string" || !isAbsolute16(value) || value.includes("\x00"))
32827
32964
  throw new Error("Invalid execution directory");
32828
- return resolve13(value);
32965
+ return resolve14(value);
32829
32966
  };
32830
32967
  function executionDirectory(execution, tree) {
32831
32968
  const origin = absolute2(execution.checkoutRoot);
@@ -32833,12 +32970,12 @@ function executionDirectory(execution, tree) {
32833
32970
  tree = absolute2(tree);
32834
32971
  if (!withinRoot(origin, cwd))
32835
32972
  throw new Error("Execution cwd escaped its checkout");
32836
- return resolve13(tree, relative10(origin, cwd));
32973
+ return resolve14(tree, relative11(origin, cwd));
32837
32974
  }
32838
32975
 
32839
32976
  // src/service/investigations.ts
32840
32977
  import { createHash as createHash32 } from "node:crypto";
32841
- import { readFileSync as readFileSync7, statSync as statSync3 } from "node:fs";
32978
+ import { readFileSync as readFileSync7, statSync as statSync4 } from "node:fs";
32842
32979
  var INVESTIGATIONS = {
32843
32980
  cited: 32,
32844
32981
  examined: 256,
@@ -32850,7 +32987,7 @@ function fileDigest(root, path) {
32850
32987
  if (!workflowBoundary(path))
32851
32988
  return null;
32852
32989
  const file = safeWorkflowFile(root, path);
32853
- const st = statSync3(file);
32990
+ const st = statSync4(file);
32854
32991
  if (!st.isFile() || st.size > INVESTIGATIONS.fileBytes)
32855
32992
  return null;
32856
32993
  return createHash32("sha256").update(readFileSync7(file)).digest("hex");
@@ -32996,7 +33133,7 @@ function decodeRecoveryDecision(reply, bounds, secrets = []) {
32996
33133
  const route = has("route") ? nullable(o.route, (value) => {
32997
33134
  const given = (key2) => Object.hasOwn(value ?? {}, key2);
32998
33135
  const r = closed(value, ["drop", "add"].filter(given));
32999
- const within = [...bounds.route?.scope ?? bounds.scope, ...scope];
33136
+ const within2 = [...bounds.route?.scope ?? bounds.scope, ...scope];
33000
33137
  return {
33001
33138
  drop: given("drop") ? list(r.drop, WORKFLOW_LIMITS.route, (v) => text(v, 64, true)) : [],
33002
33139
  add: given("add") ? list(r.add, WORKFLOW_LIMITS.tasks, (entry) => {
@@ -33008,7 +33145,7 @@ function decodeRecoveryDecision(reply, bounds, secrets = []) {
33008
33145
  "after"
33009
33146
  ]);
33010
33147
  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))
33148
+ if (!writes.length || new Set(writes).size !== writes.length || writes.some((p) => !workflowCovers(within2, p) || sanitizeText(p, secrets) !== p))
33012
33149
  refuse3("An added assignment writes outside the run's write scope; list the additional paths in scope");
33013
33150
  const after = list(t.after, WORKFLOW_LIMITS.tasks, (v) => text(v, 64, true));
33014
33151
  if (new Set(after).size !== after.length)
@@ -33223,8 +33360,8 @@ function settledWorkerCleanup(output) {
33223
33360
  }
33224
33361
 
33225
33362
  // 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";
33363
+ import { lstatSync as lstatSync26, rmdirSync } from "node:fs";
33364
+ import { dirname as dirname25, join as join42 } from "node:path";
33228
33365
  function taskBranch(goal, id) {
33229
33366
  const slug2 = goal.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "").slice(0, 48).replace(/-$/u, "") || "task";
33230
33367
  return `refs/heads/cadence/${slug2}-${decodeId(id)}`;
@@ -33233,7 +33370,7 @@ function deliveryObservation(binding2, root, id, goal) {
33233
33370
  return {
33234
33371
  binding: binding2,
33235
33372
  taskBranch: taskBranch(goal, id),
33236
- worktreeRoot: join41(root, decodeId(id), "integration"),
33373
+ worktreeRoot: join42(root, decodeId(id), "integration"),
33237
33374
  preparation: "pending",
33238
33375
  workspace: null,
33239
33376
  candidate: null,
@@ -33282,7 +33419,7 @@ class WorkflowDelivery {
33282
33419
  for (const path of [dirname25(dirname25(this.home)), dirname25(this.home)]) {
33283
33420
  if (!safeDirectory(path, true))
33284
33421
  throw new ContractError("forbidden");
33285
- const stat = lstatSync25(path);
33422
+ const stat = lstatSync26(path);
33286
33423
  if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || process.getuid && stat.uid !== process.getuid()))
33287
33424
  throw new ContractError("forbidden");
33288
33425
  }
@@ -33322,7 +33459,7 @@ class WorkflowDelivery {
33322
33459
  return path;
33323
33460
  }
33324
33461
  childPath(id) {
33325
- return join41(this.home, "tasks", id);
33462
+ return join42(this.home, "tasks", id);
33326
33463
  }
33327
33464
  child(path) {
33328
33465
  return this.view.artifacts?.find((a) => a.path === path && this.children.has(path));
@@ -33517,8 +33654,8 @@ class WorkflowDelivery {
33517
33654
  }
33518
33655
 
33519
33656
  // src/service/workflow-history.ts
33520
- import { randomUUID as randomUUID26 } from "node:crypto";
33521
- import { lstatSync as lstatSync26, opendirSync as opendirSync15 } from "node:fs";
33657
+ import { randomUUID as randomUUID27 } from "node:crypto";
33658
+ import { lstatSync as lstatSync27, opendirSync as opendirSync15 } from "node:fs";
33522
33659
  class WorkflowHistoryScanner {
33523
33660
  path;
33524
33661
  directory;
@@ -33529,7 +33666,7 @@ class WorkflowHistoryScanner {
33529
33666
  this.directory = directory2;
33530
33667
  }
33531
33668
  incarnation() {
33532
- const st = lstatSync26(this.path, { bigint: true });
33669
+ const st = lstatSync27(this.path, { bigint: true });
33533
33670
  if (!st.isDirectory() || st.isSymbolicLink())
33534
33671
  throw new ContractError("corrupt-selected");
33535
33672
  return `${st.dev}:${st.ino}`;
@@ -33581,7 +33718,7 @@ class WorkflowHistoryScanner {
33581
33718
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
33582
33719
  state.ids.pop();
33583
33720
  }
33584
- const scan = randomUUID26();
33721
+ const scan = randomUUID27();
33585
33722
  state.timer = setTimeout(() => {
33586
33723
  this.scans.delete(scan);
33587
33724
  try {
@@ -34078,9 +34215,11 @@ function workflowResultDetail(value, secrets) {
34078
34215
  }
34079
34216
 
34080
34217
  // src/service/workflows.ts
34218
+ var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
34219
+ ${RUN_ENVIRONMENT_POLICY}`;
34081
34220
  var OWNER_RUNTIME = Object.freeze({
34082
- version: "2.1.4",
34083
- build: "b335d9eae2b7c1e2f864a55d263811ab93957a77385c3e230cfc289da0bce014",
34221
+ version: "2.1.5",
34222
+ build: "f394594500c6c18cd7ae0d307db53bbfbf13f988bfd92f5e3ca1bbc15b0d5e91",
34084
34223
  entry: fileURLToPath7(import.meta.url),
34085
34224
  pid: process.pid,
34086
34225
  node: process.versions.node,
@@ -34170,12 +34309,12 @@ class Workflows {
34170
34309
  constructor(o) {
34171
34310
  this.o = o;
34172
34311
  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"), () => {
34312
+ this.root = join43(o.coordination.directory, "workflows-v1");
34313
+ this.cwd = realpathSync14(o.coordination.store.root);
34314
+ this.worktreeRoot = join43(o.coordination.stateHome, "cadence-worktrees-v1", basename5(o.coordination.store.privateRoot));
34315
+ this.historyScanner = new WorkflowHistoryScanner(join43(this.root, "runs"), () => {
34177
34316
  this.o.owner.lease.assert();
34178
- return this.files.directory(join42(this.root, "runs"));
34317
+ return this.files.directory(join43(this.root, "runs"));
34179
34318
  });
34180
34319
  this.recover();
34181
34320
  }
@@ -34183,7 +34322,7 @@ class Workflows {
34183
34322
  return this.o.coordination.files;
34184
34323
  }
34185
34324
  path(id, name) {
34186
- return join42(this.root, "runs", decodeId(id), name);
34325
+ return join43(this.root, "runs", decodeId(id), name);
34187
34326
  }
34188
34327
  write(path, value, expected, max = RECORD_BYTES3) {
34189
34328
  this.o.owner.lease.assert();
@@ -34200,7 +34339,7 @@ class Workflows {
34200
34339
  `), 2048, this.o.secrets());
34201
34340
  }
34202
34341
  recover() {
34203
- const runs = join42(this.root, "runs");
34342
+ const runs = join43(this.root, "runs");
34204
34343
  if (!this.files.directory(runs))
34205
34344
  return;
34206
34345
  const ids = [];
@@ -34279,10 +34418,11 @@ class Workflows {
34279
34418
  run.delivery.integration.status = "unknown";
34280
34419
  run.delivery.integration.reason = "Owner restarted during integration; observe the target, never replay.";
34281
34420
  }
34282
- run.delivery.cleanup = {
34283
- status: "retained",
34284
- reason: "Owner restarted; artifacts retained without replay or cleanup."
34285
- };
34421
+ if (run.delivery.cleanup.status !== "removed")
34422
+ run.delivery.cleanup = {
34423
+ status: "retained",
34424
+ reason: "Owner restarted; artifacts retained without replay or cleanup."
34425
+ };
34286
34426
  if (run.delivery.workspace && run.delivery.workspace.state !== "removed")
34287
34427
  run.delivery.workspace.state = "retained";
34288
34428
  for (const child2 of run.delivery.artifacts ?? [])
@@ -34309,7 +34449,7 @@ class Workflows {
34309
34449
  throw new ContractError("quarantine");
34310
34450
  }
34311
34451
  floor() {
34312
- const space = statfsSync3(this.o.coordination.directory);
34452
+ const space = statfsSync4(this.o.coordination.directory);
34313
34453
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
34314
34454
  throw new ContractError("capacity");
34315
34455
  }
@@ -34335,7 +34475,7 @@ class Workflows {
34335
34475
  throw new ContractError("stale");
34336
34476
  safeDirectory(cwd, true);
34337
34477
  }
34338
- if (realpathSync13(cwd) !== cwd)
34478
+ if (realpathSync14(cwd) !== cwd)
34339
34479
  throw new ContractError("stale");
34340
34480
  return cwd;
34341
34481
  }
@@ -34350,6 +34490,7 @@ class Workflows {
34350
34490
  delivery,
34351
34491
  digest: hash(canonicalJson({
34352
34492
  runtime,
34493
+ environment: RUN_ENVIRONMENT_POLICY,
34353
34494
  source,
34354
34495
  delivery: delivery ?? null,
34355
34496
  working: plan.delivery === "working-copy" ? captureChanges(this.cwd).fingerprint : null
@@ -34357,7 +34498,7 @@ class Workflows {
34357
34498
  };
34358
34499
  }
34359
34500
  proposal(id) {
34360
- const file = this.files.read(join42(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES3);
34501
+ const file = this.files.read(join43(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES3);
34361
34502
  if (!file)
34362
34503
  throw new ContractError("unavailable");
34363
34504
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3));
@@ -34374,7 +34515,7 @@ class Workflows {
34374
34515
  const observed = this.observation(p.plan, runtime);
34375
34516
  if (p.plan.delivery === "local-merge" && !p.delivery)
34376
34517
  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)))
34518
+ 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
34519
  throw new ContractError("stale");
34379
34520
  return { source: observed.source, runtime };
34380
34521
  }
@@ -34583,8 +34724,8 @@ class Workflows {
34583
34724
  if (action === "prepare")
34584
34725
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
34585
34726
  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));
34727
+ return !!this.files.read(join43(this.root, "proposals", `${id}.json`), RECORD_BYTES3);
34728
+ return this.files.directory(join43(this.root, "runs", id));
34588
34729
  }
34589
34730
  admit(commandId, epoch, r, effect) {
34590
34731
  this.current();
@@ -34608,7 +34749,7 @@ class Workflows {
34608
34749
  checkoutRoot: this.cwd,
34609
34750
  observation: digest2,
34610
34751
  display: {
34611
- runtime: describeWorkerRuntime(runtime2),
34752
+ runtime: runtimeSummary(runtime2),
34612
34753
  model: `${selected2.provider}/${selected2.model} · ${selected2.thinking}`,
34613
34754
  branch: source.branch,
34614
34755
  baseCommit: source.head
@@ -34617,7 +34758,7 @@ class Workflows {
34617
34758
  };
34618
34759
  if (sanitizeData(p, secrets) !== canonicalJson(p))
34619
34760
  throw new ContractError("forbidden");
34620
- const target3 = join42(this.root, "proposals", `${commandId}.json`);
34761
+ const target3 = join43(this.root, "proposals", `${commandId}.json`);
34621
34762
  const previous = this.files.read(target3, RECORD_BYTES3);
34622
34763
  if (previous) {
34623
34764
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -34640,7 +34781,7 @@ class Workflows {
34640
34781
  this.grants.delete(key2);
34641
34782
  if (this.grants.size >= 16)
34642
34783
  throw new ContractError("capacity");
34643
- const grant = randomUUID27(), expiresAt = Date.now() + 120000;
34784
+ const grant = randomUUID28(), expiresAt = Date.now() + 120000;
34644
34785
  effect();
34645
34786
  this.grants.set(grant, {
34646
34787
  commandId,
@@ -34735,8 +34876,8 @@ class Workflows {
34735
34876
  };
34736
34877
  const abort = new AbortController;
34737
34878
  let begin;
34738
- const ready2 = new Promise((resolve15) => {
34739
- begin = resolve15;
34879
+ const ready2 = new Promise((resolve16) => {
34880
+ begin = resolve16;
34740
34881
  });
34741
34882
  const live2 = {
34742
34883
  runtime,
@@ -34782,7 +34923,7 @@ class Workflows {
34782
34923
  throw new ContractError("corrupt-selected");
34783
34924
  live2.file = this.write(this.path(live2.run.id, "state.json"), live2.run, live2.file);
34784
34925
  }
34785
- saveFinal(live2) {
34926
+ saveSettlement(live2) {
34786
34927
  const cause = live2.abort.signal.reason;
34787
34928
  if (live2.abort.signal.aborted && cause?.source)
34788
34929
  live2.run.notice = this.notice(live2.run.notice, `${cause.source}: ${cause.reason} (${live2.run.id})`);
@@ -34801,7 +34942,7 @@ class Workflows {
34801
34942
  assertRunning(live2) {
34802
34943
  this.current();
34803
34944
  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))
34945
+ 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
34946
  throw new ContractError("stale");
34806
34947
  }
34807
34948
  step(live2, id, kind, childRunId) {
@@ -34825,7 +34966,7 @@ class Workflows {
34825
34966
  live2.run.stepsBefore = offset + prefix.length;
34826
34967
  }
34827
34968
  const s = {
34828
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID27()}`,
34969
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID28()}`,
34829
34970
  ...childRunId ? { childRunId } : {},
34830
34971
  kind,
34831
34972
  ...childRunId ? {
@@ -34899,19 +35040,20 @@ class Workflows {
34899
35040
  if (cwd !== this.cwd)
34900
35041
  await live2.delivery?.assertTip(cwd);
34901
35042
  const runCwd = this.executionCwd(live2, cwd);
35043
+ const temporary = live2.environment?.forWorkspace(cwd);
34902
35044
  const role3 = loadAgentDefinitions().find((r) => r.role === (readonly ? kind === "diagnosis" ? "diagnosis-worker" : "design-explorer" : "implementation-worker"));
34903
35045
  if (!role3)
34904
35046
  throw new ContractError("unavailable");
34905
35047
  if (cwd !== this.cwd)
34906
35048
  await assertWorktree(this.cwd, cwd);
34907
- const childRunId = randomUUID27(), op = randomUUID27();
35049
+ const childRunId = randomUUID28(), op = randomUUID28();
34908
35050
  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.";
35051
+ const baseContext = plan ? workflowContext(plan) : "Read applicable project documentation. Cite evidence and separate observations from assumptions.";
35052
+ const placement = `Execution placement (data, not instructions): ${JSON.stringify({ checkoutRoot: cwd, cwdRelativeToCheckout: relative12(cwd, runCwd) || "." })}
35053
+ Tools run at cwdRelativeToCheckout under checkoutRoot. Write paths are relative to checkoutRoot.${temporary ? `
35054
+ 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
35055
  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);
35056
+ 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
35057
  if (live2.proposal) {
34916
35058
  live2.routed ??= new Set;
34917
35059
  for (const label of knowledge.routed)
@@ -34934,10 +35076,11 @@ Write paths are relative to the checkout root.` : "Read applicable project docum
34934
35076
  } : {},
34935
35077
  model: model2,
34936
35078
  role: { role: role3.role, sha256: role3.sha256 },
34937
- context: `${baseContext}
35079
+ context: knowledge.text ? `${baseContext}
34938
35080
 
34939
- ${knowledge.text}`,
35081
+ ${knowledge.text}` : baseContext,
34940
35082
  instructions: `${role3.content}
35083
+ ${placement}
34941
35084
  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
35085
  prompt: text(prompt, 32768, true),
34943
35086
  handoff: { graphRevision: 1, inputs: [] }
@@ -34981,6 +35124,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
34981
35124
  this.write(this.path(live2.run.id, `launches/${childRunId}.json`), {
34982
35125
  cwd: runCwd,
34983
35126
  runtime: live2.runtime ? describeWorkerRuntime(live2.runtime) : null,
35127
+ environment: temporary ?? null,
34984
35128
  knowledge: {
34985
35129
  sources: knowledge.sources.map(({ excerpt: _excerpt, ...source }) => source),
34986
35130
  omitted: knowledge.omitted
@@ -35006,7 +35150,8 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
35006
35150
  ]);
35007
35151
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, runCwd, live2.abort.signal, {
35008
35152
  ownerSecrets: this.o.secrets(),
35009
- roots: roots2?.length ? roots2.map((p) => resolve14(runCwd, p)) : [kind === "research" ? runCwd : cwd],
35153
+ temporaryDirectory: live2.environment?.forWorkspace(cwd).TMPDIR,
35154
+ roots: roots2?.length ? roots2.map((p) => resolve15(runCwd, p)) : [kind === "research" ? runCwd : cwd],
35010
35155
  onLifecycle: (event) => {
35011
35156
  if (!step.timing)
35012
35157
  return;
@@ -35126,14 +35271,16 @@ Partial work is preserved.`);
35126
35271
  if (cwd !== this.cwd && shell)
35127
35272
  await assertWorktree(this.cwd, cwd);
35128
35273
  const runCwd = shell ? this.executionCwd(live2, cwd) : cwd;
35129
- const id = randomUUID27();
35274
+ const id = randomUUID28();
35130
35275
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
35131
35276
  cwd: runCwd,
35132
35277
  args: shell ? operation.check : operation.git
35133
35278
  });
35134
35279
  let native;
35280
+ const temporary = options.temporary ?? live2.environment?.forWorkspace(cwd);
35135
35281
  const environment2 = {
35136
35282
  ...this.o.checkEnvironment ?? {},
35283
+ ...temporary,
35137
35284
  CADENCE_SUBAGENT_CHILD: "1"
35138
35285
  };
35139
35286
  const running = Promise.resolve().then(() => runProcess({
@@ -35141,7 +35288,7 @@ Partial work is preserved.`);
35141
35288
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
35142
35289
  "--no-lazy-fetch",
35143
35290
  "-c",
35144
- `core.hooksPath=${join42(this.root, "empty-hooks")}`,
35291
+ `core.hooksPath=${join43(this.root, "empty-hooks")}`,
35145
35292
  "-c",
35146
35293
  "commit.gpgsign=false",
35147
35294
  "-c",
@@ -35152,7 +35299,7 @@ Partial work is preserved.`);
35152
35299
  ]),
35153
35300
  windowsVerbatimArguments: shell && process.platform === "win32" ? true : undefined,
35154
35301
  cwd: runCwd,
35155
- env: shell ? environment2 : gitEnvironment(),
35302
+ env: shell ? environment2 : { ...gitEnvironment(), ...temporary },
35156
35303
  retainOutput: true,
35157
35304
  stopTarget: id,
35158
35305
  signal: options.uninterruptible ? new AbortController().signal : live2.abort.signal,
@@ -35193,7 +35340,8 @@ Partial work is preserved.`);
35193
35340
  const step = this.step(live2, title, "check");
35194
35341
  try {
35195
35342
  const runCwd = this.executionCwd(live2, cwd);
35196
- const result = await this.run(live2, cwd, { check: c });
35343
+ const temporary = live2.environment?.forWorkspace(cwd);
35344
+ const result = await this.run(live2, cwd, { check: c }, { temporary });
35197
35345
  this.finishStep(live2, step, result, result.outcome === "completed" ? undefined : `${c.name} in ${runCwd}
35198
35346
  Command: ${c.command}
35199
35347
  ${result.output || result.text}`, undefined, {
@@ -35204,9 +35352,9 @@ ${result.output || result.text}`, undefined, {
35204
35352
  target: live2.run.delivery?.binding.target ?? null,
35205
35353
  environment: Object.fromEntries(["TMPDIR", "TEMP", "TMP"].map((name) => [
35206
35354
  name,
35207
- this.o.checkEnvironment?.[name] ?? null
35355
+ temporary?.[name] ?? this.o.checkEnvironment?.[name] ?? null
35208
35356
  ])),
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."
35357
+ 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
35358
  });
35211
35359
  return { result, step };
35212
35360
  } finally {
@@ -35273,7 +35421,14 @@ ${step.text}` : ""}`, step?.id);
35273
35421
  for (const c of p.plan.setup.filter((c2) => (c2.placement ?? "worktree") === placement)) {
35274
35422
  if (placement === "target") {
35275
35423
  const { result, step } = await this.check(live2, cwd, c, `setup: ${c.name}`);
35276
- this.success(result, step);
35424
+ try {
35425
+ this.success(result, step);
35426
+ } catch (error) {
35427
+ if (!(error instanceof WorkflowFailure))
35428
+ throw error;
35429
+ 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.
35430
+ ${error.message}`, step?.id);
35431
+ }
35277
35432
  continue;
35278
35433
  }
35279
35434
  await this.recoverStage(live2, cwd, p, `setup: ${c.name}`, async () => {
@@ -35439,7 +35594,7 @@ ${IMPLEMENTATION_REPORT}`, false, version, undefined, kind);
35439
35594
  return this.recordedInvestigation(id) !== null;
35440
35595
  }
35441
35596
  investigationPath(id) {
35442
- return join42(this.root, "investigations", `${decodeId(id)}.json`);
35597
+ return join43(this.root, "investigations", `${decodeId(id)}.json`);
35443
35598
  }
35444
35599
  recordedInvestigation(id) {
35445
35600
  try {
@@ -35497,7 +35652,7 @@ This recorded investigation is out of date: ${changed.slice(0, 8).join(", ")}${c
35497
35652
  ${moved}${record3.answer}`;
35498
35653
  }
35499
35654
  questionPath(question, roots2) {
35500
- return join42(this.root, "investigations", "questions", `${questionKey(question, roots2)}.json`);
35655
+ return join43(this.root, "investigations", "questions", `${questionKey(question, roots2)}.json`);
35501
35656
  }
35502
35657
  answered(question, roots2) {
35503
35658
  try {
@@ -35551,7 +35706,7 @@ ${diagnosticText(lines.join(`
35551
35706
  async review(live2, cwd, p, checks) {
35552
35707
  live2.run.phase = "reviewing";
35553
35708
  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.
35709
+ 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
35710
  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
35711
  Files: ${this.scope(live2, p).join(", ")}${this.deviationBrief(live2, "review")}${live2.knowledgeDone && live2.managed ? `
35557
35712
  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 +35953,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35798
35953
  if (head)
35799
35954
  await assertCandidate(cwd, head);
35800
35955
  if (checked2 && verdict === "approved") {
35801
- const id = randomUUID27(), steps = [...checks.map((s) => s.id), review.id];
35956
+ const id = randomUUID28(), steps = [...checks.map((s) => s.id), review.id];
35802
35957
  this.write(this.path(live2.run.id, `verification/${id}.json`), {
35803
35958
  id,
35804
35959
  agreement: p.digest,
@@ -35860,7 +36015,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35860
36015
  }
35861
36016
  knowledgeTurn(live2, lint) {
35862
36017
  const topics = lint.usage.topics.map((t) => t.path);
35863
- const path = join42(this.root, "knowledge-use.json");
36018
+ const path = join43(this.root, "knowledge-use.json");
35864
36019
  try {
35865
36020
  const file = this.files.read(path, RECORD_BYTES3);
35866
36021
  const next = advanceKnowledgeUse(file ? decodeKnowledgeUse(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3)) : null, { routes: lint.routes, topics }, live2.routed ?? []);
@@ -36131,8 +36286,8 @@ ${result.output}`}`);
36131
36286
  break;
36132
36287
  await Promise.race([
36133
36288
  ...running.values(),
36134
- new Promise((resolve15) => {
36135
- revised = resolve15;
36289
+ new Promise((resolve16) => {
36290
+ revised = resolve16;
36136
36291
  })
36137
36292
  ]);
36138
36293
  }
@@ -36385,14 +36540,24 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
36385
36540
  }
36386
36541
  async execute(live2, request3) {
36387
36542
  let failure2 = "";
36543
+ let outcome = "unknown";
36388
36544
  try {
36389
36545
  this.assertRunning(live2);
36390
36546
  live2.barrier = await this.o.gate.acquire(live2.run.id, live2.abort.signal);
36391
36547
  live2.barrier.assertHeld();
36392
36548
  if (live2.run.diagnostics)
36393
36549
  live2.run.diagnostics.acquiredAt = Date.now();
36394
- if (live2.proposal)
36550
+ if (live2.proposal) {
36395
36551
  await this.assertStartable(live2, live2.proposal);
36552
+ let environmentFile;
36553
+ live2.environment = new RunEnvironment(this.o.coordination.stateHome, this.cwd, (directories) => {
36554
+ environmentFile = this.write(this.path(live2.run.id, "environment.json"), { directories }, environmentFile);
36555
+ }, () => {
36556
+ this.o.owner.lease.assert();
36557
+ if (this.o.owner.state !== "idle" || live2.abort.signal.aborted)
36558
+ throw new ContractError("unavailable");
36559
+ });
36560
+ }
36396
36561
  if (live2.run.delivery)
36397
36562
  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
36563
  live2.run.status = "running";
@@ -36407,32 +36572,60 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
36407
36572
  throw new WorkflowFailure("unknown", "Original operation or cleanup settlement is unknown; delivery is not reported as completed.");
36408
36573
  if (live2.abort.signal.aborted)
36409
36574
  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
- `));
36575
+ outcome = "completed";
36415
36576
  } 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";
36577
+ outcome = this.o.owner.state === "quarantined" ? "unknown" : live2.abort.signal.aborted ? "canceled" : error instanceof WorkflowFailure && error.outcome !== "completed" ? error.outcome : "failed";
36417
36578
  failure2 = this.describe(error);
36418
36579
  } finally {
36419
- live2.run.phase = "finished";
36420
- if (live2.run.diagnostics)
36421
- live2.run.diagnostics.settledAt = Date.now();
36422
36580
  if (live2.delivery && this.o.owner.state === "idle") {
36423
36581
  try {
36424
36582
  live2.delivery.finish();
36425
36583
  } catch {
36426
36584
  this.o.owner.quarantine();
36427
- live2.run.status = "unknown";
36585
+ outcome = "unknown";
36428
36586
  }
36429
36587
  }
36588
+ let resources = "";
36589
+ if (live2.environment) {
36590
+ live2.run.notice = this.notice("Finalizing the run's temporary resources; the outcome is not yet settled.", failure2);
36591
+ try {
36592
+ this.saveSettlement(live2);
36593
+ } catch {
36594
+ this.o.owner.quarantine();
36595
+ outcome = "unknown";
36596
+ failure2 = this.notice(failure2, "Workflow settlement could not be recorded; temporary resources are retained.");
36597
+ }
36598
+ try {
36599
+ const retained = await live2.environment.finish(this.o.owner.state === "idle" && outcome === "completed" && !live2.abort.signal.aborted);
36600
+ if (retained.length)
36601
+ resources = `Temporary resource paths retained or unconfirmed: ${retained.join(", ")}`;
36602
+ } catch {
36603
+ this.o.owner.quarantine();
36604
+ outcome = "unknown";
36605
+ resources = "Temporary-resource recording did not settle; remaining directories are retained.";
36606
+ }
36607
+ }
36608
+ if (this.o.owner.state === "quarantined") {
36609
+ outcome = "unknown";
36610
+ failure2 = this.notice(failure2, "Owner settlement is unconfirmed; delivery is not reported as completed.");
36611
+ } else if (live2.abort.signal.aborted && outcome === "completed") {
36612
+ outcome = "canceled";
36613
+ failure2 = this.notice(failure2, "Cancellation requested before finalization settled; actual delivery is preserved.");
36614
+ }
36615
+ live2.run.status = outcome;
36616
+ live2.run.phase = "finished";
36617
+ if (live2.run.diagnostics)
36618
+ live2.run.diagnostics.settledAt = Date.now();
36619
+ const deviations = outcome === "completed" ? live2.run.deviations ?? [] : [];
36430
36620
  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);
36621
+ 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:
36622
+ ${deviations.map((d) => `${d.item} → ${d.delivered}`).join(`
36623
+ `)}` : "", failure2, delivered.length ? `${outcome === "completed" ? "Changed files" : "Changed files so far"}: ${delivered.join(", ")}` : "", ...live2.notes, resources);
36432
36624
  try {
36433
- this.saveFinal(live2);
36625
+ this.saveSettlement(live2);
36434
36626
  } catch {
36435
36627
  this.o.owner.quarantine();
36628
+ live2.run.status = "unknown";
36436
36629
  }
36437
36630
  if (this.o.owner.state === "idle")
36438
36631
  live2.barrier?.release();
@@ -36468,7 +36661,7 @@ class Workbench {
36468
36661
  });
36469
36662
  this.conversations.assertSettled();
36470
36663
  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");
36664
+ this.projectRoot = join44(o.coordination.files.namespace, "workbench-projects-v1");
36472
36665
  }
36473
36666
  activityReaderScope() {
36474
36667
  return activityReaderScope(this.o.agentDir, this.o.sessionDir);
@@ -36634,7 +36827,7 @@ class Workbench {
36634
36827
  for (let e = directory2.readSync();e; e = directory2.readSync()) {
36635
36828
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries3.length > 128)
36636
36829
  throw new ContractError("corrupt-selected");
36637
- const saved = files.read(join43(this.projectRoot, e.name));
36830
+ const saved = files.read(join44(this.projectRoot, e.name));
36638
36831
  if (!saved)
36639
36832
  throw new ContractError("corrupt-selected");
36640
36833
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -36730,7 +36923,7 @@ class Workbench {
36730
36923
  if (this.opening.size >= 64)
36731
36924
  throw new ContractError("capacity");
36732
36925
  const path = this.files.directory(request3.path);
36733
- const marker2 = join43(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
36926
+ const marker2 = join44(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
36734
36927
  const files = this.o.coordination.files;
36735
36928
  if (files.read(marker2))
36736
36929
  throw new ContractError("receipt-inconclusive");
@@ -36748,7 +36941,7 @@ class Workbench {
36748
36941
  }
36749
36942
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
36750
36943
  for (const root of [this.o.cwd, opened.path]) {
36751
- const entry = join43(this.projectRoot, `${hash(root)}.json`);
36944
+ const entry = join44(this.projectRoot, `${hash(root)}.json`);
36752
36945
  const saved = files.read(entry);
36753
36946
  if (!saved)
36754
36947
  files.create(entry, canonicalJson({ path: root }));
@@ -36778,7 +36971,7 @@ async function predecessorExited() {
36778
36971
  } catch {
36779
36972
  return;
36780
36973
  }
36781
- await new Promise((resolve15) => setTimeout(resolve15, 100));
36974
+ await new Promise((resolve16) => setTimeout(resolve16, 100));
36782
36975
  }
36783
36976
  }
36784
36977
  async function healBeforeStart(c) {
@@ -36816,8 +37009,8 @@ function legacy(store, budget, reader) {
36816
37009
  decodeId(entry.name);
36817
37010
  if (created.has(entry.name))
36818
37011
  continue;
36819
- const path = join44(store.tasks, entry.name, "task.json");
36820
- const size3 = lstatSync27(path).size;
37012
+ const path = join45(store.tasks, entry.name, "task.json");
37013
+ const size3 = lstatSync28(path).size;
36821
37014
  if (size3 > 128 * 1024)
36822
37015
  throw new ContractError("corrupt-selected");
36823
37016
  budget.reserve(size3);
@@ -36952,8 +37145,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
36952
37145
  let timer;
36953
37146
  await Promise.race([
36954
37147
  owner?.idle(),
36955
- new Promise((resolve15) => {
36956
- timer = setTimeout(resolve15, FAULT_SETTLE_MS);
37148
+ new Promise((resolve16) => {
37149
+ timer = setTimeout(resolve16, FAULT_SETTLE_MS);
36957
37150
  })
36958
37151
  ]);
36959
37152
  clearTimeout(timer);