@abelxiaoxing/cadence 2.1.3 → 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.
@@ -5585,7 +5585,16 @@ function decodeWorkflowPlan(v, options = {}) {
5585
5585
  },
5586
5586
  tasks,
5587
5587
  checks,
5588
- setup: commands(o.setup, "setup", 4),
5588
+ setup: entries("setup", o.setup, 4, (value, path) => {
5589
+ const entry = fields2(path, value, ["name", "command", ...strict ? ["placement"] : []], ["timeoutMs", ...!strict ? ["placement"] : []]);
5590
+ const { placement, ...check } = entry;
5591
+ return {
5592
+ ...decodeWorkflowCheck(check, path),
5593
+ ...placement === undefined ? {} : {
5594
+ placement: at(`${path}.placement`, () => oneOf(placement, ["target", "candidate", "worktree"]))
5595
+ }
5596
+ };
5597
+ }),
5589
5598
  baselineChecks: commands(o.baselineChecks, "baselineChecks", WORKFLOW_LIMITS.checks),
5590
5599
  delivery: at("delivery", () => {
5591
5600
  try {
@@ -6095,7 +6104,7 @@ function decodeWorkflowRun(v) {
6095
6104
  "check",
6096
6105
  "git"
6097
6106
  ]),
6098
- status: s.kind === "review" && s.status === "rejected" ? "rejected" : status(s.status),
6107
+ status: s.kind === "review" && s.status === "rejected" ? "rejected" : ["implementation", "knowledge"].includes(s.kind) && ["partial", "blocked"].includes(s.status) ? oneOf(s.status, ["partial", "blocked"]) : status(s.status),
6099
6108
  text: text(s.text, 65536),
6100
6109
  exitCode: nullable(s.exitCode, (n) => integer(n, -2147483648, 2147483647)),
6101
6110
  truncated: bool(s.truncated)
@@ -6156,7 +6165,8 @@ ${t.instructions}`).join(`
6156
6165
  `)}
6157
6166
 
6158
6167
  ## Setup (explicitly authorized commands)
6159
- ${p.setup.map(readableCheck).join(`
6168
+ Execution order: target once before worktree creation, candidate once, then worktree in the candidate and every detached child; listed order within each stage. Each command is a separate process; exports do not persist.
6169
+ ${p.setup.map((c) => `[${c.placement ?? "worktree"}] ${readableCheck(c)}`).join(`
6160
6170
  `) || "None; no dependency installation or copying."}
6161
6171
 
6162
6172
  ## Baseline verification
@@ -16950,7 +16960,7 @@ async function createGateway(value, hostUrl, source) {
16950
16960
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
16951
16961
  const web = loadWebAssets(source?.webDirectory);
16952
16962
  const build2 = {
16953
- contractHash: "22fa5bdb0557f6831e6623c6c8f8458679ac6c7b28862f19aec01b8a607cdb26",
16963
+ contractHash: "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245",
16954
16964
  assets: {
16955
16965
  sourceHash: web.manifest.sourceHash,
16956
16966
  contractHash: web.manifest.contractHash,
@@ -17834,8 +17844,8 @@ Content-Length: 0\r
17834
17844
 
17835
17845
  // src/service/host.ts
17836
17846
  import { spawn as spawn7 } from "node:child_process";
17837
- import { lstatSync as lstatSync27, opendirSync as opendirSync18 } from "node:fs";
17838
- 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";
17839
17849
  import { fileURLToPath as fileURLToPath8 } from "node:url";
17840
17850
 
17841
17851
  // src/agent-registry.ts
@@ -27238,12 +27248,149 @@ async function healHistory(lease, log) {
27238
27248
 
27239
27249
  // src/subagent-process.ts
27240
27250
  import { spawn as spawn5 } from "node:child_process";
27241
- import { createHash as createHash28, randomUUID as randomUUID21 } from "node:crypto";
27242
- 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";
27243
27253
  import { StringDecoder } from "node:string_decoder";
27244
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
+
27245
27392
  // src/worker-capture.mjs
27246
- import { createHash as createHash27, randomUUID as randomUUID20 } from "node:crypto";
27393
+ import { createHash as createHash27, randomUUID as randomUUID21 } from "node:crypto";
27247
27394
  var completeCoverage = () => ({
27248
27395
  observed: "complete",
27249
27396
  source: "complete",
@@ -27813,11 +27960,11 @@ class WorkerRecording {
27813
27960
  try {
27814
27961
  await Promise.race([
27815
27962
  ...this.pending,
27816
- new Promise((resolve12) => {
27817
- abort = resolve12;
27963
+ new Promise((resolve13) => {
27964
+ abort = resolve13;
27818
27965
  signal.addEventListener("abort", abort, { once: true });
27819
27966
  if (signal.aborted)
27820
- resolve12();
27967
+ resolve13();
27821
27968
  })
27822
27969
  ]);
27823
27970
  } finally {
@@ -27868,7 +28015,7 @@ class WorkerRecording {
27868
28015
  // src/subagent-process.ts
27869
28016
  function terminateWindowsTree(pid, fallback) {
27870
28017
  const root = process.env.SystemRoot;
27871
- 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 });
27872
28019
  taskkill.once("error", fallback);
27873
28020
  taskkill.once("close", (code2) => {
27874
28021
  if (code2 !== 0)
@@ -27907,7 +28054,7 @@ function runProcess(spec) {
27907
28054
  if (spec.input !== undefined && Buffer.byteLength(spec.input) > 128 * 1024)
27908
28055
  return Promise.resolve(early("failed", "Worker input exceeds bound"));
27909
28056
  const ipc = !!(spec.onCoordinator || spec.onAuth || spec.inputs);
27910
- return new Promise((resolve12) => {
28057
+ return new Promise((resolve13) => {
27911
28058
  const child2 = spawn5(spec.command, spec.args, {
27912
28059
  cwd: spec.cwd,
27913
28060
  env: spec.env ?? safeChildEnv(),
@@ -28024,7 +28171,7 @@ function runProcess(spec) {
28024
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);
28025
28172
  const safeOutput = clean(output, Number.MAX_SAFE_INTEGER);
28026
28173
  const outputBytes2 = spec.retainOutput ? 256 * 1024 : 65536;
28027
- resolve12({
28174
+ resolve13({
28028
28175
  ...stopCause ? { stop: stopCause } : {},
28029
28176
  outcome,
28030
28177
  closed: closed2,
@@ -28412,7 +28559,7 @@ function encodeEnvelope(material, captured, roots = [material.cwd]) {
28412
28559
  throw new Error("network");
28413
28560
  return { material, investigation, ambient, scoped, selected: selected2, secrets, input };
28414
28561
  }
28415
- function launchEncoded(encoded2, signal, extra = {}) {
28562
+ function launchEncoded(encoded2, signal, extra = {}, temporaryDirectory) {
28416
28563
  if (!sameNetwork(encoded2.ambient, networkSnapshot(process.env)) || !sameNetwork(encoded2.scoped, scopedNetwork(encoded2.material)))
28417
28564
  throw new Error("network");
28418
28565
  return runProcess({
@@ -28420,7 +28567,7 @@ function launchEncoded(encoded2, signal, extra = {}) {
28420
28567
  args: [fileURLToPath6(new URL("./sdk-worker.mjs", import.meta.url))],
28421
28568
  cwd: encoded2.material.cwd,
28422
28569
  input: encoded2.input,
28423
- env: encoded2.selected.env,
28570
+ env: temporaryDirectory ? { ...encoded2.selected.env, ...temporaryEnvironment(temporaryDirectory) } : encoded2.selected.env,
28424
28571
  protocol: true,
28425
28572
  childRunId: encoded2.material.request.childRunId,
28426
28573
  expectedRequest: encoded2.material.request,
@@ -28505,7 +28652,7 @@ function launchWorkflowWorker(prepared, cwd, signal, options) {
28505
28652
  onLifecycle: options.onLifecycle,
28506
28653
  onNative: (native, capture) => options.onNative(native, capture?.selected?.messageId),
28507
28654
  onFrame: (frame) => options.onFrame(frame, secrets)
28508
- });
28655
+ }, options.temporaryDirectory);
28509
28656
  });
28510
28657
  }
28511
28658
 
@@ -28610,7 +28757,7 @@ class CheckoutGate {
28610
28757
  throw new ContractError("conflict");
28611
28758
  if (this.waiting.length >= CHECKOUT_WAITERS)
28612
28759
  throw new ContractError("capacity");
28613
- const result = new Promise((resolve12, reject) => {
28760
+ const result = new Promise((resolve13, reject) => {
28614
28761
  const abort = () => {
28615
28762
  const at2 = this.waiting.indexOf(waiter);
28616
28763
  if (at2 >= 0)
@@ -28620,7 +28767,7 @@ class CheckoutGate {
28620
28767
  id,
28621
28768
  resolve: (permit) => {
28622
28769
  signal.removeEventListener("abort", abort);
28623
- resolve12(permit);
28770
+ resolve13(permit);
28624
28771
  },
28625
28772
  reject: (error) => {
28626
28773
  signal.removeEventListener("abort", abort);
@@ -28668,14 +28815,14 @@ class CheckoutGate {
28668
28815
  }
28669
28816
 
28670
28817
  // src/service/model-choice.ts
28671
- import { randomUUID as randomUUID22 } from "node:crypto";
28818
+ import { randomUUID as randomUUID23 } from "node:crypto";
28672
28819
  var choiceOwners = new WeakSet;
28673
28820
 
28674
28821
  class OwnerModelChoice {
28675
28822
  options;
28676
28823
  selection = null;
28677
28824
  revision;
28678
- catalogId = randomUUID22();
28825
+ catalogId = randomUUID23();
28679
28826
  installing = false;
28680
28827
  constructor(options) {
28681
28828
  this.options = options;
@@ -28738,7 +28885,7 @@ class OwnerModelChoice {
28738
28885
  if (this.selection?.sourceSelectionId !== selected2.sourceSelectionId) {
28739
28886
  this.selection = selected2;
28740
28887
  ++this.revision;
28741
- this.catalogId = randomUUID22();
28888
+ this.catalogId = randomUUID23();
28742
28889
  this.options.owner.configurationInstalled();
28743
28890
  }
28744
28891
  try {
@@ -28752,7 +28899,7 @@ class OwnerModelChoice {
28752
28899
  }
28753
28900
 
28754
28901
  // src/service/model-context.ts
28755
- import { randomUUID as randomUUID23 } from "node:crypto";
28902
+ import { randomUUID as randomUUID24 } from "node:crypto";
28756
28903
 
28757
28904
  // src/worker-model.mjs
28758
28905
  var WORKER_POLICY = Object.freeze({
@@ -29048,18 +29195,18 @@ function projectModelCatalog(runtime, supportedThinking, current2, literals, val
29048
29195
  }
29049
29196
 
29050
29197
  // src/service/worker-settings.ts
29051
- import { lstatSync as lstatSync20, realpathSync as realpathSync11 } from "node:fs";
29052
- 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";
29053
29200
  var SETTINGS_FILE_BYTES = 1024 * 1024;
29054
29201
  function observe(path) {
29055
29202
  let target2;
29056
29203
  try {
29057
- target2 = realpathSync11(path);
29204
+ target2 = realpathSync12(path);
29058
29205
  } catch (error) {
29059
29206
  if (error.code !== "ENOENT")
29060
29207
  throw error;
29061
29208
  try {
29062
- lstatSync20(path);
29209
+ lstatSync21(path);
29063
29210
  } catch (missing2) {
29064
29211
  if (missing2.code === "ENOENT")
29065
29212
  return;
@@ -29085,7 +29232,7 @@ function readWorkerRuntime(cwd, agentDir, model2, pi) {
29085
29232
  throw new ContractError("corrupt-selected");
29086
29233
  return body;
29087
29234
  };
29088
- const global = source(join36(agentDir, "settings.json"));
29235
+ const global = source(join37(agentDir, "settings.json"));
29089
29236
  const storage = (project2) => ({
29090
29237
  withLock(scope, use) {
29091
29238
  if (use(scope === "global" ? global : project2) !== undefined)
@@ -29097,10 +29244,10 @@ function readWorkerRuntime(cwd, agentDir, model2, pi) {
29097
29244
  });
29098
29245
  if (user.drainErrors().length)
29099
29246
  throw new ContractError("corrupt-selected");
29100
- const trust = source(join36(agentDir, "trust.json"));
29247
+ const trust = source(join37(agentDir, "trust.json"));
29101
29248
  const decision = trust === undefined ? null : new pi.ProjectTrustStore(agentDir).get(cwd);
29102
29249
  const projectTrusted = decision ?? user.getDefaultProjectTrust() === "always";
29103
- const project = projectTrusted ? source(join36(cwd, ".pi", "settings.json")) : undefined;
29250
+ const project = projectTrusted ? source(join37(cwd, ".pi", "settings.json")) : undefined;
29104
29251
  const manager = pi.SettingsManager.fromStorage(storage(project), {
29105
29252
  projectTrusted
29106
29253
  });
@@ -29290,7 +29437,7 @@ class OwnerModelContext {
29290
29437
  const current2 = this.catalogSource();
29291
29438
  const validated = this.validateModel(selector, current2);
29292
29439
  this.#options.owner.assertQuiescent();
29293
- const selection = { sourceSelectionId: randomUUID23(), ...selector };
29440
+ const selection = { sourceSelectionId: randomUUID24(), ...selector };
29294
29441
  const selected2 = {
29295
29442
  ...validated,
29296
29443
  model: clonePrivate(validated.model),
@@ -29401,7 +29548,7 @@ class OwnerModelContext {
29401
29548
  throw new ContractError("capacity");
29402
29549
  const selector = decodeModelSelector(input);
29403
29550
  const validated = this.validateModel(selector, this.catalogSource());
29404
- const selection = { sourceSelectionId: randomUUID23(), ...selector };
29551
+ const selection = { sourceSelectionId: randomUUID24(), ...selector };
29405
29552
  this.#selected.set(selection.sourceSelectionId, {
29406
29553
  ...validated,
29407
29554
  model: clonePrivate(validated.model),
@@ -29496,10 +29643,10 @@ class OwnerModelContext {
29496
29643
  closed2 = true;
29497
29644
  };
29498
29645
  let reportClosed;
29499
- const closedWait = new Promise((resolve12) => {
29646
+ const closedWait = new Promise((resolve13) => {
29500
29647
  reportClosed = () => {
29501
29648
  close();
29502
- resolve12(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
29649
+ resolve13(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
29503
29650
  };
29504
29651
  });
29505
29652
  input.signal.addEventListener("abort", reportClosed, { once: true });
@@ -29639,7 +29786,7 @@ class OwnerModelContext {
29639
29786
  const next = this.prepareTracked({
29640
29787
  ...input,
29641
29788
  runtime: workerRuntime,
29642
- operationId: randomUUID23()
29789
+ operationId: randomUUID24()
29643
29790
  });
29644
29791
  const result = await next.result;
29645
29792
  await next.settled;
@@ -29952,8 +30099,8 @@ class ServiceOwner {
29952
30099
  if (!this.attempt) {
29953
30100
  this.reportingExpired = false;
29954
30101
  let complete;
29955
- this.attempt = new Promise((resolve12) => {
29956
- complete = resolve12;
30102
+ this.attempt = new Promise((resolve13) => {
30103
+ complete = resolve13;
29957
30104
  });
29958
30105
  const finish = () => {
29959
30106
  this.attempt = undefined;
@@ -29971,11 +30118,11 @@ class ServiceOwner {
29971
30118
  try {
29972
30119
  await Promise.race([
29973
30120
  this.attempt,
29974
- new Promise((resolve12) => {
30121
+ new Promise((resolve13) => {
29975
30122
  timer = setTimeout(() => {
29976
30123
  this.reportingExpired = true;
29977
30124
  this.persistPhase("quarantined");
29978
- resolve12();
30125
+ resolve13();
29979
30126
  }, waitMs);
29980
30127
  })
29981
30128
  ]);
@@ -30006,7 +30153,7 @@ class ServiceOwner {
30006
30153
 
30007
30154
  // src/service/workbench.ts
30008
30155
  import { opendirSync as opendirSync17 } from "node:fs";
30009
- import { join as join43 } from "node:path";
30156
+ import { join as join44 } from "node:path";
30010
30157
 
30011
30158
  // src/service/conversation-images.ts
30012
30159
  var binding = (send2) => {
@@ -30092,17 +30239,17 @@ class ConversationImages {
30092
30239
  }
30093
30240
 
30094
30241
  // src/service/conversation-workflow.ts
30095
- import { randomUUID as randomUUID24 } from "node:crypto";
30096
- import { join as join38 } from "node:path";
30242
+ import { randomUUID as randomUUID25 } from "node:crypto";
30243
+ import { join as join39 } from "node:path";
30097
30244
 
30098
30245
  // src/cadence-instructions.ts
30099
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.
30100
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.
30101
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.
30102
- 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. 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.
30103
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.
30104
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.
30105
- 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.
30106
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.
30107
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.`;
30108
30255
 
@@ -30111,9 +30258,9 @@ import { isUtf8 } from "node:buffer";
30111
30258
  import { createHash as createHash30 } from "node:crypto";
30112
30259
  import {
30113
30260
  closeSync as closeSync11,
30114
- constants as constants10,
30261
+ constants as constants11,
30115
30262
  fstatSync as fstatSync8,
30116
- lstatSync as lstatSync23,
30263
+ lstatSync as lstatSync24,
30117
30264
  opendirSync as opendirSync13,
30118
30265
  openSync as openSync11,
30119
30266
  readSync as readSync7
@@ -30121,26 +30268,26 @@ import {
30121
30268
  import { dirname as dirname23, posix as posix2 } from "node:path";
30122
30269
 
30123
30270
  // src/service/knowledge-store.ts
30124
- 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";
30125
30272
  import { dirname as dirname22, posix } from "node:path";
30126
30273
 
30127
30274
  // src/service/workflow-git.ts
30128
- import { spawn as spawn6, spawnSync as spawnSync5 } from "node:child_process";
30275
+ import { spawn as spawn6, spawnSync as spawnSync6 } from "node:child_process";
30129
30276
  import { createHash as createHash29 } from "node:crypto";
30130
30277
  import {
30131
30278
  closeSync as closeSync10,
30132
- constants as constants9,
30279
+ constants as constants10,
30133
30280
  existsSync as existsSync4,
30134
30281
  fstatSync as fstatSync7,
30135
- lstatSync as lstatSync21,
30282
+ lstatSync as lstatSync22,
30136
30283
  openSync as openSync10,
30137
30284
  readdirSync as readdirSync4,
30138
30285
  readlinkSync,
30139
30286
  readSync as readSync6,
30140
- realpathSync as realpathSync12
30287
+ realpathSync as realpathSync13
30141
30288
  } from "node:fs";
30142
30289
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
30143
- 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";
30144
30291
  var NAMES_BYTES = 64 * 1024 * 1024;
30145
30292
  var SYNC_MS = 30000;
30146
30293
  var READ_MS = 120000;
@@ -30155,7 +30302,7 @@ class WorkflowRefusal extends ContractError {
30155
30302
  }
30156
30303
  }
30157
30304
  function gitRead(cwd, args) {
30158
- const r = spawnSync5("git", gitArguments(args), {
30305
+ const r = spawnSync6("git", gitArguments(args), {
30159
30306
  cwd,
30160
30307
  env: gitEnvironment(),
30161
30308
  encoding: "utf8",
@@ -30168,7 +30315,7 @@ function gitRead(cwd, args) {
30168
30315
  return r.stdout;
30169
30316
  }
30170
30317
  function gitAnswer(cwd, args) {
30171
- const r = spawnSync5("git", gitArguments(args), {
30318
+ const r = spawnSync6("git", gitArguments(args), {
30172
30319
  cwd,
30173
30320
  env: gitEnvironment(),
30174
30321
  encoding: "utf8",
@@ -30224,20 +30371,20 @@ async function gitHead(cwd) {
30224
30371
  return (await gitText(cwd, ["rev-parse", "--verify", "HEAD"])).trim();
30225
30372
  }
30226
30373
  function contains2(root, path) {
30227
- const within = relative8(root, path);
30228
- return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute14(within);
30374
+ const within2 = relative9(root, path);
30375
+ return !within2 || !within2.startsWith(`..${sep8}`) && within2 !== ".." && !isAbsolute15(within2);
30229
30376
  }
30230
30377
  function nested(a, b) {
30231
30378
  return contains2(a, b) || contains2(b, a);
30232
30379
  }
30233
30380
  function safeWorkflowFile(cwd, name) {
30234
30381
  workflowPath(name);
30235
- const p = resolve12(cwd, name);
30236
- if (relative8(cwd, p).startsWith(".."))
30382
+ const p = resolve13(cwd, name);
30383
+ if (relative9(cwd, p).startsWith(".."))
30237
30384
  throw new ContractError("forbidden");
30238
30385
  safeDirectory(dirname21(p));
30239
30386
  try {
30240
- const st = lstatSync21(p);
30387
+ const st = lstatSync22(p);
30241
30388
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
30242
30389
  throw new ContractError("forbidden");
30243
30390
  } catch (e) {
@@ -30248,12 +30395,12 @@ function safeWorkflowFile(cwd, name) {
30248
30395
  }
30249
30396
  function declaredTarget(cwd, name) {
30250
30397
  workflowPath(name);
30251
- const p = resolve12(cwd, name);
30252
- if (relative8(cwd, p).startsWith(".."))
30398
+ const p = resolve13(cwd, name);
30399
+ if (relative9(cwd, p).startsWith(".."))
30253
30400
  throw new ContractError("forbidden");
30254
30401
  safeDirectory(dirname21(p));
30255
30402
  try {
30256
- const st = lstatSync21(p);
30403
+ const st = lstatSync22(p);
30257
30404
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
30258
30405
  throw new ContractError("forbidden");
30259
30406
  } catch (e) {
@@ -30279,7 +30426,7 @@ function fileIdentity(p, st, hashBytes) {
30279
30426
  return quick;
30280
30427
  let fd;
30281
30428
  try {
30282
- fd = openSync10(p, constants9.O_RDONLY | (constants9.O_NOFOLLOW ?? 0));
30429
+ fd = openSync10(p, constants10.O_RDONLY | (constants10.O_NOFOLLOW ?? 0));
30283
30430
  } catch (e) {
30284
30431
  if (absent2(e))
30285
30432
  return null;
@@ -30304,7 +30451,7 @@ async function fileIdentityAsync(p, st, hashBytes, signal) {
30304
30451
  return quick;
30305
30452
  let handle;
30306
30453
  try {
30307
- 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));
30308
30455
  } catch (e) {
30309
30456
  if (absent2(e))
30310
30457
  return null;
@@ -30343,13 +30490,13 @@ function directoryIdentity(root, name) {
30343
30490
  continue;
30344
30491
  if (++count2 > DIRECTORY_ENTRIES)
30345
30492
  throw tooLarge(name);
30346
- const full = join37(directory2, entry), relative9 = `${prefix}${entry}`;
30347
- const st = lstatSync21(full);
30493
+ const full = join38(directory2, entry), relative10 = `${prefix}${entry}`;
30494
+ const st = lstatSync22(full);
30348
30495
  if (st.isDirectory()) {
30349
- rows.push(`${relative9}/`);
30350
- visit(full, `${relative9}/`);
30496
+ rows.push(`${relative10}/`);
30497
+ visit(full, `${relative10}/`);
30351
30498
  } else
30352
- rows.push(`${relative9}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
30499
+ rows.push(`${relative10}\x00${fileIdentity(full, st, DIRECTORY_HASH_BYTES)}`);
30353
30500
  }
30354
30501
  };
30355
30502
  visit(root, "");
@@ -30367,13 +30514,13 @@ async function directoryIdentityAsync(root, name, contentOnly = false, signal) {
30367
30514
  continue;
30368
30515
  if (++count2 > DIRECTORY_ENTRIES)
30369
30516
  throw tooLarge(name);
30370
- const full = join37(directory2, entry), relative9 = `${prefix}${entry}`;
30517
+ const full = join38(directory2, entry), relative10 = `${prefix}${entry}`;
30371
30518
  const st = await lstat(full);
30372
30519
  if (st.isDirectory()) {
30373
- rows.push(`${relative9}/`);
30374
- await visit(full, `${relative9}/`);
30520
+ rows.push(`${relative10}/`);
30521
+ await visit(full, `${relative10}/`);
30375
30522
  } else
30376
- 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)}`);
30377
30524
  }
30378
30525
  };
30379
30526
  await visit(root, "");
@@ -30381,12 +30528,12 @@ async function directoryIdentityAsync(root, name, contentOnly = false, signal) {
30381
30528
  `))}`;
30382
30529
  }
30383
30530
  function pathIdentity(cwd, name, walk = true) {
30384
- const p = resolve12(cwd, name);
30385
- if (relative8(cwd, p).startsWith(".."))
30531
+ const p = resolve13(cwd, name);
30532
+ if (relative9(cwd, p).startsWith(".."))
30386
30533
  throw new ContractError("forbidden");
30387
30534
  let st;
30388
30535
  try {
30389
- st = lstatSync21(p);
30536
+ st = lstatSync22(p);
30390
30537
  } catch (e) {
30391
30538
  if (absent2(e))
30392
30539
  return null;
@@ -30399,8 +30546,8 @@ function pathIdentity(cwd, name, walk = true) {
30399
30546
  async function pathIdentityAsync(cwd, name, contentOnly = false, signal) {
30400
30547
  if (signal?.aborted)
30401
30548
  throw new ContractError("stale");
30402
- const p = resolve12(cwd, name);
30403
- if (relative8(cwd, p).startsWith(".."))
30549
+ const p = resolve13(cwd, name);
30550
+ if (relative9(cwd, p).startsWith(".."))
30404
30551
  throw new ContractError("forbidden");
30405
30552
  let st;
30406
30553
  try {
@@ -30508,8 +30655,8 @@ async function committedPaths(cwd, from, to) {
30508
30655
  ])).sort();
30509
30656
  }
30510
30657
  function repositoryIdentity(cwd) {
30511
- const repository = realpathSync12(resolve12(cwd, gitRead(cwd, ["rev-parse", "--git-common-dir"]).replace(/\r?\n$/u, "")));
30512
- 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);
30513
30660
  if (!st.isDirectory())
30514
30661
  throw new ContractError("stale");
30515
30662
  return {
@@ -30530,12 +30677,12 @@ function deliveryTarget(cwd, source) {
30530
30677
  "index.lock",
30531
30678
  "HEAD.lock"
30532
30679
  ]) {
30533
- if (existsSync4(join37(gitDir, name)))
30680
+ if (existsSync4(join38(gitDir, name)))
30534
30681
  throw new WorkflowRefusal("conflict", "Finish the existing Git operation before planning isolated delivery.");
30535
30682
  }
30536
30683
  return {
30537
30684
  ...repositoryIdentity(cwd),
30538
- checkoutRoot: realpathSync12(cwd),
30685
+ checkoutRoot: realpathSync13(cwd),
30539
30686
  head: source.head,
30540
30687
  branch: source.branch
30541
30688
  };
@@ -30656,14 +30803,14 @@ function snapshotChanges(before, after) {
30656
30803
  async function assertWorktree(root, cwd) {
30657
30804
  if (!safeDirectory(cwd))
30658
30805
  throw new ContractError("stale");
30659
- const real = (p) => realpathSync12(resolve12(p));
30806
+ const real = (p) => realpathSync13(resolve13(p));
30660
30807
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
30661
30808
  throw new ContractError("stale");
30662
- 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()));
30663
30810
  if (await common(root) !== await common(cwd))
30664
30811
  throw new ContractError("stale");
30665
- const marker2 = resolve12(cwd, ".git");
30666
- 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: "))
30667
30814
  throw new ContractError("stale");
30668
30815
  }
30669
30816
 
@@ -30787,7 +30934,7 @@ function readKnowledgeStore(root) {
30787
30934
  let names3 = [];
30788
30935
  try {
30789
30936
  const directory2 = dirname22(safeWorkflowFile(root, `${KNOWLEDGE_STORE.topics}/index.md`));
30790
- if (lstatSync22(directory2).isDirectory()) {
30937
+ if (lstatSync23(directory2).isDirectory()) {
30791
30938
  const dir = opendirSync12(directory2);
30792
30939
  try {
30793
30940
  for (let e = dir.readSync();e; e = dir.readSync()) {
@@ -30834,7 +30981,7 @@ function fileHas(root, path, symbol) {
30834
30981
  return !!file && (symbol === null || file.body.includes(symbol));
30835
30982
  }
30836
30983
  try {
30837
- const stat = lstatSync22(safeWorkflowFile(root, path));
30984
+ const stat = lstatSync23(safeWorkflowFile(root, path));
30838
30985
  if (!stat.isFile() && !stat.isDirectory())
30839
30986
  return false;
30840
30987
  if (symbol === null)
@@ -31064,8 +31211,8 @@ function readKnowledgeFile(root, path) {
31064
31211
  let fd;
31065
31212
  try {
31066
31213
  const file = safeWorkflowFile(root, path);
31067
- const selected2 = lstatSync23(file);
31068
- 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));
31069
31216
  const before = fstatSync8(fd);
31070
31217
  if (selected2.dev !== before.dev || selected2.ino !== before.ino)
31071
31218
  return null;
@@ -31080,7 +31227,7 @@ function readKnowledgeFile(root, path) {
31080
31227
  bytes += n;
31081
31228
  }
31082
31229
  const after = fstatSync8(fd);
31083
- const located = lstatSync23(file);
31230
+ const located = lstatSync24(file);
31084
31231
  if (located.dev !== before.dev || located.ino !== before.ino)
31085
31232
  return null;
31086
31233
  if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
@@ -31570,7 +31717,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31570
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}`);
31571
31718
  let published;
31572
31719
  try {
31573
- published = this.o.workflows.command(randomUUID24(), epoch, {
31720
+ published = this.o.workflows.command(randomUUID25(), epoch, {
31574
31721
  action: "propose",
31575
31722
  plan,
31576
31723
  model: model2
@@ -31606,7 +31753,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31606
31753
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
31607
31754
  if (busy.length)
31608
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.`);
31609
- const id = randomUUID24(), conversationId = current2.state.id;
31756
+ const id = randomUUID25(), conversationId = current2.state.id;
31610
31757
  try {
31611
31758
  this.o.workflows.command(id, epoch, {
31612
31759
  action: "research",
@@ -31634,7 +31781,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31634
31781
  approval(c, caller) {
31635
31782
  if (!caller)
31636
31783
  throw new ContractError("forbidden");
31637
- 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`);
31638
31785
  let effects = true;
31639
31786
  try {
31640
31787
  effects = this.o.owner.state !== "idle";
@@ -31694,7 +31841,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31694
31841
  });
31695
31842
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
31696
31843
  throw new ContractError("unavailable");
31697
- const g = prepared.response, grant2 = randomUUID24();
31844
+ const g = prepared.response, grant2 = randomUUID25();
31698
31845
  this.grants.set(grant2, {
31699
31846
  caller: canonicalJson(caller),
31700
31847
  revision: c.revision,
@@ -31760,9 +31907,9 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
31760
31907
  }
31761
31908
 
31762
31909
  // src/service/conversations.ts
31763
- import { randomUUID as randomUUID25 } from "node:crypto";
31764
- import { opendirSync as opendirSync14, statfsSync as statfsSync2 } from "node:fs";
31765
- 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";
31766
31913
  var META_BYTES2 = 64 * 1024;
31767
31914
  var PREVIEW_BYTES = 64 * 1024;
31768
31915
  var RECENT_PREVIEWS = 8;
@@ -32000,7 +32147,7 @@ class Conversations {
32000
32147
  }
32001
32148
  assertSettled() {
32002
32149
  this.o.owner.lease.assert();
32003
- const sessions = join39(this.records.root, "sessions");
32150
+ const sessions = join40(this.records.root, "sessions");
32004
32151
  if (!this.files.directory(sessions))
32005
32152
  return;
32006
32153
  const dir = opendirSync14(sessions);
@@ -32071,7 +32218,7 @@ class Conversations {
32071
32218
  throw new ContractError("invalid");
32072
32219
  if (input.images?.length && !this.o.models.catalog().entries.some((m) => m.provider === execution.model?.provider && m.model === execution.model?.model && m.images))
32073
32220
  throw new ContractError("unsupported-context");
32074
- const space = statfsSync2(this.o.coordination.directory);
32221
+ const space = statfsSync3(this.o.coordination.directory);
32075
32222
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
32076
32223
  throw new ContractError("capacity");
32077
32224
  const listed = session ? this.records.sessions.find(input.conversationId) : undefined;
@@ -32088,8 +32235,8 @@ class Conversations {
32088
32235
  const runtime = control?.reply || !execution.model ? undefined : this.o.models.workerSettings(execution.cwd, execution.model);
32089
32236
  const abort = new AbortController;
32090
32237
  let begin;
32091
- const ready2 = new Promise((resolve13) => {
32092
- begin = resolve13;
32238
+ const ready2 = new Promise((resolve14) => {
32239
+ begin = resolve14;
32093
32240
  });
32094
32241
  const live2 = {
32095
32242
  coordinator: !!control,
@@ -32179,7 +32326,7 @@ class Conversations {
32179
32326
  const session = this.records.sessions.session(request3.conversationId);
32180
32327
  if (live2.inputs.length >= RUN_INPUTS || live2.inputs.filter((input2) => !input2.withdrawn && !session?.delivered(input2.commandId)).length >= WAITING_INPUTS)
32181
32328
  throw new ContractError("capacity");
32182
- const space = statfsSync2(this.o.coordination.directory);
32329
+ const space = statfsSync3(this.o.coordination.directory);
32183
32330
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
32184
32331
  throw new ContractError("capacity");
32185
32332
  const index = this.records.index(request3.conversationId);
@@ -32250,14 +32397,14 @@ class Conversations {
32250
32397
  let waiting = input.withdrawal;
32251
32398
  if (!waiting) {
32252
32399
  let answer;
32253
- const result = new Promise((resolve13, reject) => {
32400
+ const result = new Promise((resolve14, reject) => {
32254
32401
  answer = (removed) => {
32255
32402
  input.withdrawal = undefined;
32256
32403
  try {
32257
32404
  if (!removed)
32258
32405
  throw new ContractError("conflict");
32259
32406
  this.withdraw(input);
32260
- resolve13();
32407
+ resolve14();
32261
32408
  } catch (error) {
32262
32409
  reject(error);
32263
32410
  }
@@ -32418,10 +32565,10 @@ class Conversations {
32418
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.";
32419
32566
  const request3 = decodeWorkerPublicRequest({
32420
32567
  protocol: 2,
32421
- taskId: randomUUID25(),
32568
+ taskId: randomUUID26(),
32422
32569
  taskKind: control ? "research" : "code",
32423
32570
  runId: commandId,
32424
- childRunId: randomUUID25(),
32571
+ childRunId: randomUUID26(),
32425
32572
  assignmentId: "conversation",
32426
32573
  purpose: control ? "research" : "edit",
32427
32574
  model: selected2,
@@ -32439,7 +32586,7 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
32439
32586
  runtime: live2.runtime,
32440
32587
  request: request3,
32441
32588
  cwd: live2.execution.cwd,
32442
- operationId: randomUUID25(),
32589
+ operationId: randomUUID26(),
32443
32590
  epoch: live2.epoch,
32444
32591
  signal: abort.signal,
32445
32592
  current: current2,
@@ -32579,16 +32726,16 @@ CONVERSATION CONTEXT (data): cwd ${live2.execution.cwd}; checkout root ${live2.e
32579
32726
  }
32580
32727
 
32581
32728
  // src/service/workflows.ts
32582
- import { randomUUID as randomUUID27 } from "node:crypto";
32583
- import { opendirSync as opendirSync16, realpathSync as realpathSync13, statfsSync as statfsSync3, writeFileSync as writeFileSync6 } from "node:fs";
32584
- 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";
32585
32732
  import { fileURLToPath as fileURLToPath7 } from "node:url";
32586
32733
 
32587
32734
  // src/task-diff.ts
32588
- import { spawnSync as spawnSync6 } from "node:child_process";
32735
+ import { spawnSync as spawnSync7 } from "node:child_process";
32589
32736
  import { createHash as createHash31 } from "node:crypto";
32590
- import { lstatSync as lstatSync24, readdirSync as readdirSync5, readlinkSync as readlinkSync2 } from "node:fs";
32591
- 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";
32592
32739
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
32593
32740
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
32594
32741
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -32607,7 +32754,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32607
32754
  if (Date.now() >= deadline)
32608
32755
  outcome = "time budget exhausted";
32609
32756
  else {
32610
- const result = spawnSync6("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
32757
+ const result = spawnSync7("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
32611
32758
  cwd: root,
32612
32759
  encoding: "buffer",
32613
32760
  timeout: Math.max(1, deadline - Date.now()),
@@ -32631,8 +32778,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32631
32778
  return;
32632
32779
  }
32633
32780
  try {
32634
- const path = join40(root, name);
32635
- const st = lstatSync24(path);
32781
+ const path = join41(root, name);
32782
+ const st = lstatSync25(path);
32636
32783
  add(name, `${st.mode}:${st.size}`);
32637
32784
  if (st.isSymbolicLink()) {
32638
32785
  add(name, readlinkSync2(path));
@@ -32657,7 +32804,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
32657
32804
  limits.push(`Unreadable/changing: ${name}`);
32658
32805
  }
32659
32806
  };
32660
- const probe2 = spawnSync6("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
32807
+ const probe2 = spawnSync7("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
32661
32808
  cwd: root,
32662
32809
  env: gitEnvironment(),
32663
32810
  timeout: 3000,
@@ -32772,8 +32919,8 @@ ${data2.toString("utf8")}`);
32772
32919
  return;
32773
32920
  }
32774
32921
  for (const name of names3) {
32775
- const path = join40(dir, name);
32776
- const rel = relative9(root, path).split("\\").join("/");
32922
+ const path = join41(dir, name);
32923
+ const rel = relative10(root, path).split("\\").join("/");
32777
32924
  if (rel === ".git" || admin(rel))
32778
32925
  continue;
32779
32926
  if (++fileCount > 2000 || Date.now() >= deadline) {
@@ -32781,7 +32928,7 @@ ${data2.toString("utf8")}`);
32781
32928
  break;
32782
32929
  }
32783
32930
  try {
32784
- const st = lstatSync24(path);
32931
+ const st = lstatSync25(path);
32785
32932
  if (st.isDirectory())
32786
32933
  walk(path, depth + 1);
32787
32934
  else
@@ -32807,15 +32954,15 @@ ${data2.toString("utf8")}`);
32807
32954
  }
32808
32955
 
32809
32956
  // src/worker-workspace.mjs
32810
- 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";
32811
32958
  function withinRoot(root, path) {
32812
- const part = relative10(root, path);
32813
- return part === "" || !isAbsolute15(part) && part !== ".." && !part.startsWith(`..${sep8}`);
32959
+ const part = relative11(root, path);
32960
+ return part === "" || !isAbsolute16(part) && part !== ".." && !part.startsWith(`..${sep9}`);
32814
32961
  }
32815
32962
  var absolute2 = (value) => {
32816
- if (typeof value !== "string" || !isAbsolute15(value) || value.includes("\x00"))
32963
+ if (typeof value !== "string" || !isAbsolute16(value) || value.includes("\x00"))
32817
32964
  throw new Error("Invalid execution directory");
32818
- return resolve13(value);
32965
+ return resolve14(value);
32819
32966
  };
32820
32967
  function executionDirectory(execution, tree) {
32821
32968
  const origin = absolute2(execution.checkoutRoot);
@@ -32823,12 +32970,12 @@ function executionDirectory(execution, tree) {
32823
32970
  tree = absolute2(tree);
32824
32971
  if (!withinRoot(origin, cwd))
32825
32972
  throw new Error("Execution cwd escaped its checkout");
32826
- return resolve13(tree, relative10(origin, cwd));
32973
+ return resolve14(tree, relative11(origin, cwd));
32827
32974
  }
32828
32975
 
32829
32976
  // src/service/investigations.ts
32830
32977
  import { createHash as createHash32 } from "node:crypto";
32831
- import { readFileSync as readFileSync7, statSync as statSync3 } from "node:fs";
32978
+ import { readFileSync as readFileSync7, statSync as statSync4 } from "node:fs";
32832
32979
  var INVESTIGATIONS = {
32833
32980
  cited: 32,
32834
32981
  examined: 256,
@@ -32840,7 +32987,7 @@ function fileDigest(root, path) {
32840
32987
  if (!workflowBoundary(path))
32841
32988
  return null;
32842
32989
  const file = safeWorkflowFile(root, path);
32843
- const st = statSync3(file);
32990
+ const st = statSync4(file);
32844
32991
  if (!st.isFile() || st.size > INVESTIGATIONS.fileBytes)
32845
32992
  return null;
32846
32993
  return createHash32("sha256").update(readFileSync7(file)).digest("hex");
@@ -32883,9 +33030,11 @@ var RECOVERY_BYTES = 32768;
32883
33030
 
32884
33031
  class AttemptFailure extends Error {
32885
33032
  steps;
32886
- constructor(message2, steps) {
33033
+ identity;
33034
+ constructor(message2, steps, identity2) {
32887
33035
  super(message2);
32888
33036
  this.steps = steps;
33037
+ this.identity = identity2;
32889
33038
  }
32890
33039
  }
32891
33040
 
@@ -32984,7 +33133,7 @@ function decodeRecoveryDecision(reply, bounds, secrets = []) {
32984
33133
  const route = has("route") ? nullable(o.route, (value) => {
32985
33134
  const given = (key2) => Object.hasOwn(value ?? {}, key2);
32986
33135
  const r = closed(value, ["drop", "add"].filter(given));
32987
- const within = [...bounds.route?.scope ?? bounds.scope, ...scope];
33136
+ const within2 = [...bounds.route?.scope ?? bounds.scope, ...scope];
32988
33137
  return {
32989
33138
  drop: given("drop") ? list(r.drop, WORKFLOW_LIMITS.route, (v) => text(v, 64, true)) : [],
32990
33139
  add: given("add") ? list(r.add, WORKFLOW_LIMITS.tasks, (entry) => {
@@ -32996,7 +33145,7 @@ function decodeRecoveryDecision(reply, bounds, secrets = []) {
32996
33145
  "after"
32997
33146
  ]);
32998
33147
  const writes = list(t.writes, 128, (v) => workflowPath(v, true));
32999
- 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))
33000
33149
  refuse3("An added assignment writes outside the run's write scope; list the additional paths in scope");
33001
33150
  const after = list(t.after, WORKFLOW_LIMITS.tasks, (v) => text(v, 64, true));
33002
33151
  if (new Set(after).size !== after.length)
@@ -33099,36 +33248,39 @@ class DeliveryController {
33099
33248
  async complete(stage, action) {
33100
33249
  let repair = [];
33101
33250
  let recorded = 0;
33251
+ let failure2;
33252
+ let original;
33102
33253
  let floor = "repair";
33103
33254
  for (;; ) {
33104
33255
  this.ports.assertRunning();
33105
33256
  try {
33106
33257
  while (repair.length) {
33107
- await this.ports.execute(repair[0], recorded);
33258
+ if (!failure2)
33259
+ throw new Error("Recovery has no original failure");
33260
+ await this.ports.execute(repair[0], recorded, failure2);
33108
33261
  repair.shift();
33109
33262
  }
33110
33263
  return await action();
33111
33264
  } catch (error) {
33112
33265
  if (!(error instanceof AttemptFailure))
33113
33266
  throw error;
33267
+ if (!repair.length)
33268
+ original = error;
33269
+ const attempt2 = repair.length && original ? new AttemptFailure(error.message, [...new Set([...original.steps, ...error.steps])], `${original.identity ?? stage}:repair:${error.identity ?? "incomplete"}`) : error;
33270
+ failure2 = attempt2;
33114
33271
  this.ports.assertRunning();
33115
33272
  const observation = await this.ports.observe();
33116
33273
  let decision;
33117
33274
  for (;; ) {
33118
- decision = await this.decide(error, floor);
33275
+ decision = await this.decide(attempt2, floor);
33119
33276
  this.ports.assertRunning();
33120
33277
  if (decision.action === "blocked")
33121
33278
  break;
33122
33279
  const fingerprint2 = createHash33("sha256").update(canonicalJson({
33123
33280
  stage,
33124
33281
  observation,
33125
- failure: error.message.replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/gu, "<step>"),
33126
- level: decision.level,
33127
- strategy: decision.strategy.trim().toLowerCase(),
33128
- work: decision.work,
33129
- scope: decision.scope,
33130
- route: decision.route,
33131
- deviation: decision.deviation
33282
+ failure: attempt2.identity ?? attempt2.message.replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/gu, "<step>"),
33283
+ level: decision.level
33132
33284
  })).digest("hex");
33133
33285
  if (!this.tried.has(fingerprint2)) {
33134
33286
  this.tried.add(fingerprint2);
@@ -33143,7 +33295,7 @@ class DeliveryController {
33143
33295
  revision: ++this.revision,
33144
33296
  stage,
33145
33297
  observation,
33146
- failure: error.message,
33298
+ failure: attempt2.message,
33147
33299
  decision
33148
33300
  };
33149
33301
  recorded = this.ports.record(record3);
@@ -33163,7 +33315,7 @@ Choose the least departure that can work:
33163
33315
  - level "replan": a different implementation or split of the remaining work; list in "scope" any further repository files it must write. Files edited outside the scope so far are either adopted this way, when the goal needs them, or restored by a work item. While assignments are still waiting to start you may also revise them in "route": drop one that the new approach makes wrong or unnecessary, add one, or give one again under its own ID to rewrite it. An assignment that already started cannot change; what remains of the failed one is your work items. Every assignment that waits for a dropped one must be dropped or rewritten too.
33164
33316
  - level "deviate": only when an acceptance item or decision cannot be met as written. Deliver the closest achievable result and record the deviation: the item, the evidence it is impossible, what is delivered instead, and in "waives" any declared check that can no longer pass because of it. An independent review must find it necessary and minimal, and it leads the final report.
33165
33317
  Use action "blocked" only for a condition outside the repository that no route can remove, and name it in "blocker": an unavailable model, failed authentication, storage or permission limits, a target branch changed from outside, an installation this agreement does not allow, or a missing tool. A hard problem is not a blocker.
33166
- Every continuation needs a reason grounded in new evidence or a different approach, not another copy of a failed attempt. Model-request recovery belongs to the SDK and is never permission to replay a workflow step. The owner will run the acceptance checks and independent review again.
33318
+ The execution context supplied with evidence is authoritative about what ran and where. Project guidance that applies only when a resource was declared does not create a missing resource requirement: do not demand an original temporary directory or marker unless the approved commands actually declared one. Never ask a repair worker to obtain undisclosed owner records, inspect private state or reconstruct the owner environment. Strategy text is explanation only; executable repair actions must be in work. A repair that reports partial progress does not resolve the original failure. Rewording a strategy or work instructions is not progress: the same failed operation with unchanged observed state escalates. Every continuation needs new evidence or an actionable changed approach, not another copy of a failed attempt. Model-request recovery belongs to the SDK and is never permission to replay a workflow step. The owner will run the acceptance checks and independent review again.
33167
33319
  ${REPLY}`;
33168
33320
  function modelRequestFailed(output) {
33169
33321
  for (const line of output.split(`
@@ -33208,8 +33360,8 @@ function settledWorkerCleanup(output) {
33208
33360
  }
33209
33361
 
33210
33362
  // src/service/workflow-delivery.ts
33211
- import { lstatSync as lstatSync25, rmdirSync } from "node:fs";
33212
- 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";
33213
33365
  function taskBranch(goal, id) {
33214
33366
  const slug2 = goal.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "").slice(0, 48).replace(/-$/u, "") || "task";
33215
33367
  return `refs/heads/cadence/${slug2}-${decodeId(id)}`;
@@ -33218,7 +33370,7 @@ function deliveryObservation(binding2, root, id, goal) {
33218
33370
  return {
33219
33371
  binding: binding2,
33220
33372
  taskBranch: taskBranch(goal, id),
33221
- worktreeRoot: join41(root, decodeId(id), "integration"),
33373
+ worktreeRoot: join42(root, decodeId(id), "integration"),
33222
33374
  preparation: "pending",
33223
33375
  workspace: null,
33224
33376
  candidate: null,
@@ -33267,7 +33419,7 @@ class WorkflowDelivery {
33267
33419
  for (const path of [dirname25(dirname25(this.home)), dirname25(this.home)]) {
33268
33420
  if (!safeDirectory(path, true))
33269
33421
  throw new ContractError("forbidden");
33270
- const stat = lstatSync25(path);
33422
+ const stat = lstatSync26(path);
33271
33423
  if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || process.getuid && stat.uid !== process.getuid()))
33272
33424
  throw new ContractError("forbidden");
33273
33425
  }
@@ -33307,7 +33459,7 @@ class WorkflowDelivery {
33307
33459
  return path;
33308
33460
  }
33309
33461
  childPath(id) {
33310
- return join41(this.home, "tasks", id);
33462
+ return join42(this.home, "tasks", id);
33311
33463
  }
33312
33464
  child(path) {
33313
33465
  return this.view.artifacts?.find((a) => a.path === path && this.children.has(path));
@@ -33502,8 +33654,8 @@ class WorkflowDelivery {
33502
33654
  }
33503
33655
 
33504
33656
  // src/service/workflow-history.ts
33505
- import { randomUUID as randomUUID26 } from "node:crypto";
33506
- 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";
33507
33659
  class WorkflowHistoryScanner {
33508
33660
  path;
33509
33661
  directory;
@@ -33514,7 +33666,7 @@ class WorkflowHistoryScanner {
33514
33666
  this.directory = directory2;
33515
33667
  }
33516
33668
  incarnation() {
33517
- const st = lstatSync26(this.path, { bigint: true });
33669
+ const st = lstatSync27(this.path, { bigint: true });
33518
33670
  if (!st.isDirectory() || st.isSymbolicLink())
33519
33671
  throw new ContractError("corrupt-selected");
33520
33672
  return `${st.dev}:${st.ino}`;
@@ -33566,7 +33718,7 @@ class WorkflowHistoryScanner {
33566
33718
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
33567
33719
  state.ids.pop();
33568
33720
  }
33569
- const scan = randomUUID26();
33721
+ const scan = randomUUID27();
33570
33722
  state.timer = setTimeout(() => {
33571
33723
  this.scans.delete(scan);
33572
33724
  try {
@@ -33824,7 +33976,7 @@ function implementationReport(reply, secrets = []) {
33824
33976
  "summary",
33825
33977
  ...Object.hasOwn(raw ?? {}, "lessons") ? ["lessons"] : []
33826
33978
  ]);
33827
- if (o.status !== "completed" && o.status !== "blocked")
33979
+ if (o.status !== "completed" && o.status !== "partial" && o.status !== "blocked")
33828
33980
  return null;
33829
33981
  if (typeof o.summary !== "string" || !o.summary.trim())
33830
33982
  return null;
@@ -33868,6 +34020,8 @@ class WorkflowTranscript {
33868
34020
  trackReport(frame) {
33869
34021
  const e = frame.event;
33870
34022
  if (e.kind === "tool-start") {
34023
+ if (["read", "grep", "find", "ls", "changes"].includes(e.name))
34024
+ return;
33871
34025
  this.reportText = undefined;
33872
34026
  this.reportDetails.clear();
33873
34027
  this.reportCapture = undefined;
@@ -34017,7 +34171,7 @@ function excerpt(value, budget) {
34017
34171
  }
34018
34172
  return take(low);
34019
34173
  }
34020
- function boundedResult(value, [textKey, outputKey, truncatedKey]) {
34174
+ function boundedResult(value, [textKey, outputKey, truncatedKey], maximum = WORKFLOW_RESULT_BYTES) {
34021
34175
  if (!value || typeof value !== "object" || Array.isArray(value))
34022
34176
  throw new ContractError("corrupt-selected");
34023
34177
  const original = value;
@@ -34030,7 +34184,7 @@ function boundedResult(value, [textKey, outputKey, truncatedKey]) {
34030
34184
  [outputKey]: "",
34031
34185
  [truncatedKey]: false
34032
34186
  };
34033
- const budget = WORKFLOW_RESULT_BYTES - Buffer.byteLength(JSON.stringify(result));
34187
+ const budget = maximum - Buffer.byteLength(JSON.stringify(result));
34034
34188
  if (budget < 0)
34035
34189
  throw new ContractError("oversize");
34036
34190
  const keptText = excerpt(text2, budget);
@@ -34051,7 +34205,8 @@ function workflowResultDetail(value, secrets) {
34051
34205
  const record3 = JSON.parse(sanitizeData(value, secrets));
34052
34206
  const resultKey = sanitizeText("result", secrets);
34053
34207
  const keys2 = ["text", "output", "truncated"].map((key2) => sanitizeText(key2, secrets));
34054
- const result = boundedResult(record3[resultKey], keys2);
34208
+ const wrapper = Buffer.byteLength(JSON.stringify({ ...record3, [resultKey]: null })) - 4;
34209
+ const result = boundedResult(record3[resultKey], keys2, Math.min(WORKFLOW_RESULT_BYTES, 256 * 1024 - wrapper));
34055
34210
  record3[resultKey] = result;
34056
34211
  return {
34057
34212
  text: canonicalJson(record3, 256 * 1024),
@@ -34060,9 +34215,11 @@ function workflowResultDetail(value, secrets) {
34060
34215
  }
34061
34216
 
34062
34217
  // src/service/workflows.ts
34218
+ var runtimeSummary = (runtime) => `${describeWorkerRuntime(runtime)}
34219
+ ${RUN_ENVIRONMENT_POLICY}`;
34063
34220
  var OWNER_RUNTIME = Object.freeze({
34064
- version: "2.1.3",
34065
- build: "636b05ac92cbf5b5afff8c298a69e9400a889064a9023e60d61c51928d5e1d86",
34221
+ version: "2.1.5",
34222
+ build: "f394594500c6c18cd7ae0d307db53bbfbf13f988bfd92f5e3ca1bbc15b0d5e91",
34066
34223
  entry: fileURLToPath7(import.meta.url),
34067
34224
  pid: process.pid,
34068
34225
  node: process.versions.node,
@@ -34138,7 +34295,7 @@ function clipBytes(value, maximum) {
34138
34295
  return Buffer.from(value).subarray(0, maximum).toString("utf8").replace(/�+$/u, "");
34139
34296
  }
34140
34297
  var LESSONS = 32;
34141
- var IMPLEMENTATION_REPORT = `After all tools, call cadence_report with status completed or blocked and a concrete summary of actual work and remaining gaps. Its optional lessons are for what this work taught that the code does not show and a later worker here would have to rediscover; usually there is none. Then give a short final answer. The report is not passing check evidence; the owner verifies and reviews independently. Never claim completion just because a tool exited zero.`;
34298
+ var IMPLEMENTATION_REPORT = `After the assigned work, call cadence_report with status completed, partial (useful outputs with remaining work), or blocked (a concrete unmet prerequisite) and a concrete summary of actual work and remaining gaps. Its optional lessons are for what this work taught that the code does not show and a later worker here would have to rediscover; usually there is none. Then give a short final answer. The report is not passing check evidence; the owner verifies and reviews independently. Never claim completion just because a tool exited zero.`;
34142
34299
 
34143
34300
  class Workflows {
34144
34301
  o;
@@ -34152,12 +34309,12 @@ class Workflows {
34152
34309
  constructor(o) {
34153
34310
  this.o = o;
34154
34311
  this.contexts = o.contexts ?? new ConversationContexts(o);
34155
- this.root = join42(o.coordination.directory, "workflows-v1");
34156
- this.cwd = realpathSync13(o.coordination.store.root);
34157
- this.worktreeRoot = join42(o.coordination.stateHome, "cadence-worktrees-v1", basename5(o.coordination.store.privateRoot));
34158
- 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"), () => {
34159
34316
  this.o.owner.lease.assert();
34160
- return this.files.directory(join42(this.root, "runs"));
34317
+ return this.files.directory(join43(this.root, "runs"));
34161
34318
  });
34162
34319
  this.recover();
34163
34320
  }
@@ -34165,7 +34322,7 @@ class Workflows {
34165
34322
  return this.o.coordination.files;
34166
34323
  }
34167
34324
  path(id, name) {
34168
- return join42(this.root, "runs", decodeId(id), name);
34325
+ return join43(this.root, "runs", decodeId(id), name);
34169
34326
  }
34170
34327
  write(path, value, expected, max = RECORD_BYTES3) {
34171
34328
  this.o.owner.lease.assert();
@@ -34182,7 +34339,7 @@ class Workflows {
34182
34339
  `), 2048, this.o.secrets());
34183
34340
  }
34184
34341
  recover() {
34185
- const runs = join42(this.root, "runs");
34342
+ const runs = join43(this.root, "runs");
34186
34343
  if (!this.files.directory(runs))
34187
34344
  return;
34188
34345
  const ids = [];
@@ -34261,10 +34418,11 @@ class Workflows {
34261
34418
  run.delivery.integration.status = "unknown";
34262
34419
  run.delivery.integration.reason = "Owner restarted during integration; observe the target, never replay.";
34263
34420
  }
34264
- run.delivery.cleanup = {
34265
- status: "retained",
34266
- reason: "Owner restarted; artifacts retained without replay or cleanup."
34267
- };
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
+ };
34268
34426
  if (run.delivery.workspace && run.delivery.workspace.state !== "removed")
34269
34427
  run.delivery.workspace.state = "retained";
34270
34428
  for (const child2 of run.delivery.artifacts ?? [])
@@ -34291,7 +34449,7 @@ class Workflows {
34291
34449
  throw new ContractError("quarantine");
34292
34450
  }
34293
34451
  floor() {
34294
- const space = statfsSync3(this.o.coordination.directory);
34452
+ const space = statfsSync4(this.o.coordination.directory);
34295
34453
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
34296
34454
  throw new ContractError("capacity");
34297
34455
  }
@@ -34317,7 +34475,7 @@ class Workflows {
34317
34475
  throw new ContractError("stale");
34318
34476
  safeDirectory(cwd, true);
34319
34477
  }
34320
- if (realpathSync13(cwd) !== cwd)
34478
+ if (realpathSync14(cwd) !== cwd)
34321
34479
  throw new ContractError("stale");
34322
34480
  return cwd;
34323
34481
  }
@@ -34332,6 +34490,7 @@ class Workflows {
34332
34490
  delivery,
34333
34491
  digest: hash(canonicalJson({
34334
34492
  runtime,
34493
+ environment: RUN_ENVIRONMENT_POLICY,
34335
34494
  source,
34336
34495
  delivery: delivery ?? null,
34337
34496
  working: plan.delivery === "working-copy" ? captureChanges(this.cwd).fingerprint : null
@@ -34339,7 +34498,7 @@ class Workflows {
34339
34498
  };
34340
34499
  }
34341
34500
  proposal(id) {
34342
- 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);
34343
34502
  if (!file)
34344
34503
  throw new ContractError("unavailable");
34345
34504
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3));
@@ -34356,7 +34515,7 @@ class Workflows {
34356
34515
  const observed = this.observation(p.plan, runtime);
34357
34516
  if (p.plan.delivery === "local-merge" && !p.delivery)
34358
34517
  throw new WorkflowRefusal("invalid", "Publish a new delivery agreement with explicit named-branch placement before execution.");
34359
- 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)))
34360
34519
  throw new ContractError("stale");
34361
34520
  return { source: observed.source, runtime };
34362
34521
  }
@@ -34565,8 +34724,8 @@ class Workflows {
34565
34724
  if (action === "prepare")
34566
34725
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
34567
34726
  if (action === "propose")
34568
- return !!this.files.read(join42(this.root, "proposals", `${id}.json`), RECORD_BYTES3);
34569
- 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));
34570
34729
  }
34571
34730
  admit(commandId, epoch, r, effect) {
34572
34731
  this.current();
@@ -34590,7 +34749,7 @@ class Workflows {
34590
34749
  checkoutRoot: this.cwd,
34591
34750
  observation: digest2,
34592
34751
  display: {
34593
- runtime: describeWorkerRuntime(runtime2),
34752
+ runtime: runtimeSummary(runtime2),
34594
34753
  model: `${selected2.provider}/${selected2.model} · ${selected2.thinking}`,
34595
34754
  branch: source.branch,
34596
34755
  baseCommit: source.head
@@ -34599,7 +34758,7 @@ class Workflows {
34599
34758
  };
34600
34759
  if (sanitizeData(p, secrets) !== canonicalJson(p))
34601
34760
  throw new ContractError("forbidden");
34602
- const target3 = join42(this.root, "proposals", `${commandId}.json`);
34761
+ const target3 = join43(this.root, "proposals", `${commandId}.json`);
34603
34762
  const previous = this.files.read(target3, RECORD_BYTES3);
34604
34763
  if (previous) {
34605
34764
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -34622,7 +34781,7 @@ class Workflows {
34622
34781
  this.grants.delete(key2);
34623
34782
  if (this.grants.size >= 16)
34624
34783
  throw new ContractError("capacity");
34625
- const grant = randomUUID27(), expiresAt = Date.now() + 120000;
34784
+ const grant = randomUUID28(), expiresAt = Date.now() + 120000;
34626
34785
  effect();
34627
34786
  this.grants.set(grant, {
34628
34787
  commandId,
@@ -34717,8 +34876,8 @@ class Workflows {
34717
34876
  };
34718
34877
  const abort = new AbortController;
34719
34878
  let begin;
34720
- const ready2 = new Promise((resolve15) => {
34721
- begin = resolve15;
34879
+ const ready2 = new Promise((resolve16) => {
34880
+ begin = resolve16;
34722
34881
  });
34723
34882
  const live2 = {
34724
34883
  runtime,
@@ -34764,7 +34923,7 @@ class Workflows {
34764
34923
  throw new ContractError("corrupt-selected");
34765
34924
  live2.file = this.write(this.path(live2.run.id, "state.json"), live2.run, live2.file);
34766
34925
  }
34767
- saveFinal(live2) {
34926
+ saveSettlement(live2) {
34768
34927
  const cause = live2.abort.signal.reason;
34769
34928
  if (live2.abort.signal.aborted && cause?.source)
34770
34929
  live2.run.notice = this.notice(live2.run.notice, `${cause.source}: ${cause.reason} (${live2.run.id})`);
@@ -34783,7 +34942,7 @@ class Workflows {
34783
34942
  assertRunning(live2) {
34784
34943
  this.current();
34785
34944
  this.floor();
34786
- 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))
34787
34946
  throw new ContractError("stale");
34788
34947
  }
34789
34948
  step(live2, id, kind, childRunId) {
@@ -34807,7 +34966,7 @@ class Workflows {
34807
34966
  live2.run.stepsBefore = offset + prefix.length;
34808
34967
  }
34809
34968
  const s = {
34810
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID27()}`,
34969
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID28()}`,
34811
34970
  ...childRunId ? { childRunId } : {},
34812
34971
  kind,
34813
34972
  ...childRunId ? {
@@ -34847,11 +35006,12 @@ class Workflows {
34847
35006
  sanitizeResult(result) {
34848
35007
  return workflowResult(result, this.o.secrets());
34849
35008
  }
34850
- finishStep(live2, s, original, preview, report2) {
35009
+ finishStep(live2, s, original, preview, report2, operation) {
34851
35010
  const result = this.sanitizeResult(original);
34852
35011
  this.write(this.path(live2.run.id, `results/${hash(s.id)}.json`), {
34853
35012
  stepId: s.id,
34854
- result
35013
+ result,
35014
+ ...operation ? { operation: JSON.parse(sanitizeData(operation, this.o.secrets())) } : {}
34855
35015
  });
34856
35016
  const shown2 = preview ?? (result.text || result.output);
34857
35017
  s.status = result.outcome;
@@ -34864,8 +35024,8 @@ class Workflows {
34864
35024
  s.text = diagnosticText(verdict ? verdict.approved ? `Agent review approved (automatic, not human review). ${verdict.summary}` : `Agent review rejected: ${[verdict.summary, ...verdict.blockingIssues].filter(Boolean).join(" | ") || "no reason given"}` : `Agent review reply could not be parsed as a verdict${result.truncated ? " (the reply was clipped)" : ""}; it is not counted as approval.`, 1024, this.o.secrets());
34865
35025
  }
34866
35026
  if (report2 !== undefined && result.outcome === "completed" && result.closed && result.exitCode === 0) {
34867
- s.status = report2?.status === "completed" ? "completed" : "failed";
34868
- s.text = diagnosticText(report2 ? report2.status === "blocked" ? `Assignment blocked: ${report2.summary}` : report2.summary : "Assignment did not submit a complete structured report; the owner will diagnose actual outputs.", 1024, this.o.secrets());
35027
+ s.status = report2?.status ?? "failed";
35028
+ s.text = diagnosticText(report2 ? report2.status !== "completed" ? `Assignment ${report2.status}: ${report2.summary}` : report2.summary : "Assignment did not submit a complete structured report; the owner will diagnose actual outputs.", 1024, this.o.secrets());
34869
35029
  }
34870
35030
  if (!result.closed)
34871
35031
  this.o.owner.quarantine();
@@ -34880,19 +35040,20 @@ class Workflows {
34880
35040
  if (cwd !== this.cwd)
34881
35041
  await live2.delivery?.assertTip(cwd);
34882
35042
  const runCwd = this.executionCwd(live2, cwd);
35043
+ const temporary = live2.environment?.forWorkspace(cwd);
34883
35044
  const role3 = loadAgentDefinitions().find((r) => r.role === (readonly ? kind === "diagnosis" ? "diagnosis-worker" : "design-explorer" : "implementation-worker"));
34884
35045
  if (!role3)
34885
35046
  throw new ContractError("unavailable");
34886
35047
  if (cwd !== this.cwd)
34887
35048
  await assertWorktree(this.cwd, cwd);
34888
- const childRunId = randomUUID27(), op = randomUUID27();
35049
+ const childRunId = randomUUID28(), op = randomUUID28();
34889
35050
  const plan = live2.proposal?.plan;
34890
- const baseContext = plan ? `${workflowContext(plan)}
34891
- Execution cwd: ${runCwd}
34892
- Checkout root: ${cwd}
34893
- 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.` : ""}`;
34894
35055
  const reader = await this.reader(live2, cwd, id, kind);
34895
- 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);
34896
35057
  if (live2.proposal) {
34897
35058
  live2.routed ??= new Set;
34898
35059
  for (const label of knowledge.routed)
@@ -34915,10 +35076,11 @@ Write paths are relative to the checkout root.` : "Read applicable project docum
34915
35076
  } : {},
34916
35077
  model: model2,
34917
35078
  role: { role: role3.role, sha256: role3.sha256 },
34918
- context: `${baseContext}
35079
+ context: knowledge.text ? `${baseContext}
34919
35080
 
34920
- ${knowledge.text}`,
35081
+ ${knowledge.text}` : baseContext,
34921
35082
  instructions: `${role3.content}
35083
+ ${placement}
34922
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.`,
34923
35085
  prompt: text(prompt, 32768, true),
34924
35086
  handoff: { graphRevision: 1, inputs: [] }
@@ -34962,6 +35124,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
34962
35124
  this.write(this.path(live2.run.id, `launches/${childRunId}.json`), {
34963
35125
  cwd: runCwd,
34964
35126
  runtime: live2.runtime ? describeWorkerRuntime(live2.runtime) : null,
35127
+ environment: temporary ?? null,
34965
35128
  knowledge: {
34966
35129
  sources: knowledge.sources.map(({ excerpt: _excerpt, ...source }) => source),
34967
35130
  omitted: knowledge.omitted
@@ -34987,7 +35150,8 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
34987
35150
  ]);
34988
35151
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, runCwd, live2.abort.signal, {
34989
35152
  ownerSecrets: this.o.secrets(),
34990
- 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],
34991
35155
  onLifecycle: (event) => {
34992
35156
  if (!step.timing)
34993
35157
  return;
@@ -35107,14 +35271,16 @@ Partial work is preserved.`);
35107
35271
  if (cwd !== this.cwd && shell)
35108
35272
  await assertWorktree(this.cwd, cwd);
35109
35273
  const runCwd = shell ? this.executionCwd(live2, cwd) : cwd;
35110
- const id = randomUUID27();
35274
+ const id = randomUUID28();
35111
35275
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
35112
35276
  cwd: runCwd,
35113
35277
  args: shell ? operation.check : operation.git
35114
35278
  });
35115
35279
  let native;
35280
+ const temporary = options.temporary ?? live2.environment?.forWorkspace(cwd);
35116
35281
  const environment2 = {
35117
35282
  ...this.o.checkEnvironment ?? {},
35283
+ ...temporary,
35118
35284
  CADENCE_SUBAGENT_CHILD: "1"
35119
35285
  };
35120
35286
  const running = Promise.resolve().then(() => runProcess({
@@ -35122,7 +35288,7 @@ Partial work is preserved.`);
35122
35288
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
35123
35289
  "--no-lazy-fetch",
35124
35290
  "-c",
35125
- `core.hooksPath=${join42(this.root, "empty-hooks")}`,
35291
+ `core.hooksPath=${join43(this.root, "empty-hooks")}`,
35126
35292
  "-c",
35127
35293
  "commit.gpgsign=false",
35128
35294
  "-c",
@@ -35133,7 +35299,7 @@ Partial work is preserved.`);
35133
35299
  ]),
35134
35300
  windowsVerbatimArguments: shell && process.platform === "win32" ? true : undefined,
35135
35301
  cwd: runCwd,
35136
- env: shell ? environment2 : gitEnvironment(),
35302
+ env: shell ? environment2 : { ...gitEnvironment(), ...temporary },
35137
35303
  retainOutput: true,
35138
35304
  stopTarget: id,
35139
35305
  signal: options.uninterruptible ? new AbortController().signal : live2.abort.signal,
@@ -35173,8 +35339,23 @@ Partial work is preserved.`);
35173
35339
  async check(live2, cwd, c, title) {
35174
35340
  const step = this.step(live2, title, "check");
35175
35341
  try {
35176
- const result = await this.run(live2, cwd, { check: c });
35177
- this.finishStep(live2, step, result);
35342
+ const runCwd = this.executionCwd(live2, cwd);
35343
+ const temporary = live2.environment?.forWorkspace(cwd);
35344
+ const result = await this.run(live2, cwd, { check: c }, { temporary });
35345
+ this.finishStep(live2, step, result, result.outcome === "completed" ? undefined : `${c.name} in ${runCwd}
35346
+ Command: ${c.command}
35347
+ ${result.output || result.text}`, undefined, {
35348
+ command: c,
35349
+ cwd: runCwd,
35350
+ checkoutRoot: cwd,
35351
+ placement: cwd === this.cwd ? "target" : cwd === live2.delivery?.view.worktreeRoot ? "candidate" : "child",
35352
+ target: live2.run.delivery?.binding.target ?? null,
35353
+ environment: Object.fromEntries(["TMPDIR", "TEMP", "TMP"].map((name) => [
35354
+ name,
35355
+ temporary?.[name] ?? this.o.checkEnvironment?.[name] ?? null
35356
+ ])),
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."
35358
+ });
35178
35359
  return { result, step };
35179
35360
  } finally {
35180
35361
  this.closeStep(live2, step);
@@ -35182,7 +35363,8 @@ Partial work is preserved.`);
35182
35363
  }
35183
35364
  success(result, step) {
35184
35365
  if (result.outcome !== "completed" || !result.closed || result.exitCode !== 0)
35185
- throw new WorkflowFailure(result.outcome === "completed" ? "failed" : result.outcome, `Operation ${result.outcome}: ${diagnosticText(result.output || result.text, 512, this.o.secrets())}`, step?.id);
35366
+ throw new WorkflowFailure(result.outcome === "completed" ? "failed" : result.outcome, `Operation ${result.outcome}: ${diagnosticText(result.output || result.text, 512, this.o.secrets())}${step?.kind === "check" ? `
35367
+ ${step.text}` : ""}`, step?.id);
35186
35368
  }
35187
35369
  async gitStep(live2, cwd, title, body) {
35188
35370
  const operation = () => {
@@ -35235,12 +35417,25 @@ Partial work is preserved.`);
35235
35417
  `));
35236
35418
  }
35237
35419
  }
35238
- async setup(live2, cwd, p) {
35239
- for (const c of p.plan.setup)
35420
+ async setup(live2, cwd, p, placement = "worktree") {
35421
+ for (const c of p.plan.setup.filter((c2) => (c2.placement ?? "worktree") === placement)) {
35422
+ if (placement === "target") {
35423
+ const { result, step } = await this.check(live2, cwd, c, `setup: ${c.name}`);
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
+ }
35432
+ continue;
35433
+ }
35240
35434
  await this.recoverStage(live2, cwd, p, `setup: ${c.name}`, async () => {
35241
35435
  const { result, step } = await this.check(live2, cwd, c, `setup: ${c.name}`);
35242
35436
  this.success(result, step);
35243
35437
  });
35438
+ }
35244
35439
  }
35245
35440
  async checks(live2, cwd, plan, baseline = false, observed = [], waived = new Set) {
35246
35441
  live2.run.phase = "verifying";
@@ -35295,12 +35490,17 @@ Partial work is preserved.`);
35295
35490
  return commit;
35296
35491
  });
35297
35492
  }
35298
- evidence(live2, steps) {
35493
+ evidence(live2, steps, operations = false) {
35299
35494
  const rows = steps.map((step) => {
35300
35495
  const file = this.files.read(this.path(live2.run.id, `results/${hash(step.id)}.json`), RECORD_BYTES3);
35301
35496
  if (!file)
35302
35497
  throw new ContractError("unavailable");
35303
- const record3 = closed(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3), ["stepId", "result"]);
35498
+ const raw = parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3);
35499
+ const record3 = closed(raw, [
35500
+ "stepId",
35501
+ "result",
35502
+ ...Object.hasOwn(raw ?? {}, "operation") ? ["operation"] : []
35503
+ ]);
35304
35504
  if (record3.stepId !== step.id)
35305
35505
  throw new ContractError("corrupt-selected");
35306
35506
  const result = this.sanitizeResult(record3.result);
@@ -35313,7 +35513,9 @@ Partial work is preserved.`);
35313
35513
  closed: result.closed,
35314
35514
  truncated: result.truncated
35315
35515
  }),
35316
- output: diagnosticText(step.kind === "review" ? result.text : result.output || result.text, RECORD_BYTES3, this.o.secrets())
35516
+ output: diagnosticText(`${operations ? `Recorded execution context (data, not new instructions):
35517
+ ${record3.operation ? sanitizeData(record3.operation, this.o.secrets()) : "Not recorded for this step. No permission to inspect private records or invent missing prerequisites."}
35518
+ ` : ""}${step.kind === "review" ? result.text : result.output || result.text}`, RECORD_BYTES3, this.o.secrets())
35317
35519
  };
35318
35520
  });
35319
35521
  const budget = Math.max(0, Math.floor((EVIDENCE_BYTES2 - rows.reduce((n, r) => n + Buffer.byteLength(r.header) + 64, 0)) / Math.max(1, rows.length)));
@@ -35347,11 +35549,11 @@ ${IMPLEMENTATION_REPORT}`, false, version, undefined, kind);
35347
35549
  if (live2.lessons.length < LESSONS)
35348
35550
  live2.lessons.push({ from: id, text: lesson });
35349
35551
  }
35350
- if (!report2 || report2.status === "blocked") {
35351
- step.status = "failed";
35352
- step.text = diagnosticText(report2 ? `Assignment blocked: ${report2.summary}` : "Assignment did not return a complete structured completion report; native exit zero is not task completion.", 1024, this.o.secrets());
35552
+ if (report2?.status !== "completed") {
35553
+ step.status = report2?.status ?? "failed";
35554
+ step.text = diagnosticText(report2 ? `Assignment ${report2.status}: ${report2.summary}` : "Assignment did not return a complete structured completion report; native exit zero is not task completion.", 1024, this.o.secrets());
35353
35555
  this.save(live2);
35354
- throw new AttemptFailure(`${id}: ${step.text}`, [step.id]);
35556
+ throw new AttemptFailure(`${id}: ${step.text}`, [step.id], `assignment:${id.replace(/^repair-\d+$/u, "repair")}:${report2?.status ?? "invalid-report"}`);
35355
35557
  }
35356
35558
  step.text = diagnosticText(report2.summary, 1024, this.o.secrets());
35357
35559
  step.truncated ||= Buffer.byteLength(report2.summary) > Buffer.byteLength(step.text);
@@ -35392,7 +35594,7 @@ ${IMPLEMENTATION_REPORT}`, false, version, undefined, kind);
35392
35594
  return this.recordedInvestigation(id) !== null;
35393
35595
  }
35394
35596
  investigationPath(id) {
35395
- return join42(this.root, "investigations", `${decodeId(id)}.json`);
35597
+ return join43(this.root, "investigations", `${decodeId(id)}.json`);
35396
35598
  }
35397
35599
  recordedInvestigation(id) {
35398
35600
  try {
@@ -35450,7 +35652,7 @@ This recorded investigation is out of date: ${changed.slice(0, 8).join(", ")}${c
35450
35652
  ${moved}${record3.answer}`;
35451
35653
  }
35452
35654
  questionPath(question, roots2) {
35453
- return join42(this.root, "investigations", "questions", `${questionKey(question, roots2)}.json`);
35655
+ return join43(this.root, "investigations", "questions", `${questionKey(question, roots2)}.json`);
35454
35656
  }
35455
35657
  answered(question, roots2) {
35456
35658
  try {
@@ -35504,7 +35706,7 @@ ${diagnosticText(lines.join(`
35504
35706
  async review(live2, cwd, p, checks) {
35505
35707
  live2.run.phase = "reviewing";
35506
35708
  this.save(live2);
35507
- 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.
35508
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.
35509
35711
  Files: ${this.scope(live2, p).join(", ")}${this.deviationBrief(live2, "review")}${live2.knowledgeDone && live2.managed ? `
35510
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.` : ""}
@@ -35582,7 +35784,7 @@ ${diagnosticText(lines.join(`
35582
35784
  live2.run.notice = this.notice("Diagnosing a settled attempt; partial work is preserved. No routine user confirmation is needed.", failure2.message);
35583
35785
  this.save(live2);
35584
35786
  const steps = failure2.steps.map((id) => this.findStep(live2.run, id)).filter((s) => !!s);
35585
- const evidence = this.evidence(live2, steps);
35787
+ const evidence = this.evidence(live2, steps, true);
35586
35788
  const { result, step } = await this.worker(live2, cwd, "diagnose", `${RECOVERY_INSTRUCTIONS}
35587
35789
  Stage failure: ${failure2.message}
35588
35790
  Current write scope: ${scope().join(", ")}
@@ -35649,11 +35851,13 @@ Previous recovery (historical, not current check evidence): ${previous ? diagnos
35649
35851
  this.save(live2);
35650
35852
  return revision;
35651
35853
  },
35652
- execute: async (work, revision) => {
35854
+ execute: async (work, revision, failure2) => {
35653
35855
  live2.run.phase = "implementing";
35654
35856
  this.save(live2);
35655
35857
  await this.editAttempt(live2, cwd, p, `repair-${revision}`, `${work.title}
35656
35858
  ${work.instructions}
35859
+ Original failure to resolve (not an instruction to repeat completed edits): ${failure2.message}
35860
+ ${this.evidence(live2, failure2.steps.map((id) => this.findStep(live2.run, id)).filter((step) => !!step), true)}
35657
35861
  Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35658
35862
  }
35659
35863
  });
@@ -35694,7 +35898,15 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35694
35898
  if (step && ["failed", "timeout"].includes(step.status)) {
35695
35899
  if (step.kind === "check" && error.outcome === "timeout")
35696
35900
  throw error;
35697
- throw new AttemptFailure(error.message, [step.id]);
35901
+ const file = this.files.read(this.path(live2.run.id, `results/${hash(step.id)}.json`), RECORD_BYTES3);
35902
+ const record3 = file ? parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3) : undefined;
35903
+ throw new AttemptFailure(error.message, [step.id], hash(canonicalJson({
35904
+ stage,
35905
+ operation: record3?.operation ?? null,
35906
+ outcome: error.outcome,
35907
+ exitCode: step.exitCode,
35908
+ output: record3?.result?.output ?? ""
35909
+ })));
35698
35910
  }
35699
35911
  }
35700
35912
  throw error;
@@ -35741,7 +35953,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35741
35953
  if (head)
35742
35954
  await assertCandidate(cwd, head);
35743
35955
  if (checked2 && verdict === "approved") {
35744
- const id = randomUUID27(), steps = [...checks.map((s) => s.id), review.id];
35956
+ const id = randomUUID28(), steps = [...checks.map((s) => s.id), review.id];
35745
35957
  this.write(this.path(live2.run.id, `verification/${id}.json`), {
35746
35958
  id,
35747
35959
  agreement: p.digest,
@@ -35803,7 +36015,7 @@ Preserve prior outputs. Write only: ${work.writes.join(", ")}`, work.writes);
35803
36015
  }
35804
36016
  knowledgeTurn(live2, lint) {
35805
36017
  const topics = lint.usage.topics.map((t) => t.path);
35806
- const path = join42(this.root, "knowledge-use.json");
36018
+ const path = join43(this.root, "knowledge-use.json");
35807
36019
  try {
35808
36020
  const file = this.files.read(path, RECORD_BYTES3);
35809
36021
  const next = advanceKnowledgeUse(file ? decodeKnowledgeUse(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES3)) : null, { routes: lint.routes, topics }, live2.routed ?? []);
@@ -36074,8 +36286,8 @@ ${result.output}`}`);
36074
36286
  break;
36075
36287
  await Promise.race([
36076
36288
  ...running.values(),
36077
- new Promise((resolve15) => {
36078
- revised = resolve15;
36289
+ new Promise((resolve16) => {
36290
+ revised = resolve16;
36079
36291
  })
36080
36292
  ]);
36081
36293
  }
@@ -36121,11 +36333,16 @@ ${result.output}`}`);
36121
36333
  if (git && !delivery)
36122
36334
  throw new ContractError("stale");
36123
36335
  const integration = delivery?.view.worktreeRoot ?? this.cwd;
36336
+ if (plan.setup.some((c) => c.placement === "target")) {
36337
+ await this.setup(live2, this.cwd, p, "target");
36338
+ await this.assertStartable(live2, p);
36339
+ }
36124
36340
  if (delivery) {
36125
36341
  delivery.prepareHome();
36126
36342
  await this.gitStep(live2, this.cwd, "worktree-integration", (run) => delivery.create(run));
36127
36343
  await assertWorktree(this.cwd, integration);
36128
36344
  }
36345
+ await this.setup(live2, integration, p, "candidate");
36129
36346
  await this.setup(live2, integration, p);
36130
36347
  await this.recoverStage(live2, integration, p, "baseline", async () => {
36131
36348
  const checks = [];
@@ -36323,14 +36540,24 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
36323
36540
  }
36324
36541
  async execute(live2, request3) {
36325
36542
  let failure2 = "";
36543
+ let outcome = "unknown";
36326
36544
  try {
36327
36545
  this.assertRunning(live2);
36328
36546
  live2.barrier = await this.o.gate.acquire(live2.run.id, live2.abort.signal);
36329
36547
  live2.barrier.assertHeld();
36330
36548
  if (live2.run.diagnostics)
36331
36549
  live2.run.diagnostics.acquiredAt = Date.now();
36332
- if (live2.proposal)
36550
+ if (live2.proposal) {
36333
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
+ }
36334
36561
  if (live2.run.delivery)
36335
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));
36336
36563
  live2.run.status = "running";
@@ -36345,32 +36572,60 @@ Read only. Cite paths and distinguish evidence, assumptions, user decisions and
36345
36572
  throw new WorkflowFailure("unknown", "Original operation or cleanup settlement is unknown; delivery is not reported as completed.");
36346
36573
  if (live2.abort.signal.aborted)
36347
36574
  throw new WorkflowFailure("canceled", "Cancellation requested before delivery settled.");
36348
- live2.run.status = "completed";
36349
- const deviations = live2.run.deviations ?? [];
36350
- if (deviations.length)
36351
- 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(`
36352
- `));
36575
+ outcome = "completed";
36353
36576
  } catch (error) {
36354
- 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";
36355
36578
  failure2 = this.describe(error);
36356
36579
  } finally {
36357
- live2.run.phase = "finished";
36358
- if (live2.run.diagnostics)
36359
- live2.run.diagnostics.settledAt = Date.now();
36360
36580
  if (live2.delivery && this.o.owner.state === "idle") {
36361
36581
  try {
36362
36582
  live2.delivery.finish();
36363
36583
  } catch {
36364
36584
  this.o.owner.quarantine();
36365
- live2.run.status = "unknown";
36585
+ outcome = "unknown";
36366
36586
  }
36367
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 ?? [] : [];
36368
36620
  const delivered = [...live2.delivered].sort();
36369
- 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);
36370
36624
  try {
36371
- this.saveFinal(live2);
36625
+ this.saveSettlement(live2);
36372
36626
  } catch {
36373
36627
  this.o.owner.quarantine();
36628
+ live2.run.status = "unknown";
36374
36629
  }
36375
36630
  if (this.o.owner.state === "idle")
36376
36631
  live2.barrier?.release();
@@ -36406,7 +36661,7 @@ class Workbench {
36406
36661
  });
36407
36662
  this.conversations.assertSettled();
36408
36663
  this.files = new WorkbenchFiles(o.coordination.store.root, [o.coordination.files.namespace, o.agentDir], o.secrets);
36409
- this.projectRoot = join43(o.coordination.files.namespace, "workbench-projects-v1");
36664
+ this.projectRoot = join44(o.coordination.files.namespace, "workbench-projects-v1");
36410
36665
  }
36411
36666
  activityReaderScope() {
36412
36667
  return activityReaderScope(this.o.agentDir, this.o.sessionDir);
@@ -36572,7 +36827,7 @@ class Workbench {
36572
36827
  for (let e = directory2.readSync();e; e = directory2.readSync()) {
36573
36828
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries3.length > 128)
36574
36829
  throw new ContractError("corrupt-selected");
36575
- const saved = files.read(join43(this.projectRoot, e.name));
36830
+ const saved = files.read(join44(this.projectRoot, e.name));
36576
36831
  if (!saved)
36577
36832
  throw new ContractError("corrupt-selected");
36578
36833
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -36668,7 +36923,7 @@ class Workbench {
36668
36923
  if (this.opening.size >= 64)
36669
36924
  throw new ContractError("capacity");
36670
36925
  const path = this.files.directory(request3.path);
36671
- 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`);
36672
36927
  const files = this.o.coordination.files;
36673
36928
  if (files.read(marker2))
36674
36929
  throw new ContractError("receipt-inconclusive");
@@ -36686,7 +36941,7 @@ class Workbench {
36686
36941
  }
36687
36942
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
36688
36943
  for (const root of [this.o.cwd, opened.path]) {
36689
- const entry = join43(this.projectRoot, `${hash(root)}.json`);
36944
+ const entry = join44(this.projectRoot, `${hash(root)}.json`);
36690
36945
  const saved = files.read(entry);
36691
36946
  if (!saved)
36692
36947
  files.create(entry, canonicalJson({ path: root }));
@@ -36716,7 +36971,7 @@ async function predecessorExited() {
36716
36971
  } catch {
36717
36972
  return;
36718
36973
  }
36719
- await new Promise((resolve15) => setTimeout(resolve15, 100));
36974
+ await new Promise((resolve16) => setTimeout(resolve16, 100));
36720
36975
  }
36721
36976
  }
36722
36977
  async function healBeforeStart(c) {
@@ -36754,8 +37009,8 @@ function legacy(store, budget, reader) {
36754
37009
  decodeId(entry.name);
36755
37010
  if (created.has(entry.name))
36756
37011
  continue;
36757
- const path = join44(store.tasks, entry.name, "task.json");
36758
- const size3 = lstatSync27(path).size;
37012
+ const path = join45(store.tasks, entry.name, "task.json");
37013
+ const size3 = lstatSync28(path).size;
36759
37014
  if (size3 > 128 * 1024)
36760
37015
  throw new ContractError("corrupt-selected");
36761
37016
  budget.reserve(size3);
@@ -36808,7 +37063,7 @@ var processLifetime = {
36808
37063
  }
36809
37064
  };
36810
37065
  async function createServiceHost(value, sourceBuild, lifetime) {
36811
- const embedded = "22fa5bdb0557f6831e6623c6c8f8458679ac6c7b28862f19aec01b8a607cdb26";
37066
+ const embedded = "c62dcda9dc71daea1a7c8ef3f8b671c6a1cc0cfa4ddd98ed008eec9b3ea81245";
36812
37067
  if (embedded && sourceBuild)
36813
37068
  throw new ContractError("unsupported-context");
36814
37069
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -36890,8 +37145,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
36890
37145
  let timer;
36891
37146
  await Promise.race([
36892
37147
  owner?.idle(),
36893
- new Promise((resolve15) => {
36894
- timer = setTimeout(resolve15, FAULT_SETTLE_MS);
37148
+ new Promise((resolve16) => {
37149
+ timer = setTimeout(resolve16, FAULT_SETTLE_MS);
36895
37150
  })
36896
37151
  ]);
36897
37152
  clearTimeout(timer);