@abelxiaoxing/cadence 2.0.28 → 2.0.29

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.
@@ -9,7 +9,9 @@ import {
9
9
  createServer as createServer2,
10
10
  request as request2
11
11
  } from "node:http";
12
- import { homedir as homedir5 } from "node:os";
12
+ import { homedir as homedir6 } from "node:os";
13
+ import { dirname as dirname12 } from "node:path";
14
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
13
15
  import { WebSocket, WebSocketServer as WebSocketServer2 } from "ws";
14
16
 
15
17
  // src/service-assets.ts
@@ -5598,11 +5600,167 @@ class HttpAuthentication {
5598
5600
  }
5599
5601
  }
5600
5602
 
5603
+ // src/service/autostart.ts
5604
+ import { spawnSync as spawnSync2 } from "node:child_process";
5605
+ import {
5606
+ lstatSync as lstatSync5,
5607
+ mkdirSync as mkdirSync4,
5608
+ readFileSync,
5609
+ realpathSync as realpathSync3,
5610
+ renameSync as renameSync2,
5611
+ rmSync,
5612
+ statSync as statSync2,
5613
+ writeFileSync as writeFileSync2
5614
+ } from "node:fs";
5615
+ import { homedir as homedir2 } from "node:os";
5616
+ import {
5617
+ delimiter,
5618
+ dirname as dirname5,
5619
+ isAbsolute as isAbsolute4,
5620
+ join as join6,
5621
+ resolve as resolve3,
5622
+ sep as sep3,
5623
+ win32
5624
+ } from "node:path";
5625
+ var UNIT = "cadence.service";
5626
+ var MARKER = "# Generated by @abelxiaoxing/cadence";
5627
+ function wscript(env) {
5628
+ const root = env.SystemRoot;
5629
+ return win32.join(root && win32.isAbsolute(root) ? root : "C:\\Windows", "System32", "wscript.exe");
5630
+ }
5631
+ function hostSystem(root, owner, selection = {}) {
5632
+ const scope = selection.scope ?? (process.platform === "linux" && process.getuid?.() === 0 ? "system" : "user");
5633
+ const unit = serviceUnit(selection.name);
5634
+ const run = (command, args) => {
5635
+ const r = spawnSync2(command, args, {
5636
+ encoding: "utf8",
5637
+ stdio: ["ignore", "pipe", "ignore"],
5638
+ windowsHide: true
5639
+ });
5640
+ return { status: r.error ? null : r.status, stdout: r.stdout ?? "" };
5641
+ };
5642
+ return {
5643
+ platform: process.platform,
5644
+ env: process.env,
5645
+ home: homedir2(),
5646
+ node: process.execPath,
5647
+ root,
5648
+ unit,
5649
+ scope,
5650
+ uid: process.getuid?.(),
5651
+ cgroup: () => {
5652
+ try {
5653
+ return readFileSync("/proc/self/cgroup", "utf8");
5654
+ } catch {
5655
+ return;
5656
+ }
5657
+ },
5658
+ systemctl: (args) => run("systemctl", [scope === "system" ? "--system" : "--user", ...args]),
5659
+ linger: () => {
5660
+ const r = run("loginctl", [
5661
+ "show-user",
5662
+ String(process.getuid?.()),
5663
+ "--property=Linger",
5664
+ "--value"
5665
+ ]);
5666
+ return r.status === 0 ? r.stdout.trim() === "yes" : undefined;
5667
+ },
5668
+ enableLinger: (interactive) => {
5669
+ const r = interactive ? spawnSync2("loginctl", ["enable-linger"], { stdio: "inherit" }) : spawnSync2("busctl", [
5670
+ "--system",
5671
+ "--allow-interactive-authorization=no",
5672
+ "--timeout=15",
5673
+ "call",
5674
+ "org.freedesktop.login1",
5675
+ "/org/freedesktop/login1",
5676
+ "org.freedesktop.login1.Manager",
5677
+ "SetUserLinger",
5678
+ "ubb",
5679
+ String(process.getuid?.()),
5680
+ "true",
5681
+ "false"
5682
+ ], { stdio: "ignore", timeout: 20000 });
5683
+ return !r.error && r.status === 0;
5684
+ },
5685
+ launchctl: (args) => run("launchctl", args),
5686
+ reg: (args) => run("reg", args),
5687
+ launch: (path) => {
5688
+ const r = spawnSync2(wscript(process.env), [path], {
5689
+ stdio: "ignore",
5690
+ windowsHide: true,
5691
+ timeout: 20000
5692
+ });
5693
+ return !r.error && r.status === 0;
5694
+ },
5695
+ ...owner
5696
+ };
5697
+ }
5698
+ function serviceUnit(name) {
5699
+ if (name === undefined)
5700
+ return UNIT;
5701
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/.test(name))
5702
+ throw new ContractError("invalid");
5703
+ return `cadence-${name}.service`;
5704
+ }
5705
+ function serviceName(s) {
5706
+ if (s.unit === UNIT)
5707
+ return;
5708
+ const name = /^cadence-([A-Za-z0-9][A-Za-z0-9_-]{0,47})\.service$/.exec(s.unit)?.[1];
5709
+ if (!name)
5710
+ throw new ContractError("invalid");
5711
+ return name;
5712
+ }
5713
+ function serviceConfigPath(s) {
5714
+ return serverConfigPath(s.home, serviceName(s));
5715
+ }
5716
+ function unitPath(s) {
5717
+ serviceName(s);
5718
+ if (s.scope === "system")
5719
+ return join6(s.unitDirectory ?? "/etc/systemd/system", s.unit);
5720
+ const data = s.env.XDG_DATA_HOME;
5721
+ return join6(data && isAbsolute4(data) ? data : join6(s.home, ".local", "share"), "systemd", "user", s.unit);
5722
+ }
5723
+ function readGenerated(path, marker) {
5724
+ try {
5725
+ if (!lstatSync5(path).isFile())
5726
+ return null;
5727
+ const bytes = readFileSync(path);
5728
+ const text2 = bytes[0] === 255 && bytes[1] === 254 ? bytes.subarray(2).toString("utf16le") : bytes.toString("utf8");
5729
+ return text2.startsWith(marker) ? text2 : null;
5730
+ } catch (error) {
5731
+ if (error.code === "ENOENT")
5732
+ return;
5733
+ throw error;
5734
+ }
5735
+ }
5736
+ function unitWorkspace(text2) {
5737
+ if (text2?.includes("# Cadence workbench gateway; no project workspace"))
5738
+ return null;
5739
+ return text2?.match(/^WorkingDirectory=(.+)$/m)?.[1].replaceAll("%%", "%");
5740
+ }
5741
+ function unitEnvironment(text2) {
5742
+ const out = [];
5743
+ for (const line of text2.split(`
5744
+ `)) {
5745
+ if (!line.startsWith("Environment="))
5746
+ continue;
5747
+ const value = JSON.parse(line.slice("Environment=".length));
5748
+ if (typeof value !== "string" || value.indexOf("=") < 1)
5749
+ throw new ContractError("invalid");
5750
+ const at = value.indexOf("=");
5751
+ out.push([value.slice(0, at), value.slice(at + 1).replaceAll("%%", "%")]);
5752
+ }
5753
+ return out;
5754
+ }
5755
+ function generatedUnit(s) {
5756
+ return readGenerated(unitPath(s), MARKER);
5757
+ }
5758
+
5601
5759
  // src/service/cli.ts
5602
- import { spawn } from "node:child_process";
5760
+ import { spawn as spawn2 } from "node:child_process";
5603
5761
  import { request } from "node:http";
5604
- import { homedir as homedir3 } from "node:os";
5605
- import { dirname as dirname8, join as join13, resolve as resolve5 } from "node:path";
5762
+ import { homedir as homedir4 } from "node:os";
5763
+ import { dirname as dirname10, join as join15, resolve as resolve6 } from "node:path";
5606
5764
  import { fileURLToPath as fileURLToPath2 } from "node:url";
5607
5765
 
5608
5766
  // src/sdk-network.ts
@@ -5740,29 +5898,103 @@ function sdkNetworkEnvironment(ambient, scoped) {
5740
5898
  return { env, redactionLiterals: route ? [route] : [] };
5741
5899
  }
5742
5900
 
5901
+ // src/service/contracts/gateway.ts
5902
+ function decodeProjectEntry(value) {
5903
+ const o = closed(value, ["id", "path", "cwd", "epoch"]);
5904
+ return {
5905
+ id: decodeHash(o.id),
5906
+ path: text(o.path, 4096, true),
5907
+ cwd: text(o.cwd, 4096, true),
5908
+ epoch: decodeId(o.epoch)
5909
+ };
5910
+ }
5911
+ var RECOVERY_SCOPES = ["registry", "workbench", "project"];
5912
+ var RECOVERY_CAUSES = [
5913
+ "reboot",
5914
+ "crash",
5915
+ "restart",
5916
+ "storage"
5917
+ ];
5918
+ var RECOVERY_ACTIONS = [
5919
+ "released-locks",
5920
+ "stopped-workers",
5921
+ "stopped-owner",
5922
+ "continued-history",
5923
+ "archived-history",
5924
+ "archived-state",
5925
+ "rebuilt-registry",
5926
+ "removed-temporaries"
5927
+ ];
5928
+ var MAINTENANCE_ACTIONS = ["restart", "upgrade"];
5929
+ var MAINTENANCE_STATES = [
5930
+ "running",
5931
+ "ready",
5932
+ "failed",
5933
+ "rolled-back"
5934
+ ];
5935
+ var MAINTENANCE_REASONS = [
5936
+ "fetch-failed",
5937
+ "stop-unconfirmed",
5938
+ "install-failed",
5939
+ "not-ready",
5940
+ "refused",
5941
+ "interrupted"
5942
+ ];
5943
+ var VERSION = /^(?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8})\.(?:0|[1-9][0-9]{0,8})(?:-[0-9A-Za-z.-]{1,64})?$/;
5944
+ function decodeVersion(value) {
5945
+ const version = text(value, 96, true);
5946
+ if (!VERSION.test(version))
5947
+ throw new ContractError("invalid");
5948
+ return version;
5949
+ }
5950
+ function decodeMaintenanceJob(value) {
5951
+ const o = closed(value, [
5952
+ "id",
5953
+ "action",
5954
+ "from",
5955
+ "to",
5956
+ "state",
5957
+ "reason",
5958
+ "version",
5959
+ "at",
5960
+ "endedAt"
5961
+ ]);
5962
+ return {
5963
+ id: decodeId(o.id),
5964
+ action: oneOf(o.action, MAINTENANCE_ACTIONS),
5965
+ from: decodeVersion(o.from),
5966
+ to: o.to === null ? null : decodeVersion(o.to),
5967
+ state: oneOf(o.state, MAINTENANCE_STATES),
5968
+ reason: o.reason === null ? null : oneOf(o.reason, MAINTENANCE_REASONS),
5969
+ version: o.version === null ? null : decodeVersion(o.version),
5970
+ at: integer(o.at, 0),
5971
+ endedAt: o.endedAt === null ? null : integer(o.endedAt, 0)
5972
+ };
5973
+ }
5974
+
5743
5975
  // src/service/coordination.ts
5744
5976
  import { randomBytes as randomBytes2, randomUUID as randomUUID4 } from "node:crypto";
5745
5977
  import { opendirSync } from "node:fs";
5746
5978
  import { hostname as hostname3 } from "node:os";
5747
- import { dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative as relative3, sep as sep3 } from "node:path";
5979
+ import { dirname as dirname7, isAbsolute as isAbsolute5, join as join8, relative as relative3, sep as sep4 } from "node:path";
5748
5980
 
5749
5981
  // src/service/checkout-lock.ts
5750
5982
  import { randomUUID as randomUUID3 } from "node:crypto";
5751
5983
  import {
5752
5984
  closeSync as closeSync3,
5753
5985
  fsyncSync as fsyncSync2,
5754
- lstatSync as lstatSync5,
5986
+ lstatSync as lstatSync6,
5755
5987
  openSync as openSync3,
5756
- realpathSync as realpathSync3,
5988
+ realpathSync as realpathSync4,
5757
5989
  unlinkSync as unlinkSync2,
5758
- writeFileSync as writeFileSync2
5990
+ writeFileSync as writeFileSync3
5759
5991
  } from "node:fs";
5760
5992
  import { hostname as hostname2 } from "node:os";
5761
- import { dirname as dirname5, join as join6 } from "node:path";
5993
+ import { dirname as dirname6, join as join7 } from "node:path";
5762
5994
 
5763
5995
  // src/service/liveness.ts
5764
- import { spawnSync as spawnSync2 } from "node:child_process";
5765
- import { readFileSync } from "node:fs";
5996
+ import { spawnSync as spawnSync3 } from "node:child_process";
5997
+ import { readFileSync as readFileSync2 } from "node:fs";
5766
5998
  import { hostname, uptime } from "node:os";
5767
5999
  var LEGACY_BOOT_MARGIN_MS = 10 * 60 * 1000;
5768
6000
  var REUSE_SLACK_MS = 5000;
@@ -5774,11 +6006,11 @@ function bootId() {
5774
6006
  cachedBoot = null;
5775
6007
  try {
5776
6008
  if (process.platform === "linux") {
5777
- const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
6009
+ const id = readFileSync2("/proc/sys/kernel/random/boot_id", "utf8").trim();
5778
6010
  if (/^[0-9a-f-]{36}$/.test(id))
5779
6011
  cachedBoot = id;
5780
6012
  } else if (process.platform === "darwin") {
5781
- const r = spawnSync2("sysctl", ["-n", "kern.bootsessionuuid"], {
6013
+ const r = spawnSync3("sysctl", ["-n", "kern.bootsessionuuid"], {
5782
6014
  encoding: "utf8",
5783
6015
  timeout: 2000
5784
6016
  });
@@ -5794,7 +6026,7 @@ function bootId() {
5794
6026
  function bootTime() {
5795
6027
  if (process.platform === "linux")
5796
6028
  try {
5797
- const line = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
6029
+ const line = /^btime (\d+)$/m.exec(readFileSync2("/proc/stat", "utf8"));
5798
6030
  if (line)
5799
6031
  return Number(line[1]) * 1000;
5800
6032
  } catch {}
@@ -5802,7 +6034,7 @@ function bootTime() {
5802
6034
  }
5803
6035
  function linuxStat(pid) {
5804
6036
  try {
5805
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
6037
+ const stat = readFileSync2(`/proc/${pid}/stat`, "utf8");
5806
6038
  return stat.slice(stat.lastIndexOf(")") + 2).trim().split(" ");
5807
6039
  } catch {
5808
6040
  return null;
@@ -5817,7 +6049,7 @@ function processStart(pid) {
5817
6049
  return ticks && /^\d+$/.test(ticks) ? `ticks:${ticks}` : null;
5818
6050
  }
5819
6051
  if (process.platform === "darwin") {
5820
- const r = spawnSync2("ps", ["-o", "lstart=", "-p", String(pid)], {
6052
+ const r = spawnSync3("ps", ["-o", "lstart=", "-p", String(pid)], {
5821
6053
  encoding: "utf8",
5822
6054
  timeout: 2000,
5823
6055
  env: { ...process.env, LC_ALL: "C" }
@@ -5926,14 +6158,14 @@ async function stopProcessGroup(pgid, waitMs = 5000) {
5926
6158
  send("SIGTERM");
5927
6159
  const deadline = Date.now() + waitMs;
5928
6160
  while (Date.now() < deadline) {
5929
- await new Promise((resolve3) => setTimeout(resolve3, 100));
6161
+ await new Promise((resolve4) => setTimeout(resolve4, 100));
5930
6162
  if (gone())
5931
6163
  return true;
5932
6164
  if (Date.now() > deadline - waitMs / 2)
5933
6165
  send("SIGKILL");
5934
6166
  }
5935
6167
  send("SIGKILL");
5936
- await new Promise((resolve3) => setTimeout(resolve3, 200));
6168
+ await new Promise((resolve4) => setTimeout(resolve4, 200));
5937
6169
  return gone();
5938
6170
  }
5939
6171
 
@@ -5942,7 +6174,7 @@ class CheckoutStore {
5942
6174
  root;
5943
6175
  privateRoot;
5944
6176
  constructor(root, stateHome = defaultStateHome()) {
5945
- this.root = realpathSync3(root);
6177
+ this.root = realpathSync4(root);
5946
6178
  if (privateWorkspace(this.root, stateHome))
5947
6179
  throw new Error("Private state cannot be a workspace");
5948
6180
  this.privateRoot = privateRootFor(this.root, stateHome);
@@ -5950,14 +6182,14 @@ class CheckoutStore {
5950
6182
  throw new Error("Private state home must be outside the working copy");
5951
6183
  }
5952
6184
  get lockPath() {
5953
- return join6(this.privateRoot, "checkout.lock");
6185
+ return join7(this.privateRoot, "checkout.lock");
5954
6186
  }
5955
6187
  inspectPrivate() {
5956
- const namespace = dirname5(this.privateRoot);
6188
+ const namespace = dirname6(this.privateRoot);
5957
6189
  for (const path of [namespace, this.privateRoot]) {
5958
6190
  if (!safeDirectory(path))
5959
6191
  continue;
5960
- const st = lstatSync5(path);
6192
+ const st = lstatSync6(path);
5961
6193
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
5962
6194
  throw new Error("Private state permissions refused");
5963
6195
  }
@@ -5967,7 +6199,7 @@ class CheckoutStore {
5967
6199
  if (!safeDirectory(this.privateRoot))
5968
6200
  return;
5969
6201
  try {
5970
- const st = lstatSync5(path);
6202
+ const st = lstatSync6(path);
5971
6203
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1 || st.size > max || process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
5972
6204
  throw new Error("Unsafe private state file");
5973
6205
  } catch (error) {
@@ -6006,7 +6238,7 @@ class CheckoutStore {
6006
6238
  throw new Error("Checkout busy or unresolved lock; inspect and explicitly recover only a dead owner");
6007
6239
  }
6008
6240
  try {
6009
- writeFileSync2(fd, JSON.stringify(lock));
6241
+ writeFileSync3(fd, JSON.stringify(lock));
6010
6242
  fsyncSync2(fd);
6011
6243
  } finally {
6012
6244
  closeSync3(fd);
@@ -6042,7 +6274,7 @@ var registrationKeys = [
6042
6274
  var reservationKeys = registrationKeys.filter((k) => !["schema", "phase", "checkoutToken"].includes(k));
6043
6275
  function pathValue(value) {
6044
6276
  const path = text(value, 4096, true);
6045
- if (!isAbsolute4(path))
6277
+ if (!isAbsolute5(path))
6046
6278
  refused();
6047
6279
  return path;
6048
6280
  }
@@ -6099,7 +6331,7 @@ function decodeRegistration(value) {
6099
6331
  function rootsOverlap(a, b) {
6100
6332
  const within = (x, y) => {
6101
6333
  const r = relative3(x, y);
6102
- return r === "" || r !== ".." && !r.startsWith(`..${sep3}`) && !isAbsolute4(r);
6334
+ return r === "" || r !== ".." && !r.startsWith(`..${sep4}`) && !isAbsolute5(r);
6103
6335
  };
6104
6336
  return within(a, b) || within(b, a);
6105
6337
  }
@@ -6148,10 +6380,10 @@ class ServiceCoordination {
6148
6380
  stateHome;
6149
6381
  constructor(workspace, stateHome) {
6150
6382
  this.project = workspace === null ? undefined : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
6151
- this.stateHome = this.project ? dirname6(dirname6(this.project.privateRoot)) : canonicalAmbientRoot(stateHome ?? defaultStateHome());
6152
- const namespace = join7(this.stateHome, "cadence-assistant-v1");
6383
+ this.stateHome = this.project ? dirname7(dirname7(this.project.privateRoot)) : canonicalAmbientRoot(stateHome ?? defaultStateHome());
6384
+ const namespace = join8(this.stateHome, "cadence-assistant-v1");
6153
6385
  this.files = new PrivateFiles(namespace);
6154
- this.registryDirectory = join7(namespace, "service-registry-v1");
6386
+ this.registryDirectory = join8(namespace, "service-registry-v1");
6155
6387
  }
6156
6388
  get store() {
6157
6389
  if (!this.project)
@@ -6159,13 +6391,13 @@ class ServiceCoordination {
6159
6391
  return this.project;
6160
6392
  }
6161
6393
  get directory() {
6162
- return join7(this.store.privateRoot, "service-v1");
6394
+ return join8(this.store.privateRoot, "service-v1");
6163
6395
  }
6164
6396
  path(name) {
6165
- return join7(this.directory, name);
6397
+ return join8(this.directory, name);
6166
6398
  }
6167
6399
  registryPath(name) {
6168
- return join7(this.registryDirectory, name);
6400
+ return join8(this.registryDirectory, name);
6169
6401
  }
6170
6402
  registry() {
6171
6403
  if (!this.files.directory(this.registryDirectory))
@@ -6212,14 +6444,14 @@ class ServiceCoordination {
6212
6444
  "conversation-workflows-v1",
6213
6445
  "workflows-v1"
6214
6446
  ]);
6215
- this.files.directory(join7(directory, "history-v2"), false, walks);
6447
+ this.files.directory(join8(directory, "history-v2"), false, walks);
6216
6448
  }
6217
6449
  selected(directory = this.directory, root = this.store.root, stoppedOnly = false) {
6218
6450
  const walks = new DirectoryWalks;
6219
6451
  if (!this.files.directory(directory, false, walks))
6220
6452
  return;
6221
6453
  this.assertNamespace(walks, directory);
6222
- const path = (name) => join7(directory, name);
6454
+ const path = (name) => join8(directory, name);
6223
6455
  const manifest = this.files.read(path("format.json"), undefined, walks);
6224
6456
  const config = this.files.read(path("config.json"), undefined, walks);
6225
6457
  if (!manifest || !config)
@@ -6241,7 +6473,7 @@ class ServiceCoordination {
6241
6473
  const registration = this.files.read(path("registration.json"), undefined, walks);
6242
6474
  const owner = this.files.read(path("owner.lock"), undefined, walks);
6243
6475
  const capability = this.files.read(path("local-capability.json"), undefined, walks);
6244
- const checkout = this.files.read(join7(dirname6(directory), "checkout.lock"), 8192, walks);
6476
+ const checkout = this.files.read(join8(dirname7(directory), "checkout.lock"), 8192, walks);
6245
6477
  const value = registration ? decodeRegistration(json(registration)) : undefined;
6246
6478
  if (value && (value.root !== root || value.stateHome !== this.stateHome || value.configIdentity !== config.identity || !endpointMatches(c.endpoint, value.endpoint)))
6247
6479
  refused();
@@ -6590,37 +6822,7 @@ import { isatty } from "node:tty";
6590
6822
  import { randomBytes as randomBytes3, randomUUID as randomUUID5 } from "node:crypto";
6591
6823
  import { opendirSync as opendirSync2 } from "node:fs";
6592
6824
  import { hostname as hostname4 } from "node:os";
6593
- import { join as join8, resolve as resolve3 } from "node:path";
6594
-
6595
- // src/service/contracts/gateway.ts
6596
- function decodeProjectEntry(value) {
6597
- const o = closed(value, ["id", "path", "cwd", "epoch"]);
6598
- return {
6599
- id: decodeHash(o.id),
6600
- path: text(o.path, 4096, true),
6601
- cwd: text(o.cwd, 4096, true),
6602
- epoch: decodeId(o.epoch)
6603
- };
6604
- }
6605
- var RECOVERY_SCOPES = ["registry", "workbench", "project"];
6606
- var RECOVERY_CAUSES = [
6607
- "reboot",
6608
- "crash",
6609
- "restart",
6610
- "storage"
6611
- ];
6612
- var RECOVERY_ACTIONS = [
6613
- "released-locks",
6614
- "stopped-workers",
6615
- "stopped-owner",
6616
- "continued-history",
6617
- "archived-history",
6618
- "archived-state",
6619
- "rebuilt-registry",
6620
- "removed-temporaries"
6621
- ];
6622
-
6623
- // src/service/gateway-store.ts
6825
+ import { join as join9, resolve as resolve4 } from "node:path";
6624
6826
  function decodeGatewayInput(value) {
6625
6827
  const o = closed(value, [
6626
6828
  "kind",
@@ -6631,7 +6833,7 @@ function decodeGatewayInput(value) {
6631
6833
  ]);
6632
6834
  const absolute = (v) => {
6633
6835
  const p = text(v, 4096, true);
6634
- if (resolve3(p) !== p)
6836
+ if (resolve4(p) !== p)
6635
6837
  throw new ContractError("invalid");
6636
6838
  return p;
6637
6839
  };
@@ -6645,7 +6847,7 @@ function decodeGatewayInput(value) {
6645
6847
  }
6646
6848
  function decodeGatewayProject(value) {
6647
6849
  const project = decodeProjectEntry(value);
6648
- if (resolve3(project.path) !== project.path || resolve3(project.cwd) !== project.cwd)
6850
+ if (resolve4(project.path) !== project.path || resolve4(project.cwd) !== project.cwd)
6649
6851
  throw new ContractError("corrupt-selected");
6650
6852
  return project;
6651
6853
  }
@@ -6705,11 +6907,11 @@ class GatewayStore {
6705
6907
  constructor(serverConfig, stateHome = defaultStateHome()) {
6706
6908
  this.serverConfig = serverConfig;
6707
6909
  this.stateHome = canonicalAmbientRoot(stateHome);
6708
- this.files = new PrivateFiles(join8(this.stateHome, "cadence-assistant-v1"));
6709
- this.directory = join8(this.files.namespace, "workbenches-v1", hash2(resolve3(serverConfig)));
6910
+ this.files = new PrivateFiles(join9(this.stateHome, "cadence-assistant-v1"));
6911
+ this.directory = join9(this.files.namespace, "workbenches-v1", hash2(resolve4(serverConfig)));
6710
6912
  }
6711
6913
  path(name) {
6712
- return join8(this.directory, name);
6914
+ return join9(this.directory, name);
6713
6915
  }
6714
6916
  read() {
6715
6917
  const file = this.files.read(this.path("gateway.json"));
@@ -6808,7 +7010,7 @@ class GatewayStore {
6808
7010
  for (let entry = stream.readSync();entry; entry = stream.readSync()) {
6809
7011
  if (!entry.isFile() || !/^[a-f0-9]{64}\.json$/.test(entry.name) || out.length >= 128)
6810
7012
  throw new ContractError("corrupt-selected");
6811
- const file = this.files.read(join8(directory, entry.name));
7013
+ const file = this.files.read(join9(directory, entry.name));
6812
7014
  if (!file)
6813
7015
  throw new ContractError("corrupt-selected");
6814
7016
  const project = decodeGatewayProject(json(file));
@@ -6854,12 +7056,12 @@ class GatewayStore {
6854
7056
  // src/service/recovery-log.ts
6855
7057
  import { randomUUID as randomUUID6 } from "node:crypto";
6856
7058
  import {
6857
- lstatSync as lstatSync6,
7059
+ lstatSync as lstatSync7,
6858
7060
  opendirSync as opendirSync3,
6859
- renameSync as renameSync2,
6860
- rmSync
7061
+ renameSync as renameSync3,
7062
+ rmSync as rmSync2
6861
7063
  } from "node:fs";
6862
- import { basename, join as join9, relative as relative4 } from "node:path";
7064
+ import { basename, join as join10, relative as relative4 } from "node:path";
6863
7065
  var RECOVERY_NOTICE_MS = 7 * 24 * 60 * 60 * 1000;
6864
7066
  var RECOVERY_EVENTS = 50;
6865
7067
  var RECOVERY_ARCHIVE_MS = 30 * 24 * 60 * 60 * 1000;
@@ -6912,7 +7114,7 @@ function entries(path, maximum = 4096) {
6912
7114
  function size(path, limit = { left: 1e5 }) {
6913
7115
  let st;
6914
7116
  try {
6915
- st = lstatSync6(path);
7117
+ st = lstatSync7(path);
6916
7118
  } catch {
6917
7119
  return 0;
6918
7120
  }
@@ -6922,7 +7124,7 @@ function size(path, limit = { left: 1e5 }) {
6922
7124
  return st.size;
6923
7125
  let total = 0;
6924
7126
  for (const name of entries(path, 1e5))
6925
- total += size(join9(path, name), limit);
7127
+ total += size(join10(path, name), limit);
6926
7128
  return total;
6927
7129
  }
6928
7130
 
@@ -6932,12 +7134,12 @@ class RecoveryLog {
6932
7134
  archiveDirectory;
6933
7135
  constructor(files) {
6934
7136
  this.files = files;
6935
- this.logDirectory = join9(files.namespace, "recovery-log-v1");
6936
- this.archiveDirectory = join9(files.namespace, "recovery-archive-v1");
7137
+ this.logDirectory = join10(files.namespace, "recovery-log-v1");
7138
+ this.archiveDirectory = join10(files.namespace, "recovery-archive-v1");
6937
7139
  }
6938
7140
  archive() {
6939
7141
  const name = `${Date.now()}-${randomUUID6()}`;
6940
- const directory = join9(this.archiveDirectory, name);
7142
+ const directory = join10(this.archiveDirectory, name);
6941
7143
  let used = false;
6942
7144
  return {
6943
7145
  name,
@@ -6946,8 +7148,8 @@ class RecoveryLog {
6946
7148
  if (!rel || rel.startsWith(".."))
6947
7149
  throw new ContractError("forbidden");
6948
7150
  this.files.directory(directory, true);
6949
- const target = join9(directory, as ?? rel.split(/[\\/]/).join("--"));
6950
- retryWindowsFileOperation(() => renameSync2(path, target));
7151
+ const target = join10(directory, as ?? rel.split(/[\\/]/).join("--"));
7152
+ retryWindowsFileOperation(() => renameSync3(path, target));
6951
7153
  used = true;
6952
7154
  },
6953
7155
  used: () => used
@@ -6975,7 +7177,7 @@ class RecoveryLog {
6975
7177
  };
6976
7178
  decodeRecoveryEvent(value);
6977
7179
  try {
6978
- this.files.create(join9(this.logDirectory, `${value.at}-${value.id}.json`), encoded(value), EVENT_BYTES);
7180
+ this.files.create(join10(this.logDirectory, `${value.at}-${value.id}.json`), encoded(value), EVENT_BYTES);
6979
7181
  this.prune();
6980
7182
  } catch {}
6981
7183
  return value;
@@ -6984,7 +7186,7 @@ class RecoveryLog {
6984
7186
  for (const name of entries(this.logDirectory).reverse()) {
6985
7187
  if (!/^[0-9]{13}-[0-9a-f-]{36}\.json$/.test(name))
6986
7188
  continue;
6987
- const path = join9(this.logDirectory, name);
7189
+ const path = join10(this.logDirectory, name);
6988
7190
  const snapshot = this.files.read(path, EVENT_BYTES);
6989
7191
  if (!snapshot)
6990
7192
  return;
@@ -7004,7 +7206,7 @@ class RecoveryLog {
7004
7206
  if (!/^[0-9]{13}-[0-9a-f-]{36}\.json$/.test(name))
7005
7207
  continue;
7006
7208
  try {
7007
- const file = this.files.read(join9(this.logDirectory, name), EVENT_BYTES);
7209
+ const file = this.files.read(join10(this.logDirectory, name), EVENT_BYTES);
7008
7210
  if (file)
7009
7211
  out.push(decodeRecoveryEvent(json(file, EVENT_BYTES)));
7010
7212
  } catch {}
@@ -7014,13 +7216,13 @@ class RecoveryLog {
7014
7216
  prune(now = Date.now()) {
7015
7217
  const names2 = entries(this.logDirectory);
7016
7218
  for (const name of names2.slice(0, Math.max(0, names2.length - RECOVERY_EVENTS)))
7017
- rmSync(join9(this.logDirectory, name), { force: true });
7219
+ rmSync2(join10(this.logDirectory, name), { force: true });
7018
7220
  const archived = entries(this.archiveDirectory).filter((name) => /^[0-9]{13}-[0-9a-f-]{36}$/.test(name));
7019
7221
  const kept = [];
7020
7222
  for (const name of archived) {
7021
- const path = join9(this.archiveDirectory, name);
7223
+ const path = join10(this.archiveDirectory, name);
7022
7224
  if (now - Number(name.slice(0, 13)) > RECOVERY_ARCHIVE_MS)
7023
- rmSync(path, { recursive: true, force: true });
7225
+ rmSync2(path, { recursive: true, force: true });
7024
7226
  else
7025
7227
  kept.push({ name, bytes: size(path) });
7026
7228
  }
@@ -7028,7 +7230,7 @@ class RecoveryLog {
7028
7230
  for (const entry of kept) {
7029
7231
  if (total <= RECOVERY_ARCHIVE_BYTES)
7030
7232
  break;
7031
- rmSync(join9(this.archiveDirectory, entry.name), {
7233
+ rmSync2(join10(this.archiveDirectory, entry.name), {
7032
7234
  recursive: true,
7033
7235
  force: true
7034
7236
  });
@@ -7051,23 +7253,23 @@ class RecoveryLog {
7051
7253
  const names2 = entries(this.archiveDirectory);
7052
7254
  return {
7053
7255
  entries: names2.length,
7054
- bytes: names2.reduce((sum, name) => sum + size(join9(this.archiveDirectory, name)), 0)
7256
+ bytes: names2.reduce((sum, name) => sum + size(join10(this.archiveDirectory, name)), 0)
7055
7257
  };
7056
7258
  }
7057
7259
  }
7058
7260
  function strayTemporaries(directory) {
7059
- return entries(directory).filter((name) => /^pending-[0-9a-f-]{36}\.json$/.test(name)).map((name) => join9(directory, name));
7261
+ return entries(directory).filter((name) => /^pending-[0-9a-f-]{36}\.json$/.test(name)).map((name) => join10(directory, name));
7060
7262
  }
7061
7263
 
7062
7264
  // src/service/self-heal.ts
7063
7265
  import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
7064
- import { lstatSync as lstatSync7, opendirSync as opendirSync4 } from "node:fs";
7266
+ import { lstatSync as lstatSync8, opendirSync as opendirSync4 } from "node:fs";
7065
7267
  import { hostname as hostname5 } from "node:os";
7066
- import { join as join11 } from "node:path";
7268
+ import { join as join12 } from "node:path";
7067
7269
 
7068
7270
  // src/service/process-ledger.ts
7069
- import { rmSync as rmSync2 } from "node:fs";
7070
- import { join as join10 } from "node:path";
7271
+ import { rmSync as rmSync3 } from "node:fs";
7272
+ import { join as join11 } from "node:path";
7071
7273
  var LEDGER_BYTES = 64 * 1024;
7072
7274
  var LEDGER_WORKERS = 512;
7073
7275
  function decode2(value) {
@@ -7092,10 +7294,10 @@ class ProcessLedger {
7092
7294
  directory;
7093
7295
  constructor(files) {
7094
7296
  this.files = files;
7095
- this.directory = join10(files.namespace, "process-ledger-v1");
7297
+ this.directory = join11(files.namespace, "process-ledger-v1");
7096
7298
  }
7097
7299
  path(epoch) {
7098
- return join10(this.directory, `${decodeId(epoch)}.json`);
7300
+ return join11(this.directory, `${decodeId(epoch)}.json`);
7099
7301
  }
7100
7302
  file(epoch) {
7101
7303
  try {
@@ -7114,7 +7316,7 @@ class ProcessLedger {
7114
7316
  }
7115
7317
  remove(epoch) {
7116
7318
  try {
7117
- rmSync2(this.path(epoch), { force: true });
7319
+ rmSync3(this.path(epoch), { force: true });
7118
7320
  } catch {}
7119
7321
  }
7120
7322
  open(epoch) {
@@ -7289,7 +7491,7 @@ async function stopOwnerProcess(pid) {
7289
7491
  return gone();
7290
7492
  }
7291
7493
  for (let n = 0;n < 50; n++) {
7292
- await new Promise((resolve4) => setTimeout(resolve4, 100));
7494
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
7293
7495
  if (gone())
7294
7496
  return true;
7295
7497
  }
@@ -7297,7 +7499,7 @@ async function stopOwnerProcess(pid) {
7297
7499
  process.kill(pid, "SIGKILL");
7298
7500
  } catch {}
7299
7501
  for (let n = 0;n < 20; n++) {
7300
- await new Promise((resolve4) => setTimeout(resolve4, 100));
7502
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
7301
7503
  if (gone())
7302
7504
  return true;
7303
7505
  }
@@ -7314,7 +7516,7 @@ class RegistryHealer {
7314
7516
  this.ledger = new ProcessLedger(c.files);
7315
7517
  }
7316
7518
  path(name) {
7317
- return join11(this.c.registryDirectory, name);
7519
+ return join12(this.c.registryDirectory, name);
7318
7520
  }
7319
7521
  async heal(options = {}) {
7320
7522
  const lockPath = this.path("registry.lock");
@@ -7325,7 +7527,7 @@ class RegistryHealer {
7325
7527
  lock = undefined;
7326
7528
  const age = (() => {
7327
7529
  try {
7328
- return Date.now() - lstatSync7(lockPath).mtimeMs;
7530
+ return Date.now() - lstatSync8(lockPath).mtimeMs;
7329
7531
  } catch {
7330
7532
  return 0;
7331
7533
  }
@@ -7369,7 +7571,7 @@ class RegistryHealer {
7369
7571
  pid: mark?.pid ?? null
7370
7572
  };
7371
7573
  if (holder.state === "live") {
7372
- await new Promise((resolve4) => setTimeout(resolve4, 250));
7574
+ await new Promise((resolve5) => setTimeout(resolve5, 250));
7373
7575
  if (!this.c.files.read(lockPath))
7374
7576
  return { status: "clean" };
7375
7577
  return { status: "live" };
@@ -7479,14 +7681,14 @@ function liveReservations(c) {
7479
7681
  for (let e = dir.readSync();e; e = dir.readSync()) {
7480
7682
  if (!/^[a-f0-9]{64}$/.test(e.name))
7481
7683
  continue;
7482
- const service = join11(c.files.namespace, e.name, "service-v1");
7483
- const registration2 = readFile(c.files, join11(service, "registration.json"), decodeRegistrationLenient);
7684
+ const service = join12(c.files.namespace, e.name, "service-v1");
7685
+ const registration2 = readFile(c.files, join12(service, "registration.json"), decodeRegistrationLenient);
7484
7686
  if (!registration2 || registration2 === "unreadable")
7485
7687
  continue;
7486
7688
  const r = registration2.value;
7487
7689
  if (!r || r.phase === "stopped")
7488
7690
  continue;
7489
- const owner = readFile(c.files, join11(service, "owner.lock"), decodeOwnerLock);
7691
+ const owner = readFile(c.files, join12(service, "owner.lock"), decodeOwnerLock);
7490
7692
  const mark = owner && owner !== "unreadable" && owner.value ? owner.value : r;
7491
7693
  if (holderState(mark, stampTime(registration2.snapshot.stamp)).state !== "live")
7492
7694
  continue;
@@ -7507,20 +7709,20 @@ function liveReservations(c) {
7507
7709
  return out;
7508
7710
  }
7509
7711
  function projectFiles(c, root) {
7510
- const privateRoot = join11(c.files.namespace, createHash5("sha256").update(root).digest("hex"));
7712
+ const privateRoot = join12(c.files.namespace, createHash5("sha256").update(root).digest("hex"));
7511
7713
  return {
7512
7714
  root,
7513
7715
  privateRoot,
7514
- service: join11(privateRoot, "service-v1"),
7515
- checkoutPath: join11(privateRoot, "checkout.lock")
7716
+ service: join12(privateRoot, "service-v1"),
7717
+ checkoutPath: join12(privateRoot, "checkout.lock")
7516
7718
  };
7517
7719
  }
7518
7720
  function snapshotProject(c, p) {
7519
7721
  const s = { temporaries: [] };
7520
- s.registration = readFile(c.files, join11(p.service, "registration.json"), decodeRegistrationLenient);
7521
- s.owner = readFile(c.files, join11(p.service, "owner.lock"), decodeOwnerLock);
7722
+ s.registration = readFile(c.files, join12(p.service, "registration.json"), decodeRegistrationLenient);
7723
+ s.owner = readFile(c.files, join12(p.service, "owner.lock"), decodeOwnerLock);
7522
7724
  try {
7523
- s.capability = c.files.read(join11(p.service, "local-capability.json"));
7725
+ s.capability = c.files.read(join12(p.service, "local-capability.json"));
7524
7726
  } catch {
7525
7727
  s.capability = "unreadable";
7526
7728
  }
@@ -7535,7 +7737,7 @@ function snapshotProject(c, p) {
7535
7737
  } catch {}
7536
7738
  s.temporaries = [
7537
7739
  ...strayTemporaries(p.service),
7538
- ...strayTemporaries(join11(p.service, "history-v2"))
7740
+ ...strayTemporaries(join12(p.service, "history-v2"))
7539
7741
  ];
7540
7742
  return s;
7541
7743
  }
@@ -7648,8 +7850,8 @@ function metadataDamaged(c, p) {
7648
7850
  return false;
7649
7851
  }
7650
7852
  try {
7651
- const format = c.files.read(join11(p.service, "format.json"));
7652
- const config = c.files.read(join11(p.service, "config.json"));
7853
+ const format = c.files.read(join12(p.service, "format.json"));
7854
+ const config = c.files.read(join12(p.service, "config.json"));
7653
7855
  if (!format || !config)
7654
7856
  return true;
7655
7857
  const f = closed(json(format), [
@@ -7661,10 +7863,10 @@ function metadataDamaged(c, p) {
7661
7863
  if (f.schema !== "cadence-service-format/1" || f.root !== p.root || f.stateHome !== c.stateHome || f.configIdentity !== config.identity)
7662
7864
  return true;
7663
7865
  const selected = decodeOwnerConfig(json(config));
7664
- const host = c.files.read(join11(p.service, "host-config.json"));
7866
+ const host = c.files.read(join12(p.service, "host-config.json"));
7665
7867
  if (host && host.identity !== selected.policyIdentity)
7666
7868
  return true;
7667
- const registration2 = c.files.read(join11(p.service, "registration.json"));
7869
+ const registration2 = c.files.read(join12(p.service, "registration.json"));
7668
7870
  if (registration2) {
7669
7871
  const r = decodeRegistration(json(registration2));
7670
7872
  if (r.root !== p.root || r.stateHome !== c.stateHome || r.configIdentity !== config.identity)
@@ -7687,7 +7889,7 @@ function reclaim(c, p, expected, archive) {
7687
7889
  mutate();
7688
7890
  const registration2 = s.registration;
7689
7891
  if (registration2 === "unreadable")
7690
- archive.keep(join11(p.service, "registration.json"));
7892
+ archive.keep(join12(p.service, "registration.json"));
7691
7893
  else if (registration2) {
7692
7894
  if (!registration2.value)
7693
7895
  archive.keep(registration2.path);
@@ -7695,7 +7897,7 @@ function reclaim(c, p, expected, archive) {
7695
7897
  c.files.replace(registration2.path, registration2.snapshot, encoded({ ...registration2.value, phase: "stopped" }));
7696
7898
  }
7697
7899
  if (s.row)
7698
- c.files.replace(join11(c.registryDirectory, "roots.json"), view.snapshot, encoded({
7900
+ c.files.replace(join12(c.registryDirectory, "roots.json"), view.snapshot, encoded({
7699
7901
  ...view.value,
7700
7902
  entries: view.value.entries.filter((row) => row.root !== p.root)
7701
7903
  }), 1024 * 1024);
@@ -7708,8 +7910,8 @@ function reclaim(c, p, expected, archive) {
7708
7910
  }
7709
7911
  c.files.remove(path, "snapshot" in value ? value.snapshot : value, maximum);
7710
7912
  };
7711
- drop(join11(p.service, "local-capability.json"), s.capability);
7712
- drop(join11(p.service, "owner.lock"), s.owner);
7913
+ drop(join12(p.service, "local-capability.json"), s.capability);
7914
+ drop(join12(p.service, "owner.lock"), s.owner);
7713
7915
  drop(p.checkoutPath, s.checkout, 8192);
7714
7916
  });
7715
7917
  }
@@ -7876,7 +8078,7 @@ async function confirm(question) {
7876
8078
  return false;
7877
8079
  const rl = createInterface({ input: process.stdin, output: process.stderr });
7878
8080
  try {
7879
- const answer = await new Promise((resolve4) => rl.question(`${question} [y/N] `, resolve4));
8081
+ const answer = await new Promise((resolve5) => rl.question(`${question} [y/N] `, resolve5));
7880
8082
  return /^y(es)?$/i.test(answer.trim());
7881
8083
  } finally {
7882
8084
  rl.close();
@@ -7918,12 +8120,12 @@ async function healProjectForStart(c, responsive) {
7918
8120
  }
7919
8121
 
7920
8122
  // src/service/runtime.ts
7921
- import { homedir as homedir2 } from "node:os";
7922
- import { dirname as dirname7, isAbsolute as isAbsolute5, join as join12, resolve as resolve4 } from "node:path";
8123
+ import { homedir as homedir3 } from "node:os";
8124
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join13, resolve as resolve5 } from "node:path";
7923
8125
  var STARTUP_INPUT_BYTES = 16 * 1024;
7924
8126
  function absolute(value) {
7925
8127
  const result = text(value, 4096, true);
7926
- if (!isAbsolute5(result))
8128
+ if (!isAbsolute6(result))
7927
8129
  throw new ContractError("invalid");
7928
8130
  return result;
7929
8131
  }
@@ -8013,7 +8215,7 @@ function selectStart(options, ambient) {
8013
8215
  throw new ContractError("invalid");
8014
8216
  let fromFile;
8015
8217
  if (options.config) {
8016
- const path = resolve4(options.config), f = new PrivateFiles(dirname7(path));
8218
+ const path = resolve5(options.config), f = new PrivateFiles(dirname8(path));
8017
8219
  const bytes = f.read(path);
8018
8220
  if (!bytes)
8019
8221
  throw new ContractError("corrupt-selected");
@@ -8028,11 +8230,11 @@ function selectStart(options, ambient) {
8028
8230
  port: options.port ?? 17423,
8029
8231
  proxy: null
8030
8232
  },
8031
- agentDir: resolve4(options.agentDir ?? ambient.PI_CODING_AGENT_DIR ?? join12(ambient.HOME ?? ambient.USERPROFILE ?? homedir2(), ".pi", "agent")),
8233
+ agentDir: resolve5(options.agentDir ?? ambient.PI_CODING_AGENT_DIR ?? join13(ambient.HOME ?? ambient.USERPROFILE ?? homedir3(), ".pi", "agent")),
8032
8234
  tokenSource: options.tokenFile ? "file" : env ? "environment" : "generated",
8033
- tokenFile: options.tokenFile ? resolve4(options.tokenFile) : null
8235
+ tokenFile: options.tokenFile ? resolve5(options.tokenFile) : null
8034
8236
  });
8035
- const server = options.serverConfig !== undefined ? resolve4(options.serverConfig) : old?.tokenSource === "config" ? old.tokenFile : null;
8237
+ const server = options.serverConfig !== undefined ? resolve5(options.serverConfig) : old?.tokenSource === "config" ? old.tokenFile : null;
8036
8238
  let selected = base;
8037
8239
  if (server) {
8038
8240
  if (options.tokenFile !== undefined)
@@ -8045,7 +8247,7 @@ function selectStart(options, ambient) {
8045
8247
  tokenFile: server
8046
8248
  });
8047
8249
  }
8048
- if (fromFile && encoded(fromFile) !== encoded(selected) || options.port !== undefined && options.port !== selected.http.port || options.host !== undefined && options.host !== selected.http.host || options.agentDir !== undefined && resolve4(options.agentDir) !== selected.agentDir || options.tokenFile !== undefined && resolve4(options.tokenFile) !== selected.tokenFile || env && selected.tokenSource !== "environment" || selected.tokenSource === "environment" && !env || resolveWorkspace(selected.cwd).root !== workspace.root)
8250
+ if (fromFile && encoded(fromFile) !== encoded(selected) || options.port !== undefined && options.port !== selected.http.port || options.host !== undefined && options.host !== selected.http.host || options.agentDir !== undefined && resolve5(options.agentDir) !== selected.agentDir || options.tokenFile !== undefined && resolve5(options.tokenFile) !== selected.tokenFile || env && selected.tokenSource !== "environment" || selected.tokenSource === "environment" && !env || resolveWorkspace(selected.cwd).root !== workspace.root)
8049
8251
  throw new ContractError("conflict");
8050
8252
  return {
8051
8253
  workspace: workspace.root,
@@ -8112,13 +8314,175 @@ function decodeStartupReport(value) {
8112
8314
  };
8113
8315
  }
8114
8316
 
8317
+ // src/service/maintenance.ts
8318
+ import { spawn, spawnSync as spawnSync4 } from "node:child_process";
8319
+ import { accessSync, constants as constants3, readFileSync as readFileSync3, realpathSync as realpathSync5 } from "node:fs";
8320
+ import { dirname as dirname9, join as join14 } from "node:path";
8321
+ var PACKAGE = "@abelxiaoxing/cadence";
8322
+ var JOB_SECONDS = 1800;
8323
+ var VIEW_MS = 30000;
8324
+ var INSTALL_MS = 15 * 60000;
8325
+ var RESTART_MS = 5 * 60000;
8326
+ function cgroupPath(text2) {
8327
+ const lines = text2?.split(`
8328
+ `) ?? [];
8329
+ const find = (pattern) => lines.map((line) => pattern.exec(line)?.[1]).find(Boolean);
8330
+ return find(/^\d+:name=systemd:(\/.*)$/) ?? find(/^0::(\/.*)$/);
8331
+ }
8332
+ function supervisingUnit(env, system) {
8333
+ const path = cgroupPath(system({}).cgroup());
8334
+ const match = path && /\/cadence(?:-([A-Za-z0-9][A-Za-z0-9_-]{0,47}))?\.service$/.exec(path);
8335
+ if (!path || !match || !env.INVOCATION_ID)
8336
+ return;
8337
+ const s = system({
8338
+ scope: /\/user@[0-9]+\.service\//.test(path) ? "user" : "system",
8339
+ name: match[1]
8340
+ });
8341
+ const invocation = s.systemctl(["show", "--property=InvocationID", "--value", s.unit]).stdout.trim();
8342
+ if (invocation !== env.INVOCATION_ID)
8343
+ return;
8344
+ const text2 = generatedUnit(s);
8345
+ return typeof text2 === "string" && unitWorkspace(text2) === null ? s : undefined;
8346
+ }
8347
+ function maintenanceUnit(s) {
8348
+ return s.unit.replace(/\.service$/, ".maintenance.service");
8349
+ }
8350
+ function installedVersion(root) {
8351
+ const value = JSON.parse(readFileSync3(join14(root, "package.json"), "utf8"));
8352
+ if (!value || typeof value !== "object" || !("name" in value))
8353
+ throw new ContractError("invalid");
8354
+ literal(value.name, PACKAGE);
8355
+ return decodeVersion("version" in value ? value.version : undefined);
8356
+ }
8357
+
8358
+ class MaintenanceRecord {
8359
+ store;
8360
+ constructor(store) {
8361
+ this.store = store;
8362
+ }
8363
+ get path() {
8364
+ return this.store.path("maintenance.json");
8365
+ }
8366
+ read() {
8367
+ const file = this.store.files.read(this.path);
8368
+ if (!file)
8369
+ return null;
8370
+ const o = closed(json(file), ["schema", "job"]);
8371
+ literal(o.schema, "cadence-maintenance-job/1");
8372
+ return decodeMaintenanceJob(o.job);
8373
+ }
8374
+ write(job2) {
8375
+ const bytes = encoded({ schema: "cadence-maintenance-job/1", job: job2 });
8376
+ const current = this.store.files.read(this.path);
8377
+ if (current)
8378
+ this.store.files.replace(this.path, current, bytes);
8379
+ else
8380
+ this.store.files.create(this.path, bytes);
8381
+ }
8382
+ finish(id, state, reason, version) {
8383
+ const job2 = this.read();
8384
+ if (job2?.id !== id || job2.state !== "running")
8385
+ return;
8386
+ this.write({ ...job2, state, reason, version, endedAt: Date.now() });
8387
+ }
8388
+ }
8389
+ function launchJob(s, job2) {
8390
+ const text2 = generatedUnit(s);
8391
+ if (typeof text2 !== "string")
8392
+ return false;
8393
+ const scope = s.scope === "system" ? "--system" : "--user";
8394
+ const name = serviceName(s);
8395
+ const result = spawnSync4("systemd-run", [
8396
+ scope,
8397
+ `--unit=${maintenanceUnit(s)}`,
8398
+ `--description=Cadence ${job2.action} requested from the WebUI`,
8399
+ "--collect",
8400
+ "--quiet",
8401
+ `--property=RuntimeMaxSec=${JOB_SECONDS}`,
8402
+ ...[...new Map([["HOME", s.home], ...unitEnvironment(text2)])].map(([key, value]) => `--setenv=${key}=${value}`),
8403
+ "--",
8404
+ s.node,
8405
+ join14(s.root, "src", "service-cli.mjs"),
8406
+ "server",
8407
+ job2.action,
8408
+ scope,
8409
+ ...name ? ["--name", name] : [],
8410
+ ...job2.to ? ["--to", job2.to] : [],
8411
+ "--job",
8412
+ job2.id
8413
+ ], { stdio: "ignore", timeout: 20000 });
8414
+ return !result.error && result.status === 0;
8415
+ }
8416
+ function jobRunning(s) {
8417
+ return s.systemctl(["is-active", "--quiet", maintenanceUnit(s)]).status === 0;
8418
+ }
8419
+ var npm = (args, show = false) => run("npm", args, show ? INSTALL_MS : VIEW_MS, show);
8420
+ function run(command, args, timeout, show = false) {
8421
+ return new Promise((resolve6) => {
8422
+ const child = spawn(command, args, {
8423
+ stdio: ["ignore", show ? 2 : "pipe", show ? 2 : "ignore"],
8424
+ timeout,
8425
+ windowsHide: true
8426
+ });
8427
+ let stdout = "";
8428
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => {
8429
+ if (stdout.length < 1 << 20)
8430
+ stdout += chunk;
8431
+ });
8432
+ child.once("error", () => resolve6({ status: null, stdout: "" }));
8433
+ child.once("close", (status) => resolve6({ status, stdout }));
8434
+ });
8435
+ }
8436
+ async function upgradeRoute(root, npmRun = npm) {
8437
+ const result = await npmRun(["root", "--global"]);
8438
+ const global = result.status === 0 ? result.stdout.trim() : "";
8439
+ let installed;
8440
+ try {
8441
+ installed = realpathSync5(join14(global, ...PACKAGE.split("/")));
8442
+ if (!global || installed !== realpathSync5(root))
8443
+ return "not-npm-global";
8444
+ } catch {
8445
+ return "not-npm-global";
8446
+ }
8447
+ try {
8448
+ accessSync(dirname9(installed), constants3.W_OK);
8449
+ accessSync(global, constants3.W_OK);
8450
+ } catch {
8451
+ return "not-writable";
8452
+ }
8453
+ return "npm";
8454
+ }
8455
+ async function release(spec = "latest", npmRun = npm) {
8456
+ const result = await npmRun([
8457
+ "view",
8458
+ `${PACKAGE}@${spec}`,
8459
+ "version",
8460
+ "deprecated",
8461
+ "--json"
8462
+ ]);
8463
+ if (result.status !== 0)
8464
+ return;
8465
+ try {
8466
+ const value = JSON.parse(result.stdout);
8467
+ if (typeof value === "string")
8468
+ return { version: decodeVersion(value), deprecated: false };
8469
+ const o = closed(value, ["version", "deprecated"]);
8470
+ return {
8471
+ version: decodeVersion(o.version),
8472
+ deprecated: typeof o.deprecated === "string"
8473
+ };
8474
+ } catch {
8475
+ return;
8476
+ }
8477
+ }
8478
+
8115
8479
  // src/service/cli.ts
8116
8480
  function nativeCall(c, operation, reveal = false, controlBody) {
8117
8481
  const access = c.localAccess();
8118
8482
  const url = new URL(`${access.endpoint}/local/v1/admin/${operation}`);
8119
8483
  const write2 = !["status", "diagnose"].includes(operation);
8120
8484
  const body = write2 ? JSON.stringify(controlBody ?? (reveal ? { reveal: true } : {})) : undefined;
8121
- return new Promise((resolve6, reject) => {
8485
+ return new Promise((resolve7, reject) => {
8122
8486
  let timer;
8123
8487
  const fail = () => {
8124
8488
  clearTimeout(timer);
@@ -8159,7 +8523,7 @@ function nativeCall(c, operation, reveal = false, controlBody) {
8159
8523
  throw new ContractError("stale");
8160
8524
  }
8161
8525
  clearTimeout(timer);
8162
- resolve6(reply.value);
8526
+ resolve7(reply.value);
8163
8527
  } catch {
8164
8528
  fail();
8165
8529
  }
@@ -8174,7 +8538,7 @@ function nativeCall(c, operation, reveal = false, controlBody) {
8174
8538
  req.end(body);
8175
8539
  });
8176
8540
  }
8177
- var pause = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
8541
+ var pause = (ms) => new Promise((resolve7) => setTimeout(resolve7, ms));
8178
8542
  async function serviceStatus(c, diagnose = false) {
8179
8543
  const registryLock = c.registryLockDiagnostic?.();
8180
8544
  if (registryLock)
@@ -8274,10 +8638,10 @@ function startupGuidance(result, input) {
8274
8638
  return `Pi's agent directory ${agent} must be an existing real directory (not a symlink) owned by you.
8275
8639
  `;
8276
8640
  case "pi-auth":
8277
- return `${join13(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
8641
+ return `${join15(agent, "auth.json")} must be your own single-link regular file holding valid Pi credentials; log in to Pi first.
8278
8642
  `;
8279
8643
  case "pi-models":
8280
- return `${join13(agent, "models.json")} must be your own single-link regular file using only fields Cadence's pinned Pi SDK supports; a field only newer Pi understands is refused.
8644
+ return `${join15(agent, "models.json")} must be your own single-link regular file using only fields Cadence's pinned Pi SDK supports; a field only newer Pi understands is refused.
8281
8645
  `;
8282
8646
  case "pi-runtime":
8283
8647
  return `Loading Pi's SDK model runtime failed (optional SDK packages missing, or sources the SDK refuses). Fix that and start again; the next start recovers the owner's registration automatically.
@@ -8337,7 +8701,7 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8337
8701
  throw new ContractError("oversize");
8338
8702
  if (!sameNetwork(network, networkSnapshot(process.env)))
8339
8703
  throw new ContractError("stale");
8340
- const child = spawn(process.execPath, [
8704
+ const child = spawn2(process.execPath, [
8341
8705
  ...env.NODE_USE_ENV_PROXY === "1" ? ["--use-env-proxy"] : [],
8342
8706
  fileURLToPath2(hostUrl)
8343
8707
  ], {
@@ -8348,18 +8712,18 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8348
8712
  stdio: ["pipe", "pipe", "ignore"]
8349
8713
  });
8350
8714
  let completed = false;
8351
- const closure = new Promise((resolve6) => child.once("close", (code2, signal) => {
8715
+ const closure = new Promise((resolve7) => child.once("close", (code2, signal) => {
8352
8716
  completed = true;
8353
8717
  if (foreground && (code2 !== 0 || signal !== null))
8354
8718
  process.exitCode = 1;
8355
- resolve6();
8719
+ resolve7();
8356
8720
  }));
8357
- const startup = new Promise((resolve6) => {
8721
+ const startup = new Promise((resolve7) => {
8358
8722
  let bytes = "", resolved = false;
8359
8723
  const finish = (value) => {
8360
8724
  if (!resolved) {
8361
8725
  resolved = true;
8362
- resolve6(value);
8726
+ resolve7(value);
8363
8727
  }
8364
8728
  };
8365
8729
  child.on("error", () => finish({ status: "unconfirmed" }));
@@ -8399,8 +8763,8 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8399
8763
  let timer;
8400
8764
  const result = await Promise.race([
8401
8765
  startup,
8402
- new Promise((resolve6) => {
8403
- timer = setTimeout(() => resolve6({ status: "unconfirmed" }), LIMITS.startWaitMs);
8766
+ new Promise((resolve7) => {
8767
+ timer = setTimeout(() => resolve7({ status: "unconfirmed" }), LIMITS.startWaitMs);
8404
8768
  })
8405
8769
  ]);
8406
8770
  clearTimeout(timer);
@@ -8425,12 +8789,34 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8425
8789
  }
8426
8790
  async function privateLink(workspace, stateHome, config) {
8427
8791
  try {
8428
- const value = closed(await nativeCall(workspace === null ? new GatewayStore(config ?? serverConfigPath(homedir3()), stateHome) : new ServiceCoordination(workspace, stateHome), "token-link", true), ["link"]);
8792
+ const value = closed(await nativeCall(workspace === null ? new GatewayStore(config ?? serverConfigPath(homedir4()), stateHome) : new ServiceCoordination(workspace, stateHome), "token-link", true), ["link"]);
8429
8793
  return text(value.link, 4096, true);
8430
8794
  } catch {
8431
8795
  return;
8432
8796
  }
8433
8797
  }
8798
+ var ownerControl = {
8799
+ async ownerStatus(workspace, config) {
8800
+ try {
8801
+ const observed = await serviceStatus(workspace === null ? new GatewayStore(config ?? serverConfigPath(homedir4())) : new ServiceCoordination(workspace));
8802
+ return observed && typeof observed === "object" && "status" in observed ? String(observed.status) : "unavailable";
8803
+ } catch {
8804
+ return "unavailable";
8805
+ }
8806
+ },
8807
+ async stopOwner(workspace, config) {
8808
+ try {
8809
+ const c = workspace === null ? new GatewayStore(config ?? serverConfigPath(homedir4())) : new ServiceCoordination(workspace);
8810
+ const observed = await serviceStatus(c);
8811
+ const status = observed && typeof observed === "object" && "status" in observed ? String(observed.status) : "unavailable";
8812
+ if (status === "absent" || status === "stopped")
8813
+ return "stopped";
8814
+ return status === "alive" ? (await stopService(c)).status : status;
8815
+ } catch {
8816
+ return "unavailable";
8817
+ }
8818
+ }
8819
+ };
8434
8820
  class ProjectOpenRefusal extends ContractError {
8435
8821
  noOwner;
8436
8822
  constructor(noOwner, code2 = "unavailable") {
@@ -8627,14 +9013,14 @@ Content-Length: 0\r
8627
9013
  async listen() {
8628
9014
  if (this.origin || this.stopped)
8629
9015
  throw new ContractError("conflict");
8630
- await new Promise((resolve6, reject) => {
9016
+ await new Promise((resolve7, reject) => {
8631
9017
  const failed = () => {
8632
9018
  this.server.off("listening", ready);
8633
9019
  reject(new ContractError("unavailable"));
8634
9020
  };
8635
9021
  const ready = () => {
8636
9022
  this.server.off("error", failed);
8637
- resolve6();
9023
+ resolve7();
8638
9024
  };
8639
9025
  this.server.once("error", failed);
8640
9026
  this.server.once("listening", ready);
@@ -8664,13 +9050,13 @@ Content-Length: 0\r
8664
9050
  close() {
8665
9051
  if (this.closePromise)
8666
9052
  return this.closePromise;
8667
- let resolve6;
9053
+ let resolve7;
8668
9054
  let reject;
8669
9055
  this.closePromise = new Promise((yes, no) => {
8670
- resolve6 = yes;
9056
+ resolve7 = yes;
8671
9057
  reject = no;
8672
9058
  });
8673
- this.closeTransport().then(resolve6, () => reject(new ContractError("unavailable")));
9059
+ this.closeTransport().then(resolve7, () => reject(new ContractError("unavailable")));
8674
9060
  return this.closePromise;
8675
9061
  }
8676
9062
  async closeTransport() {
@@ -8682,18 +9068,18 @@ Content-Length: 0\r
8682
9068
  request2.abort();
8683
9069
  for (const attachment of [...this.attachments.values()])
8684
9070
  this.detach(attachment);
8685
- const closedSockets = [...this.sockets].map((socket) => new Promise((resolve6) => {
9071
+ const closedSockets = [...this.sockets].map((socket) => new Promise((resolve7) => {
8686
9072
  if (socket.closed)
8687
- resolve6();
9073
+ resolve7();
8688
9074
  else {
8689
- socket.once("close", () => resolve6());
9075
+ socket.once("close", () => resolve7());
8690
9076
  socket.destroy();
8691
9077
  }
8692
9078
  }));
8693
- const listener = new Promise((resolve6, reject) => {
8694
- this.server.close((error) => error ? reject(new ContractError("unavailable")) : resolve6());
9079
+ const listener = new Promise((resolve7, reject) => {
9080
+ this.server.close((error) => error ? reject(new ContractError("unavailable")) : resolve7());
8695
9081
  });
8696
- const upgrades = new Promise((resolve6) => this.wss.close(() => resolve6()));
9082
+ const upgrades = new Promise((resolve7) => this.wss.close(() => resolve7()));
8697
9083
  await Promise.all([listener, upgrades, ...closedSockets]);
8698
9084
  }
8699
9085
  attachment(caller) {
@@ -9101,7 +9487,7 @@ Content-Length: 0\r
9101
9487
  if (signal.aborted || res.destroyed)
9102
9488
  unavailable();
9103
9489
  const chunk = data.subarray(offset, offset + LIMITS.detailPageBytes);
9104
- await new Promise((resolve6, reject) => {
9490
+ await new Promise((resolve7, reject) => {
9105
9491
  const stop = () => {
9106
9492
  res.destroy();
9107
9493
  reject(new ContractError("unavailable"));
@@ -9109,7 +9495,7 @@ Content-Length: 0\r
9109
9495
  signal.addEventListener("abort", stop, { once: true });
9110
9496
  res.write(chunk, (error) => {
9111
9497
  signal.removeEventListener("abort", stop);
9112
- error ? reject(new ContractError("unavailable")) : resolve6();
9498
+ error ? reject(new ContractError("unavailable")) : resolve7();
9113
9499
  });
9114
9500
  });
9115
9501
  activity();
@@ -9331,16 +9717,16 @@ Content-Length: 0\r
9331
9717
  // src/service/workbench-files.ts
9332
9718
  import {
9333
9719
  closeSync as closeSync4,
9334
- constants as constants3,
9720
+ constants as constants4,
9335
9721
  fstatSync as fstatSync3,
9336
- lstatSync as lstatSync8,
9722
+ lstatSync as lstatSync9,
9337
9723
  opendirSync as opendirSync5,
9338
9724
  openSync as openSync4,
9339
9725
  readSync as readSync3,
9340
- realpathSync as realpathSync4
9726
+ realpathSync as realpathSync6
9341
9727
  } from "node:fs";
9342
- import { homedir as homedir4 } from "node:os";
9343
- import { dirname as dirname9, isAbsolute as isAbsolute6, join as join14, relative as relative5, resolve as resolve6, sep as sep4 } from "node:path";
9728
+ import { homedir as homedir5 } from "node:os";
9729
+ import { dirname as dirname11, isAbsolute as isAbsolute7, join as join16, relative as relative5, resolve as resolve7, sep as sep5 } from "node:path";
9344
9730
 
9345
9731
  // src/worker-redaction.mjs
9346
9732
  var marker = "[redacted]";
@@ -9799,7 +10185,7 @@ class DetailSanitizer {
9799
10185
  // src/service/workbench-files.ts
9800
10186
  function inside(root, path) {
9801
10187
  const r = relative5(root, path);
9802
- return r === "" || !isAbsolute6(r) && r !== ".." && !r.startsWith(`..${sep4}`);
10188
+ return r === "" || !isAbsolute7(r) && r !== ".." && !r.startsWith(`..${sep5}`);
9803
10189
  }
9804
10190
  var sensitive2 = (name) => /^\.(?:git|ssh|aws|azure|gnupg|kube|npmrc|pypirc|netrc)$/i.test(name) || /^\.env(?:\.|$)/i.test(name) || /^(?:auth|models|credentials|service-account)\.json$/i.test(name) || /^id_(?:rsa|dsa|ecdsa|ed25519)(?:\.|$)/i.test(name) || /\.(?:pem|key|p12|pfx)$/i.test(name);
9805
10191
 
@@ -9809,39 +10195,39 @@ class WorkbenchFiles {
9809
10195
  excluded;
9810
10196
  constructor(root, excluded, secrets) {
9811
10197
  this.secrets = secrets;
9812
- this.root = realpathSync4(root);
10198
+ this.root = realpathSync6(root);
9813
10199
  this.excluded = excluded.flatMap((path) => [
9814
- resolve6(path),
10200
+ resolve7(path),
9815
10201
  canonicalAmbientRoot(path)
9816
10202
  ]);
9817
10203
  }
9818
10204
  allowed(path) {
9819
10205
  if (path.split(/[\\/]/).some(sensitive2) || this.excluded.some((root) => inside(root, path)))
9820
10206
  throw new ContractError("forbidden");
9821
- const stat = lstatSync8(path);
10207
+ const stat = lstatSync9(path);
9822
10208
  if (stat.isSymbolicLink() || stat.isFile() && stat.nlink !== 1 || process.platform !== "win32" && process.getuid && stat.uid !== process.getuid())
9823
10209
  throw new ContractError("forbidden");
9824
10210
  }
9825
10211
  directory(path) {
9826
- if (!isAbsolute6(path) || !safeDirectory(path))
10212
+ if (!isAbsolute7(path) || !safeDirectory(path))
9827
10213
  throw new ContractError("invalid");
9828
- const canonical = realpathSync4(path);
10214
+ const canonical = realpathSync6(path);
9829
10215
  this.allowed(canonical);
9830
10216
  return canonical;
9831
10217
  }
9832
10218
  selected(path) {
9833
- if (isAbsolute6(path) || path.split(/[\\/]/).some((part) => part === ".." || sensitive2(part)))
10219
+ if (isAbsolute7(path) || path.split(/[\\/]/).some((part) => part === ".." || sensitive2(part)))
9834
10220
  throw new ContractError("forbidden");
9835
- const target = resolve6(this.root, path);
9836
- if (!inside(this.root, target) || !safeDirectory(dirname9(target)))
10221
+ const target = resolve7(this.root, path);
10222
+ if (!inside(this.root, target) || !safeDirectory(dirname11(target)))
9837
10223
  throw new ContractError("forbidden");
9838
10224
  this.allowed(target);
9839
- if (lstatSync8(target).isSymbolicLink())
10225
+ if (lstatSync9(target).isSymbolicLink())
9840
10226
  throw new ContractError("forbidden");
9841
10227
  return target;
9842
10228
  }
9843
10229
  browsed(path) {
9844
- const full = /^~(?:[\\/]|$)/.test(path) ? join14(homedir4(), path.slice(1)) : path || this.root;
10230
+ const full = /^~(?:[\\/]|$)/.test(path) ? join16(homedir5(), path.slice(1)) : path || this.root;
9845
10231
  try {
9846
10232
  return this.directory(full);
9847
10233
  } catch (error) {
@@ -9864,13 +10250,13 @@ class WorkbenchFiles {
9864
10250
  }
9865
10251
  if (sensitive2(entry.name) || entry.isSymbolicLink() || !entry.isFile() && !entry.isDirectory() || directories && !entry.isDirectory())
9866
10252
  continue;
9867
- const absolute2 = join14(selected, entry.name);
10253
+ const absolute2 = join16(selected, entry.name);
9868
10254
  try {
9869
10255
  this.allowed(absolute2);
9870
10256
  } catch {
9871
10257
  continue;
9872
10258
  }
9873
- const wire = directories ? absolute2 : relative5(this.root, absolute2).split(sep4).join("/");
10259
+ const wire = directories ? absolute2 : relative5(this.root, absolute2).split(sep5).join("/");
9874
10260
  if (sanitizeText(wire, this.secrets()) !== wire)
9875
10261
  continue;
9876
10262
  if (entries2.length >= 200) {
@@ -9887,20 +10273,20 @@ class WorkbenchFiles {
9887
10273
  dir.closeSync();
9888
10274
  }
9889
10275
  entries2.sort((a, b) => Number(b.directory) - Number(a.directory) || a.name.localeCompare(b.name));
9890
- const parent = dirname9(selected);
10276
+ const parent = dirname11(selected);
9891
10277
  return {
9892
10278
  kind: directories ? "directories" : "files",
9893
10279
  path: directories ? selected : path,
9894
- parent: directories ? parent === selected ? null : parent : selected === this.root ? null : relative5(this.root, parent).split(sep4).join("/"),
10280
+ parent: directories ? parent === selected ? null : parent : selected === this.root ? null : relative5(this.root, parent).split(sep5).join("/"),
9895
10281
  entries: entries2,
9896
10282
  limited
9897
10283
  };
9898
10284
  }
9899
10285
  read(path) {
9900
- const selected = this.selected(path), before = lstatSync8(selected);
10286
+ const selected = this.selected(path), before = lstatSync9(selected);
9901
10287
  if (!before.isFile())
9902
10288
  throw new ContractError("forbidden");
9903
- const fd = openSync4(selected, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
10289
+ const fd = openSync4(selected, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
9904
10290
  try {
9905
10291
  const opened = fstatSync3(fd);
9906
10292
  if (!opened.isFile() || opened.nlink !== 1 || before.dev !== opened.dev || before.ino !== opened.ino)
@@ -9913,7 +10299,7 @@ class WorkbenchFiles {
9913
10299
  break;
9914
10300
  at += n;
9915
10301
  }
9916
- const after = fstatSync3(fd), current = lstatSync8(selected);
10302
+ const after = fstatSync3(fd), current = lstatSync9(selected);
9917
10303
  if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.nlink !== 1 || current.isSymbolicLink() || current.nlink !== 1 || current.ino !== opened.ino || current.dev !== opened.dev)
9918
10304
  throw new ContractError("stale");
9919
10305
  const decoded2 = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, at), { stream: at < opened.size });
@@ -9947,7 +10333,7 @@ async function createGateway(value, hostUrl, source) {
9947
10333
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
9948
10334
  const web = loadWebAssets(source?.webDirectory);
9949
10335
  const build2 = {
9950
- contractHash: "45f3666b0fc0d853e95e618b50156819f6282ce648e9703b876d9658ae15b78f",
10336
+ contractHash: "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65",
9951
10337
  assets: {
9952
10338
  sourceHash: web.manifest.sourceHash,
9953
10339
  contractHash: web.manifest.contractHash,
@@ -9999,11 +10385,11 @@ Content-Length: 0\r
9999
10385
  \r
10000
10386
  `));
10001
10387
  server.on("checkContinue", (_req, res) => reply(res, 400, { kind: "error", error: publicError("invalid") }));
10002
- await new Promise((resolve7, reject) => {
10388
+ await new Promise((resolve8, reject) => {
10003
10389
  server.once("error", reject);
10004
10390
  server.listen(input.policy.port, input.policy.host, () => {
10005
10391
  server.off("error", reject);
10006
- resolve7();
10392
+ resolve8();
10007
10393
  });
10008
10394
  });
10009
10395
  const address = server.address();
@@ -10049,12 +10435,90 @@ Content-Length: 0\r
10049
10435
  server.close();
10050
10436
  throw error;
10051
10437
  }
10052
- const files = new WorkbenchFiles(homedir5(), [store.files.namespace, input.agentDir], () => acquired.access.redactionLiterals());
10438
+ const files = new WorkbenchFiles(homedir6(), [store.files.namespace, input.agentDir], () => acquired.access.redactionLiterals());
10053
10439
  const assert = () => {
10054
10440
  store.assert();
10055
10441
  if (!accepting)
10056
10442
  throw new ContractError("quarantine");
10057
10443
  };
10444
+ const root = dirname12(dirname12(fileURLToPath3(hostUrl))), version = installedVersion(root), record2 = new MaintenanceRecord(store);
10445
+ const managed = (() => {
10446
+ const s = supervisingUnit(process.env, (selection) => hostSystem(root, ownerControl, selection));
10447
+ return s && serviceConfigPath(s) === input.serverConfig ? s : undefined;
10448
+ })();
10449
+ let route, requesting = false;
10450
+ async function associatedWork() {
10451
+ const counts = await Promise.all(store.associatedProjects().map(async (p) => {
10452
+ try {
10453
+ const observed = await serviceStatus(new ServiceCoordination(p.path, input.stateHome));
10454
+ return observed && typeof observed === "object" && "status" in observed && observed.status === "alive" && "work" in observed && typeof observed.work === "number" ? observed.work : 0;
10455
+ } catch {
10456
+ return 0;
10457
+ }
10458
+ }));
10459
+ return counts.reduce((sum, count) => sum + count, 0);
10460
+ }
10461
+ function latestJob() {
10462
+ const job2 = record2.read();
10463
+ return job2?.state === "running" && managed && !jobRunning(managed) ? { ...job2, state: "failed", reason: "interrupted" } : job2;
10464
+ }
10465
+ async function serviceEntry() {
10466
+ route ??= upgradeRoute(root);
10467
+ return {
10468
+ kind: "service",
10469
+ version,
10470
+ unit: managed ? { name: managed.unit, scope: managed.scope ?? "user" } : null,
10471
+ upgrade: await route,
10472
+ work: await associatedWork(),
10473
+ job: latestJob()
10474
+ };
10475
+ }
10476
+ async function requestJob(value2, current) {
10477
+ const o = closed(value2, ["action", "from", "to", "work", "epoch"]);
10478
+ const action = oneOf(o.action, MAINTENANCE_ACTIONS), to = o.to === null ? null : decodeVersion(o.to);
10479
+ if (action === "upgrade" !== (to !== null))
10480
+ throw new ContractError("invalid");
10481
+ if (decodeId(o.epoch) !== auth.epoch || decodeVersion(o.from) !== version)
10482
+ throw new ContractError("stale");
10483
+ if (!managed)
10484
+ throw new ContractError("unsupported-context");
10485
+ route ??= upgradeRoute(root);
10486
+ if (action === "upgrade" && await route !== "npm")
10487
+ throw new ContractError("unsupported-context");
10488
+ if (requesting || jobRunning(managed))
10489
+ throw new ContractError("conflict");
10490
+ requesting = true;
10491
+ try {
10492
+ if (await associatedWork() !== integer(o.work, 0, 1e6))
10493
+ throw new ContractError("stale");
10494
+ current();
10495
+ assert();
10496
+ const job2 = {
10497
+ id: randomUUID9(),
10498
+ action,
10499
+ from: version,
10500
+ to,
10501
+ state: "running",
10502
+ reason: null,
10503
+ version: null,
10504
+ at: Date.now(),
10505
+ endedAt: null
10506
+ };
10507
+ record2.write(job2);
10508
+ if (!launchJob(managed, job2)) {
10509
+ record2.finish(job2.id, "failed", "refused", version);
10510
+ throw new ContractError("unavailable");
10511
+ }
10512
+ return job2;
10513
+ } finally {
10514
+ requesting = false;
10515
+ }
10516
+ }
10517
+ function browserBuild(boundary) {
10518
+ const clientBuild = decodeClientBuild(parseWireJson(boundary.headers.get("x-cadence-build") ?? "null", 1024));
10519
+ if (clientBuild.kind !== "browser" || !compatibleBuild(build2, clientBuild))
10520
+ throw new ContractError("unsupported-context");
10521
+ }
10058
10522
  async function open(path, id, epoch) {
10059
10523
  assert();
10060
10524
  if (epoch !== auth.epoch)
@@ -10137,14 +10601,14 @@ Content-Length: 0\r
10137
10601
  const secret = link.searchParams.get("token");
10138
10602
  if (!secret)
10139
10603
  throw new ContractError("unavailable");
10140
- const cookie = await new Promise((resolve7, reject) => {
10604
+ const cookie = await new Promise((resolve8, reject) => {
10141
10605
  const req = request2(`${local.endpoint}/?token=${encodeURIComponent(secret)}`, { agent: false }, (res) => {
10142
10606
  const cookie2 = res.headers["set-cookie"];
10143
10607
  res.resume();
10144
10608
  if (res.statusCode !== 303 || cookie2?.length !== 1)
10145
10609
  reject(new ContractError("unavailable"));
10146
10610
  else
10147
- resolve7(cookie2[0].split(";")[0]);
10611
+ resolve8(cookie2[0].split(";")[0]);
10148
10612
  });
10149
10613
  req.setTimeout(2000, () => req.destroy(new Error));
10150
10614
  req.on("error", () => reject(new ContractError("unavailable")));
@@ -10310,20 +10774,20 @@ Content-Length: 0\r
10310
10774
  const project = target(raw);
10311
10775
  const caller = auth.authenticate(boundary, randomUUID9(), !project && req.method === "POST");
10312
10776
  if (project) {
10313
- const route = readRoute(project.tail, req.method ?? "");
10314
- if (!route)
10777
+ const route2 = readRoute(project.tail, req.method ?? "");
10778
+ if (!route2)
10315
10779
  throw new ContractError("invalid");
10316
10780
  const attachment = boundary.headers.get("x-cadence-attachment");
10317
10781
  if (attachment && attachments.get(attachment) !== project.id || req.method === "POST" && !attachment)
10318
10782
  throw new ContractError("stale");
10319
- if (route.operation === "session" && !attachment && attachments.size >= 2048)
10783
+ if (route2.operation === "session" && !attachment && attachments.size >= 2048)
10320
10784
  throw new ContractError("capacity");
10321
10785
  if (req.method === "POST" && boundary.headers.get("origin") !== boundary.origin)
10322
10786
  throw new ContractError("forbidden");
10323
10787
  if (req.headers["content-encoding"] || req.headers["transfer-encoding"] || Number(req.headers["content-length"] ?? 0) > LIMITS.controlBytes)
10324
10788
  throw new ContractError("oversize");
10325
10789
  let commandBody;
10326
- if (route.operation === "workbenchCommand") {
10790
+ if (route2.operation === "workbenchCommand") {
10327
10791
  const command = decodeWorkbenchCommand(await body(req, LIMITS.controlBytes));
10328
10792
  if (command.kind === "open-project")
10329
10793
  throw new ContractError("forbidden");
@@ -10349,7 +10813,7 @@ Content-Length: 0\r
10349
10813
  }
10350
10814
  if (commandBody !== undefined)
10351
10815
  headers["content-length"] = String(Buffer.byteLength(commandBody));
10352
- await new Promise((resolve7) => {
10816
+ await new Promise((resolve8) => {
10353
10817
  const upstream = request2(`${b.endpoint}${project.tail}`, { method: req.method, headers, agent: false }, (incoming) => {
10354
10818
  try {
10355
10819
  auth.current(caller);
@@ -10357,7 +10821,7 @@ Content-Length: 0\r
10357
10821
  close();
10358
10822
  return;
10359
10823
  }
10360
- if (route.operation === "session" && incoming.statusCode === 200) {
10824
+ if (route2.operation === "session" && incoming.statusCode === 200) {
10361
10825
  try {
10362
10826
  attachments.set(decodeId(incoming.headers["x-cadence-attachment"]), project.id);
10363
10827
  } catch {
@@ -10365,7 +10829,7 @@ Content-Length: 0\r
10365
10829
  return;
10366
10830
  }
10367
10831
  }
10368
- if (route.operation === "detach" && incoming.statusCode === 200 && attachment)
10832
+ if (route2.operation === "detach" && incoming.statusCode === 200 && attachment)
10369
10833
  attachments.delete(attachment);
10370
10834
  res.statusCode = incoming.statusCode ?? 502;
10371
10835
  for (const key of [
@@ -10385,7 +10849,7 @@ Content-Length: 0\r
10385
10849
  relays.delete(close);
10386
10850
  res.off("close", close);
10387
10851
  res.off("finish", done);
10388
- resolve7();
10852
+ resolve8();
10389
10853
  }
10390
10854
  function close() {
10391
10855
  upstream.destroy();
@@ -10417,7 +10881,7 @@ Content-Length: 0\r
10417
10881
  kind: "workbench",
10418
10882
  epoch: auth.epoch,
10419
10883
  csrf: auth.csrf,
10420
- home: homedir5(),
10884
+ home: homedir6(),
10421
10885
  projects: store.projects(),
10422
10886
  recoveries: new RecoveryLog(store.files).notices(),
10423
10887
  build: build2
@@ -10428,10 +10892,27 @@ Content-Length: 0\r
10428
10892
  reply(res, 200, files.list(text(url.searchParams.get("path"), 4096, true), true));
10429
10893
  return;
10430
10894
  }
10895
+ if (raw === "/workbench/v1/service" && req.method === "GET") {
10896
+ reply(res, 200, await serviceEntry());
10897
+ return;
10898
+ }
10899
+ if (raw === "/workbench/v1/service/release" && req.method === "GET") {
10900
+ const latest = await release();
10901
+ if (!latest)
10902
+ throw new ContractError("unavailable");
10903
+ reply(res, 200, { kind: "release", ...latest });
10904
+ return;
10905
+ }
10906
+ if (raw === "/workbench/v1/service" && req.method === "POST") {
10907
+ browserBuild(boundary);
10908
+ const value2 = await body(req);
10909
+ auth.current(caller);
10910
+ const job2 = await requestJob(value2, () => auth.current(caller));
10911
+ reply(res, 200, { kind: "service-job", job: job2 });
10912
+ return;
10913
+ }
10431
10914
  if (raw === "/workbench/v1/open" && req.method === "POST") {
10432
- const clientBuild = decodeClientBuild(parseWireJson(boundary.headers.get("x-cadence-build") ?? "null", 1024));
10433
- if (clientBuild.kind !== "browser" || !compatibleBuild(build2, clientBuild))
10434
- throw new ContractError("unsupported-context");
10915
+ browserBuild(boundary);
10435
10916
  const o = closed(await body(req), ["commandId", "path", "epoch"]);
10436
10917
  const id = decodeId(o.commandId), path = text(o.path, 4096, true), epoch = decodeId(o.epoch);
10437
10918
  auth.current(caller);
@@ -10531,14 +11012,14 @@ Content-Length: 0\r
10531
11012
  }
10532
11013
 
10533
11014
  // src/service/host.ts
10534
- import { spawn as spawn4 } from "node:child_process";
10535
- import { lstatSync as lstatSync21, opendirSync as opendirSync15 } from "node:fs";
10536
- import { join as join32 } from "node:path";
10537
- import { fileURLToPath as fileURLToPath6 } from "node:url";
11015
+ import { spawn as spawn5 } from "node:child_process";
11016
+ import { lstatSync as lstatSync22, opendirSync as opendirSync15 } from "node:fs";
11017
+ import { join as join34 } from "node:path";
11018
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
10538
11019
 
10539
11020
  // src/agent-registry.ts
10540
11021
  import { createHash as createHash7 } from "node:crypto";
10541
- import { fileURLToPath as fileURLToPath3 } from "node:url";
11022
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
10542
11023
  var AGENT_FILES = [
10543
11024
  "design-explorer.md",
10544
11025
  "implementation-worker.md",
@@ -10546,7 +11027,7 @@ var AGENT_FILES = [
10546
11027
  ];
10547
11028
  function loadAgentDefinitions() {
10548
11029
  return AGENT_FILES.map((fileName) => {
10549
- const path = fileURLToPath3(new URL(`../agents/${fileName}`, import.meta.url));
11030
+ const path = fileURLToPath4(new URL(`../agents/${fileName}`, import.meta.url));
10550
11031
  const data = readBounded(path, 32768, true);
10551
11032
  if (!data)
10552
11033
  throw new Error("Missing package Agent");
@@ -10562,18 +11043,18 @@ function loadAgentDefinitions() {
10562
11043
  }
10563
11044
 
10564
11045
  // src/cadence-preferences.ts
10565
- import { realpathSync as realpathSync5 } from "node:fs";
10566
- import { basename as basename2, dirname as dirname10, join as join15, resolve as resolve7 } from "node:path";
11046
+ import { realpathSync as realpathSync7 } from "node:fs";
11047
+ import { basename as basename2, dirname as dirname13, join as join17, resolve as resolve8 } from "node:path";
10567
11048
  function agentNamespace(agentDir) {
10568
- let at = resolve7(agentDir);
11049
+ let at = resolve8(agentDir);
10569
11050
  const missing2 = [];
10570
11051
  for (;; ) {
10571
11052
  try {
10572
- return join15(realpathSync5(at), ...missing2.reverse());
11053
+ return join17(realpathSync7(at), ...missing2.reverse());
10573
11054
  } catch {
10574
- const parent = dirname10(at);
11055
+ const parent = dirname13(at);
10575
11056
  if (parent === at)
10576
- return resolve7(agentDir);
11057
+ return resolve8(agentDir);
10577
11058
  missing2.push(basename2(at));
10578
11059
  at = parent;
10579
11060
  }
@@ -10585,7 +11066,7 @@ class CadencePreferences {
10585
11066
  files;
10586
11067
  constructor(agentDir) {
10587
11068
  const namespace = agentNamespace(agentDir);
10588
- this.path = join15(namespace, "cadence", "settings.json");
11069
+ this.path = join17(namespace, "cadence", "settings.json");
10589
11070
  this.files = new PrivateFiles(namespace, false);
10590
11071
  }
10591
11072
  read() {
@@ -10633,12 +11114,12 @@ class CadencePreferences {
10633
11114
  function scopedSnapshot(source, scope) {
10634
11115
  if (scope.kind === "task" || source.scope.kind === "child")
10635
11116
  return;
10636
- if (!source.runs.some((run) => scope.kind === "run" ? run.runId === scope.id && run.childRunId === null : run.childRunId === scope.id))
11117
+ if (!source.runs.some((run2) => scope.kind === "run" ? run2.runId === scope.id && run2.childRunId === null : run2.childRunId === scope.id))
10637
11118
  return;
10638
11119
  return decodeSnapshot({
10639
11120
  ...source,
10640
11121
  scope,
10641
- runs: source.runs.filter((run) => scope.kind === "run" ? run.runId === scope.id : run.childRunId === scope.id),
11122
+ runs: source.runs.filter((run2) => scope.kind === "run" ? run2.runId === scope.id : run2.childRunId === scope.id),
10642
11123
  horizon: {
10643
11124
  ...source.horizon,
10644
11125
  historicalRuns: { ...source.horizon.historicalRuns, scope }
@@ -10878,40 +11359,40 @@ class HistoryLive {
10878
11359
 
10879
11360
  // src/history/navigation.ts
10880
11361
  import { createHash as createHash11 } from "node:crypto";
10881
- import { lstatSync as lstatSync12 } from "node:fs";
10882
- import { dirname as dirname13, join as join18 } from "node:path";
11362
+ import { lstatSync as lstatSync13 } from "node:fs";
11363
+ import { dirname as dirname16, join as join20 } from "node:path";
10883
11364
 
10884
11365
  // src/history/index-tree.ts
10885
- import { lstatSync as lstatSync10 } from "node:fs";
10886
- import { join as join16 } from "node:path";
11366
+ import { lstatSync as lstatSync11 } from "node:fs";
11367
+ import { join as join18 } from "node:path";
10887
11368
 
10888
11369
  // src/history/read-io.ts
10889
11370
  import { createHash as createHash8 } from "node:crypto";
10890
11371
  import {
10891
11372
  closeSync as closeSync5,
10892
- constants as constants4,
11373
+ constants as constants5,
10893
11374
  fstatSync as fstatSync4,
10894
- lstatSync as lstatSync9,
11375
+ lstatSync as lstatSync10,
10895
11376
  openSync as openSync5,
10896
11377
  readSync as readSync4
10897
11378
  } from "node:fs";
10898
- import { dirname as dirname11 } from "node:path";
11379
+ import { dirname as dirname14 } from "node:path";
10899
11380
  function bad() {
10900
11381
  throw new ContractError("corrupt-selected");
10901
11382
  }
10902
11383
  var stamp2 = (s) => [s.dev, s.ino, s.size, s.mode, s.uid, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
10903
11384
  function selected(files, path, read, walks) {
10904
- if (!files.files.directory(dirname11(path), false, walks))
11385
+ if (!files.files.directory(dirname14(path), false, walks))
10905
11386
  bad();
10906
- const before = lstatSync9(path);
11387
+ const before = lstatSync10(path);
10907
11388
  if (!before.isFile() || before.nlink !== 1 || process.platform !== "win32" && (before.mode & 63 || process.getuid && before.uid !== process.getuid()))
10908
11389
  bad();
10909
- const fd = openSync5(path, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
11390
+ const fd = openSync5(path, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
10910
11391
  try {
10911
11392
  if (stamp2(fstatSync4(fd)) !== stamp2(before))
10912
11393
  bad();
10913
11394
  const result = read(fd, before.size, stamp2(before));
10914
- if (stamp2(fstatSync4(fd)) !== stamp2(before) || stamp2(lstatSync9(path)) !== stamp2(before))
11395
+ if (stamp2(fstatSync4(fd)) !== stamp2(before) || stamp2(lstatSync10(path)) !== stamp2(before))
10915
11396
  bad();
10916
11397
  return result;
10917
11398
  } finally {
@@ -11012,7 +11493,7 @@ class IndexTree {
11012
11493
  this.files = files;
11013
11494
  }
11014
11495
  path(id) {
11015
- return join16(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
11496
+ return join18(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
11016
11497
  }
11017
11498
  load(id, budget, unit) {
11018
11499
  decodeHash(id);
@@ -11027,7 +11508,7 @@ class IndexTree {
11027
11508
  if (budget) {
11028
11509
  const path = this.path(id);
11029
11510
  budget.reserve(0);
11030
- const selected2 = lstatSync10(path).size;
11511
+ const selected2 = lstatSync11(path).size;
11031
11512
  if (selected2 > MAX_NODE)
11032
11513
  throw new ContractError("receipt-inconclusive");
11033
11514
  bytes = readRange(this.files, path, 0, selected2, budget);
@@ -11147,16 +11628,16 @@ class IndexTree {
11147
11628
  import { createHash as createHash10, randomBytes as randomBytes4, randomUUID as randomUUID10 } from "node:crypto";
11148
11629
  import {
11149
11630
  closeSync as closeSync6,
11150
- constants as constants5,
11631
+ constants as constants6,
11151
11632
  fstatSync as fstatSync5,
11152
11633
  fsyncSync as fsyncSync3,
11153
- lstatSync as lstatSync11,
11634
+ lstatSync as lstatSync12,
11154
11635
  opendirSync as opendirSync7,
11155
11636
  openSync as openSync6,
11156
11637
  statfsSync
11157
11638
  } from "node:fs";
11158
11639
  import { open } from "node:fs/promises";
11159
- import { dirname as dirname12, join as join17 } from "node:path";
11640
+ import { dirname as dirname15, join as join19 } from "node:path";
11160
11641
 
11161
11642
  // src/history/admission.ts
11162
11643
  function decodeRunAdmission(value) {
@@ -11641,7 +12122,7 @@ async function retryStalled(read) {
11641
12122
  } catch (error) {
11642
12123
  if (!(error instanceof StalledQuantum) || retry >= STALL_RETRIES)
11643
12124
  throw error;
11644
- await new Promise((resolve8) => setImmediate(resolve8));
12125
+ await new Promise((resolve9) => setImmediate(resolve9));
11645
12126
  }
11646
12127
  }
11647
12128
  }
@@ -11662,14 +12143,14 @@ class HistoryFiles {
11662
12143
  this.coordination = coordination;
11663
12144
  this.format = format;
11664
12145
  this.formatSnapshot = formatSnapshot;
11665
- this.directory = join17(coordination.directory, "history-v2");
12146
+ this.directory = join19(coordination.directory, "history-v2");
11666
12147
  this.files = coordination.files;
11667
12148
  }
11668
12149
  static open(coordination) {
11669
- const dir = join17(coordination.directory, "history-v2");
12150
+ const dir = join19(coordination.directory, "history-v2");
11670
12151
  if (!coordination.files.directory(dir))
11671
12152
  return;
11672
- const file = coordination.files.read(join17(dir, "format.json"));
12153
+ const file = coordination.files.read(join19(dir, "format.json"));
11673
12154
  if (!file)
11674
12155
  corrupt();
11675
12156
  const format = decodeFormat(json(file));
@@ -11685,7 +12166,7 @@ class HistoryFiles {
11685
12166
  existing.assertWritable();
11686
12167
  return existing;
11687
12168
  }
11688
- const dir = join17(c.directory, "history-v2");
12169
+ const dir = join19(c.directory, "history-v2");
11689
12170
  const format = {
11690
12171
  schema: FORMAT,
11691
12172
  storeId: randomUUID10(),
@@ -11695,19 +12176,19 @@ class HistoryFiles {
11695
12176
  c.files.directory(dir, true);
11696
12177
  for (const name of ["commands", "ledger", "runs", "indexes"]) {
11697
12178
  lease.assert();
11698
- c.files.directory(join17(dir, name), true);
12179
+ c.files.directory(join19(dir, name), true);
11699
12180
  }
11700
12181
  lease.assert();
11701
- const keyPath = join17(dir, "read-proof-key.json");
12182
+ const keyPath = join19(dir, "read-proof-key.json");
11702
12183
  c.files.create(keyPath, encoded({
11703
12184
  schema: "cadence-history-read-key/1",
11704
12185
  storeId: format.storeId,
11705
12186
  key: randomBytes4(32).toString("base64url")
11706
12187
  }));
11707
12188
  lease.assert();
11708
- const snapshot = c.files.create(join17(dir, "format.json"), encoded(format));
12189
+ const snapshot = c.files.create(join19(dir, "format.json"), encoded(format));
11709
12190
  const result = new HistoryFiles(c, format, snapshot);
11710
- result.syncParents(join17(dir, "format.json"));
12191
+ result.syncParents(join19(dir, "format.json"));
11711
12192
  result.assertWritable();
11712
12193
  return result;
11713
12194
  }
@@ -11742,7 +12223,7 @@ class HistoryFiles {
11742
12223
  throw new ContractError("quarantine");
11743
12224
  }
11744
12225
  assertFormat() {
11745
- this.files.assert(join17(this.directory, "format.json"), this.formatSnapshot);
12226
+ this.files.assert(join19(this.directory, "format.json"), this.formatSnapshot);
11746
12227
  }
11747
12228
  readProofMaterial(budget) {
11748
12229
  if (this.format.schema !== FORMAT)
@@ -11751,7 +12232,7 @@ class HistoryFiles {
11751
12232
  this.assertReadFormat(budget);
11752
12233
  else
11753
12234
  this.assertFormat();
11754
- const selected2 = this.readBudgeted(join17(this.directory, "read-proof-key.json"), 512, budget);
12235
+ const selected2 = this.readBudgeted(join19(this.directory, "read-proof-key.json"), 512, budget);
11755
12236
  if (!selected2 || this.proofSnapshot && (selected2.identity !== this.proofSnapshot.identity || selected2.stamp !== this.proofSnapshot.stamp))
11756
12237
  corrupt();
11757
12238
  try {
@@ -11779,17 +12260,17 @@ class HistoryFiles {
11779
12260
  return;
11780
12261
  }
11781
12262
  this.assertFormat();
11782
- assertIncarnation(this, join17(this.directory, "read-proof-key.json"), this.proofSnapshot.stamp);
12263
+ assertIncarnation(this, join19(this.directory, "read-proof-key.json"), this.proofSnapshot.stamp);
11783
12264
  }
11784
12265
  segmentPath(segment) {
11785
- return join17(this.directory, "ledger", `${String(segment).padStart(12, "0")}.jsonl`);
12266
+ return join19(this.directory, "ledger", `${String(segment).padStart(12, "0")}.jsonl`);
11786
12267
  }
11787
12268
  artifactPath(ref) {
11788
- return join17(this.directory, "runs", ref.runId, "artifacts", ref.artifactId, `${ref.part}.part`);
12269
+ return join19(this.directory, "runs", ref.runId, "artifacts", ref.artifactId, `${ref.part}.part`);
11789
12270
  }
11790
12271
  admissionPath(runId) {
11791
12272
  decodeId(runId);
11792
- return join17(this.directory, "runs", runId, "admission.json");
12273
+ return join19(this.directory, "runs", runId, "admission.json");
11793
12274
  }
11794
12275
  writeAdmission(lease, input) {
11795
12276
  lease.assert();
@@ -11803,7 +12284,7 @@ class HistoryFiles {
11803
12284
  return this.files.read(path, maximum);
11804
12285
  let size2;
11805
12286
  try {
11806
- size2 = lstatSync11(path).size;
12287
+ size2 = lstatSync12(path).size;
11807
12288
  } catch {
11808
12289
  return this.files.read(path, 0, budget.walks);
11809
12290
  }
@@ -11815,7 +12296,7 @@ class HistoryFiles {
11815
12296
  readCommand(commandId, budget) {
11816
12297
  decodeId(commandId);
11817
12298
  this.assertReadFormat(budget);
11818
- return this.readBudgeted(join17(this.directory, "commands", commandId, "intent.json"), RECORD_BYTES, budget);
12299
+ return this.readBudgeted(join19(this.directory, "commands", commandId, "intent.json"), RECORD_BYTES, budget);
11819
12300
  }
11820
12301
  readAdmission(runId, identity, budget) {
11821
12302
  return this.readAdmissionIdentity(runId, hash2(canonicalJson(identity)), budget);
@@ -11836,10 +12317,10 @@ class HistoryFiles {
11836
12317
  syncParents(file) {
11837
12318
  if (process.platform === "win32")
11838
12319
  return;
11839
- for (let path = dirname12(file);; path = dirname12(path)) {
12320
+ for (let path = dirname15(file);; path = dirname15(path)) {
11840
12321
  if (!this.files.directory(path))
11841
12322
  corrupt();
11842
- const fd = openSync6(path, constants5.O_RDONLY | constants5.O_DIRECTORY);
12323
+ const fd = openSync6(path, constants6.O_RDONLY | constants6.O_DIRECTORY);
11843
12324
  try {
11844
12325
  fsyncSync3(fd);
11845
12326
  } finally {
@@ -11847,13 +12328,13 @@ class HistoryFiles {
11847
12328
  }
11848
12329
  if (path === this.coordination.directory)
11849
12330
  break;
11850
- if (path === dirname12(path))
12331
+ if (path === dirname15(path))
11851
12332
  corrupt();
11852
12333
  }
11853
12334
  }
11854
12335
  assertReadFormat(budget) {
11855
12336
  budget.reserve(this.formatSnapshot.bytes.length);
11856
- this.files.assert(join17(this.directory, "format.json"), this.formatSnapshot, this.formatSnapshot.bytes.length);
12337
+ this.files.assert(join19(this.directory, "format.json"), this.formatSnapshot, this.formatSnapshot.bytes.length);
11857
12338
  }
11858
12339
  assertPublished(segment, end, seq) {
11859
12340
  const fence = publicationFences.get(this.directory);
@@ -11891,7 +12372,7 @@ class HistoryFiles {
11891
12372
  const dir = opendirSync7(path);
11892
12373
  try {
11893
12374
  for (let e = dir.readSync();e; e = dir.readSync()) {
11894
- const p = join17(path, e.name), st = lstatSync11(p);
12375
+ const p = join19(path, e.name), st = lstatSync12(p);
11895
12376
  if (st.isDirectory())
11896
12377
  bytes += walk(p, depth + 1);
11897
12378
  else {
@@ -11926,7 +12407,7 @@ class HistoryFiles {
11926
12407
  state.bytes = 0;
11927
12408
  state.identity = null;
11928
12409
  let count = 0;
11929
- const ledger = join17(this.directory, "ledger");
12410
+ const ledger = join19(this.directory, "ledger");
11930
12411
  if (!this.files.directory(ledger))
11931
12412
  corrupt();
11932
12413
  const dir = opendirSync7(ledger);
@@ -12089,9 +12570,9 @@ class HistoryFiles {
12089
12570
  this.activity().generation++;
12090
12571
  const before = this.files.create(path, "", LIMITS.segmentBytes);
12091
12572
  let committed;
12092
- const fd = await open(path, constants5.O_WRONLY | constants5.O_APPEND | (constants5.O_NOFOLLOW ?? 0));
12573
+ const fd = await open(path, constants6.O_WRONLY | constants6.O_APPEND | (constants6.O_NOFOLLOW ?? 0));
12093
12574
  const assertOriginal = (bytes) => {
12094
- const original = fstatSync5(fd.fd), selected2 = lstatSync11(path);
12575
+ const original = fstatSync5(fd.fd), selected2 = lstatSync12(path);
12095
12576
  if (original.dev !== selected2.dev || original.ino !== selected2.ino || original.nlink !== 1)
12096
12577
  corrupt();
12097
12578
  const snapshot = this.files.read(path, LIMITS.segmentBytes);
@@ -12204,11 +12685,11 @@ class HistoryFiles {
12204
12685
  }
12205
12686
  if (!before || segment === state.segment && (before.bytes.length !== state.bytes || before.identity !== state.identity))
12206
12687
  corrupt();
12207
- const fd = await open(path, constants5.O_WRONLY | constants5.O_APPEND | (constants5.O_NOFOLLOW ?? 0));
12688
+ const fd = await open(path, constants6.O_WRONLY | constants6.O_APPEND | (constants6.O_NOFOLLOW ?? 0));
12208
12689
  try {
12209
12690
  lease.assert();
12210
12691
  this.files.assert(path, before, LIMITS.segmentBytes);
12211
- const opened = await fd.stat(), selected2 = lstatSync11(path);
12692
+ const opened = await fd.stat(), selected2 = lstatSync12(path);
12212
12693
  if (opened.ino !== selected2.ino || opened.dev !== selected2.dev || opened.nlink !== 1)
12213
12694
  corrupt();
12214
12695
  beforeEffect?.();
@@ -12243,7 +12724,7 @@ class HistoryFiles {
12243
12724
  checkpoint(lease, state) {
12244
12725
  lease.assert();
12245
12726
  this.assertWritable();
12246
- const path = join17(this.directory, "checkpoint.json"), old = this.files.read(path);
12727
+ const path = join19(this.directory, "checkpoint.json"), old = this.files.read(path);
12247
12728
  const body = encoded({
12248
12729
  schema: "cadence-history-checkpoint/2",
12249
12730
  storeId: this.format.storeId,
@@ -12952,7 +13433,7 @@ class HistoryNavigation {
12952
13433
  cacheBytes = 0;
12953
13434
  blocks = new Map;
12954
13435
  block(path, at, size2, budget) {
12955
- const start = Math.floor(at / (1024 * 1024)) * 1024 * 1024, key = `${path}/${start}`, st = stamp3(lstatSync12(path));
13436
+ const start = Math.floor(at / (1024 * 1024)) * 1024 * 1024, key = `${path}/${start}`, st = stamp3(lstatSync13(path));
12956
13437
  let old = this.blocks.get(key);
12957
13438
  if (!old || old.budget !== budget || old.stamp !== st) {
12958
13439
  const bytes = readRange(this.files, path, start, Math.min(1024 * 1024, size2 - start), budget);
@@ -12990,9 +13471,9 @@ class HistoryNavigation {
12990
13471
  if (row.value.kind === "auth-preparation")
12991
13472
  auth.set(row.value.intent.operationId, row.value.intent.runId);
12992
13473
  if (row.value.kind === "auth-settlement") {
12993
- const run = auth.get(row.value.result.operationId);
12994
- if (run)
12995
- keys2.add(run);
13474
+ const run2 = auth.get(row.value.result.operationId);
13475
+ if (run2)
13476
+ keys2.add(run2);
12996
13477
  auth.delete(row.value.result.operationId);
12997
13478
  }
12998
13479
  }
@@ -13030,7 +13511,7 @@ class HistoryNavigation {
13030
13511
  }
13031
13512
  }
13032
13513
  indexPath(group, id) {
13033
- return join18(this.files.directory, "indexes", group, `${id}.json`);
13514
+ return join20(this.files.directory, "indexes", group, `${id}.json`);
13034
13515
  }
13035
13516
  hintKey(group, id) {
13036
13517
  return `${this.files.directory}/${this.files.format.storeId}/${group}/${id}`;
@@ -13087,9 +13568,9 @@ class HistoryNavigation {
13087
13568
  return structuredClone(source.value);
13088
13569
  }
13089
13570
  try {
13090
- if (!this.files.files.directory(dirname13(path), false, budget.walks))
13571
+ if (!this.files.files.directory(dirname16(path), false, budget.walks))
13091
13572
  return source ? structuredClone(source.value) : undefined;
13092
- const size2 = lstatSync12(path).size;
13573
+ const size2 = lstatSync13(path).size;
13093
13574
  if (size2 > RECORD_BYTES)
13094
13575
  return source ? structuredClone(source.value) : undefined;
13095
13576
  return parseWireJson(readRange(this.files, path, 0, size2, budget).toString("utf8"), RECORD_BYTES);
@@ -13168,10 +13649,10 @@ class HistoryNavigation {
13168
13649
  if (row.value.kind === "auth-preparation")
13169
13650
  this.authRuns.set(row.value.intent.operationId, row.value.intent.runId);
13170
13651
  if (row.value.kind === "auth-settlement") {
13171
- const run = this.authRuns.get(row.value.result.operationId);
13172
- if (run) {
13173
- keys2.add(run);
13174
- runKeys.add(run);
13652
+ const run2 = this.authRuns.get(row.value.result.operationId);
13653
+ if (run2) {
13654
+ keys2.add(run2);
13655
+ runKeys.add(run2);
13175
13656
  }
13176
13657
  this.authRuns.delete(row.value.result.operationId);
13177
13658
  }
@@ -13221,7 +13702,7 @@ class HistoryNavigation {
13221
13702
  }
13222
13703
  batch(p, budget) {
13223
13704
  const key = canonicalJson(p), cached = this.cache.get(key), path = this.files.segmentPath(p.segment);
13224
- if (cached && cached.budget === budget && cached.stamp === stamp3(lstatSync12(path))) {
13705
+ if (cached && cached.budget === budget && cached.stamp === stamp3(lstatSync13(path))) {
13225
13706
  this.validateBridge(cached.batch.rows, p, budget);
13226
13707
  this.rememberBoundary(p, cached.batch.navigationRoot, budget);
13227
13708
  return cached.batch;
@@ -13232,7 +13713,7 @@ class HistoryNavigation {
13232
13713
  if (cached.identity !== identity)
13233
13714
  bad2();
13234
13715
  cached.budget = budget;
13235
- cached.stamp = stamp3(lstatSync12(path));
13716
+ cached.stamp = stamp3(lstatSync13(path));
13236
13717
  this.files.assertPublished(p.segment, p.offset + p.bytes, p.seq);
13237
13718
  this.validateBridge(cached.batch.rows, p, budget);
13238
13719
  this.rememberBoundary(p, cached.batch.navigationRoot, budget);
@@ -13283,7 +13764,7 @@ class HistoryNavigation {
13283
13764
  identity,
13284
13765
  batch,
13285
13766
  bytes: bytes.length,
13286
- stamp: stamp3(lstatSync12(path)),
13767
+ stamp: stamp3(lstatSync13(path)),
13287
13768
  budget
13288
13769
  });
13289
13770
  this.cacheBytes += bytes.length;
@@ -13300,7 +13781,7 @@ class HistoryNavigation {
13300
13781
  const path = this.files.segmentPath(segment);
13301
13782
  let size2;
13302
13783
  try {
13303
- size2 = lstatSync12(path).size;
13784
+ size2 = lstatSync13(path).size;
13304
13785
  } catch (e) {
13305
13786
  if (e instanceof Error && "code" in e && e.code === "ENOENT")
13306
13787
  return null;
@@ -14161,7 +14642,7 @@ function materializeEntity(s, sources) {
14161
14642
 
14162
14643
  // src/history/export.ts
14163
14644
  import { createHash as createHash15, randomUUID as randomUUID11 } from "node:crypto";
14164
- import { readFileSync as readFileSync2 } from "node:fs";
14645
+ import { readFileSync as readFileSync4 } from "node:fs";
14165
14646
 
14166
14647
  // src/history/search.ts
14167
14648
  import { createHash as createHash14 } from "node:crypto";
@@ -16014,14 +16495,14 @@ async function searchQuantum(reader, value, limit = LIMITS.pageEntries) {
16014
16495
  // src/history/export.ts
16015
16496
  var exporterIdentity;
16016
16497
  function buildIdentity() {
16017
- exporterIdentity ??= createHash15("sha256").update(readFileSync2(new URL(import.meta.url))).digest("hex");
16498
+ exporterIdentity ??= createHash15("sha256").update(readFileSync4(new URL(import.meta.url))).digest("hex");
16018
16499
  return exporterIdentity;
16019
16500
  }
16020
16501
  function aborted(signal) {
16021
16502
  if (signal.aborted)
16022
16503
  throw new ContractError("unavailable");
16023
16504
  }
16024
- var yieldTurn = () => new Promise((resolve8) => setImmediate(resolve8));
16505
+ var yieldTurn = () => new Promise((resolve9) => setImmediate(resolve9));
16025
16506
  function* textChunks(text2) {
16026
16507
  const bytes = Buffer.from(text2);
16027
16508
  for (let at = 0;at < bytes.length; ) {
@@ -16749,14 +17230,14 @@ function decodeState(value) {
16749
17230
  legacyIdentity: o.legacyIdentity
16750
17231
  };
16751
17232
  }
16752
- function target(entity, run, stop = null) {
17233
+ function target(entity, run2, stop = null) {
16753
17234
  return {
16754
17235
  phase: "scan",
16755
17236
  proof: freshValidator(),
16756
17237
  row: 0,
16757
17238
  event: 0,
16758
17239
  entity,
16759
- run,
17240
+ run: run2,
16760
17241
  stop
16761
17242
  };
16762
17243
  }
@@ -17860,7 +18341,7 @@ class HistoryProjection {
17860
18341
  // src/history/reader.ts
17861
18342
  import { createHash as createHash18 } from "node:crypto";
17862
18343
  import { existsSync as existsSync2 } from "node:fs";
17863
- import { join as join19 } from "node:path";
18344
+ import { join as join21 } from "node:path";
17864
18345
 
17865
18346
  // src/history/saved-graph-state.ts
17866
18347
  var freshSavedGraph = () => ({
@@ -18259,12 +18740,12 @@ class HistoryReader {
18259
18740
  }
18260
18741
  reviewSelection(taskId2, runId, snapshotSeq) {
18261
18742
  const budget = HistoryReadBudget.authority();
18262
- const run = this.reviewRun(taskId2, runId, snapshotSeq, budget);
18263
- if (!run.admission)
18743
+ const run2 = this.reviewRun(taskId2, runId, snapshotSeq, budget);
18744
+ if (!run2.admission)
18264
18745
  throw new ContractError("corrupt-selected");
18265
- const { graph } = this.files.readAdmission(runId, run.admission, budget);
18746
+ const { graph } = this.files.readAdmission(runId, run2.admission, budget);
18266
18747
  if (!graph)
18267
- return { run, graph, readablePlan: "" };
18748
+ return { run: run2, graph, readablePlan: "" };
18268
18749
  const ref = graph.plan;
18269
18750
  const { detail, bytes } = this.planText({
18270
18751
  storeId: this.storeId,
@@ -18278,7 +18759,7 @@ class HistoryReader {
18278
18759
  }, budget);
18279
18760
  if (ref.bytes > 32768 || canonicalJson(detail.content) !== canonicalJson(ref) || detail.owner.taskId !== taskId2 || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId2 || detail.owner.entity.version !== graph.planRevision)
18280
18761
  throw new ContractError("corrupt-selected");
18281
- return { run, graph, readablePlan: bytes.toString("utf8") };
18762
+ return { run: run2, graph, readablePlan: bytes.toString("utf8") };
18282
18763
  }
18283
18764
  async graph(value) {
18284
18765
  const request3 = decodeGraphReadRequest(value);
@@ -18628,7 +19109,7 @@ class HistoryReader {
18628
19109
  }
18629
19110
  async readDetail(value) {
18630
19111
  const cursor = decodeCursor(value);
18631
- if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(join19(this.files.directory, "indexes", "heads", "latest.json")))
19112
+ if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(join21(this.files.directory, "indexes", "heads", "latest.json")))
18632
19113
  return readRetainedDetail(this, cursor);
18633
19114
  if (this.files.format.schema !== FORMAT)
18634
19115
  return this.detail(cursor);
@@ -18830,12 +19311,12 @@ class HistoryReader {
18830
19311
 
18831
19312
  // src/history/recovery.ts
18832
19313
  import { createHash as createHash22, randomUUID as randomUUID15 } from "node:crypto";
18833
- import { lstatSync as lstatSync13, opendirSync as opendirSync8 } from "node:fs";
18834
- import { join as join23, relative as relative7 } from "node:path";
19314
+ import { lstatSync as lstatSync14, opendirSync as opendirSync8 } from "node:fs";
19315
+ import { join as join25, relative as relative7 } from "node:path";
18835
19316
 
18836
19317
  // src/history/writer.ts
18837
19318
  import { createHash as createHash21, randomUUID as randomUUID14 } from "node:crypto";
18838
- import { join as join22 } from "node:path";
19319
+ import { join as join24 } from "node:path";
18839
19320
 
18840
19321
  // src/task-store.ts
18841
19322
  import { createHash as createHash19, randomUUID as randomUUID12 } from "node:crypto";
@@ -18844,12 +19325,12 @@ import {
18844
19325
  fsyncSync as fsyncSync4,
18845
19326
  openSync as openSync7,
18846
19327
  readdirSync as readdirSync2,
18847
- renameSync as renameSync3,
19328
+ renameSync as renameSync4,
18848
19329
  unlinkSync as unlinkSync3,
18849
- writeFileSync as writeFileSync3
19330
+ writeFileSync as writeFileSync4
18850
19331
  } from "node:fs";
18851
19332
  import { hostname as hostname6 } from "node:os";
18852
- import { join as join20 } from "node:path";
19333
+ import { join as join22 } from "node:path";
18853
19334
  // src/task-types.ts
18854
19335
  var TASK_SCHEMA = "cadence-workflow-assistant/1";
18855
19336
  var MAX_RECORD_BYTES = 128 * 1024;
@@ -18936,7 +19417,7 @@ class TaskStore extends CheckoutStore {
18936
19417
  tasks;
18937
19418
  constructor(root, stateHome = defaultStateHome()) {
18938
19419
  super(root, stateHome);
18939
- this.tasks = join20(this.root, ".cadence", "assistant", "tasks");
19420
+ this.tasks = join22(this.root, ".cadence", "assistant", "tasks");
18940
19421
  }
18941
19422
  recover(expected, acknowledgeEscapedProcesses) {
18942
19423
  if (!acknowledgeEscapedProcesses || expected.host !== hostname6())
@@ -18959,10 +19440,10 @@ class TaskStore extends CheckoutStore {
18959
19440
  loadSnapshot(id) {
18960
19441
  if (!validId(id))
18961
19442
  throw new Error("Invalid task id");
18962
- const directory = join20(this.tasks, id);
19443
+ const directory = join22(this.tasks, id);
18963
19444
  if (safeDirectory(directory) && readdirSync2(directory).some((name) => name !== "task.json"))
18964
19445
  throw new Error("Unknown task directory content; preserved without reset");
18965
- const data = readBounded(join20(this.tasks, id, "task.json"), MAX_RECORD_BYTES);
19446
+ const data = readBounded(join22(this.tasks, id, "task.json"), MAX_RECORD_BYTES);
18966
19447
  if (!data)
18967
19448
  return;
18968
19449
  const record2 = decodeTask(parseRecord(data));
@@ -19000,25 +19481,25 @@ class TaskStore extends CheckoutStore {
19000
19481
  throw new Error("Revision conflict");
19001
19482
  if (current2?.identity !== expectedIdentity)
19002
19483
  throw new Error("Task content changed; reopen it");
19003
- const dir = join20(this.tasks, next.id);
19484
+ const dir = join22(this.tasks, next.id);
19004
19485
  safeDirectory(dir, true);
19005
19486
  if (!current2 && readdirSync2(dir).length)
19006
19487
  throw new Error("Unknown task directory");
19007
- const temporary = join20(dir, `task.${randomUUID12()}.tmp`);
19488
+ const temporary = join22(dir, `task.${randomUUID12()}.tmp`);
19008
19489
  const fd = openSync7(temporary, "wx", 384);
19009
19490
  try {
19010
- writeFileSync3(fd, text2);
19491
+ writeFileSync4(fd, text2);
19011
19492
  fsyncSync4(fd);
19012
19493
  } finally {
19013
19494
  closeSync7(fd);
19014
19495
  }
19015
19496
  this.assertOwner(lock);
19016
- const latest = readBounded(join20(dir, "task.json"), MAX_RECORD_BYTES);
19497
+ const latest = readBounded(join22(dir, "task.json"), MAX_RECORD_BYTES);
19017
19498
  if ((latest ? contentIdentity(latest) : undefined) !== expectedIdentity)
19018
19499
  throw new Error("Task content changed; replacement preserved without overwrite");
19019
- retryWindowsFileOperation(() => renameSync3(temporary, join20(dir, "task.json")), () => {
19500
+ retryWindowsFileOperation(() => renameSync4(temporary, join22(dir, "task.json")), () => {
19020
19501
  this.assertOwner(lock);
19021
- const now = readBounded(join20(dir, "task.json"), MAX_RECORD_BYTES);
19502
+ const now = readBounded(join22(dir, "task.json"), MAX_RECORD_BYTES);
19022
19503
  if ((now ? contentIdentity(now) : undefined) !== expectedIdentity)
19023
19504
  throw new Error("Task content changed; replacement preserved without overwrite");
19024
19505
  });
@@ -19029,7 +19510,7 @@ class TaskStore extends CheckoutStore {
19029
19510
  }
19030
19511
  }
19031
19512
  checks() {
19032
- const data = readBounded(join20(this.root, ".cadence", "assistant", "config.json"), 32768);
19513
+ const data = readBounded(join22(this.root, ".cadence", "assistant", "config.json"), 32768);
19033
19514
  if (!data)
19034
19515
  return [];
19035
19516
  const value = parseRecord(data);
@@ -19043,8 +19524,8 @@ class TaskStore extends CheckoutStore {
19043
19524
  readLog(name) {
19044
19525
  if (!/^[a-f0-9-]{36}\.log$/.test(name))
19045
19526
  throw new Error("Invalid diagnostic name");
19046
- this.inspectPrivateFile(join20(this.privateRoot, name), 65536);
19047
- const data = readBounded(join20(this.privateRoot, name), 65536);
19527
+ this.inspectPrivateFile(join22(this.privateRoot, name), 65536);
19528
+ const data = readBounded(join22(this.privateRoot, name), 65536);
19048
19529
  return data ? diagnosticText(data.toString("utf8"), 65536) : "Private diagnostic unavailable";
19049
19530
  }
19050
19531
  writeLog(lock, output) {
@@ -19052,7 +19533,7 @@ class TaskStore extends CheckoutStore {
19052
19533
  throw new Error("Not the lock owner");
19053
19534
  this.assertOwner(lock);
19054
19535
  const name = `${randomUUID12()}.log`;
19055
- writeFileSync3(join20(this.privateRoot, name), diagnosticText(output, 65536), {
19536
+ writeFileSync4(join22(this.privateRoot, name), diagnosticText(output, 65536), {
19056
19537
  flag: "wx",
19057
19538
  mode: 384
19058
19539
  });
@@ -19130,12 +19611,12 @@ function planRecording(plan, graph, operationId, epoch) {
19130
19611
  // src/history/publication.ts
19131
19612
  import {
19132
19613
  closeSync as closeSync8,
19133
- constants as constants6,
19614
+ constants as constants7,
19134
19615
  fsyncSync as fsyncSync5,
19135
19616
  openSync as openSync8,
19136
- realpathSync as realpathSync6
19617
+ realpathSync as realpathSync8
19137
19618
  } from "node:fs";
19138
- import { dirname as dirname14, isAbsolute as isAbsolute7, join as join21, relative as relative6, sep as sep5 } from "node:path";
19619
+ import { dirname as dirname17, isAbsolute as isAbsolute8, join as join23, relative as relative6, sep as sep6 } from "node:path";
19139
19620
  function summary(text2, maximum, runId) {
19140
19621
  const label = `[Cadence summary${runId ? `; run ${runId}` : ""}; retained history is separate]
19141
19622
  `;
@@ -19150,12 +19631,12 @@ function summary(text2, maximum, runId) {
19150
19631
  end--;
19151
19632
  return label + bytes.subarray(0, end).toString("utf8") + tail;
19152
19633
  }
19153
- function publicationPhase(run) {
19154
- if (!run.settlement)
19634
+ function publicationPhase(run2) {
19635
+ if (!run2.settlement)
19155
19636
  return "running";
19156
- switch (settlementOutcome(run.settlement)) {
19637
+ switch (settlementOutcome(run2.settlement)) {
19157
19638
  case "completed":
19158
- return run.admission?.kind === "generate-plan" ? "planning" : "review";
19639
+ return run2.admission?.kind === "generate-plan" ? "planning" : "review";
19159
19640
  case "failed":
19160
19641
  case "blocked":
19161
19642
  return "failed";
@@ -19168,7 +19649,7 @@ function publicationPhase(run) {
19168
19649
  function bad11() {
19169
19650
  throw new ContractError("conflict");
19170
19651
  }
19171
- function publicationRecord(store, reader, intent, link, run, request3, expected, facts, snapshotSeq) {
19652
+ function publicationRecord(store, reader, intent, link, run2, request3, expected, facts, snapshotSeq) {
19172
19653
  const identity = intent.identity;
19173
19654
  if (identity.kind !== "action")
19174
19655
  bad11();
@@ -19184,8 +19665,8 @@ function publicationRecord(store, reader, intent, link, run, request3, expected,
19184
19665
  else {
19185
19666
  if (action.kind !== "create" || !request3.cwd || store.list().length >= 1000)
19186
19667
  bad11();
19187
- const cwd = realpathSync6(request3.cwd), within = relative6(store.root, cwd);
19188
- if (isAbsolute7(within) || within === ".." || within.startsWith(`..${sep5}`))
19668
+ const cwd = realpathSync8(request3.cwd), within = relative6(store.root, cwd);
19669
+ if (isAbsolute8(within) || within === ".." || within.startsWith(`..${sep6}`))
19189
19670
  bad11();
19190
19671
  record2 = {
19191
19672
  schema: TASK_SCHEMA,
@@ -19218,7 +19699,7 @@ function publicationRecord(store, reader, intent, link, run, request3, expected,
19218
19699
  if (mode === "baseline") {
19219
19700
  if (!facts.some(({ link: l, fact: f }) => l.taskId === link.taskId && l.runId === link.runId && f.kind === "changes" && f.stage === "before" && canonicalJson(f.content) === canonicalJson(ref)))
19220
19701
  bad11();
19221
- } else if (!run || ![...run.children.values()].some((c) => c.completion?.recording.status === "committed" && canonicalJson(c.completion.recording.detail.content) === canonicalJson(ref)))
19702
+ } else if (!run2 || ![...run2.children.values()].some((c) => c.completion?.recording.status === "committed" && canonicalJson(c.completion.recording.detail.content) === canonicalJson(ref)))
19222
19703
  bad11();
19223
19704
  let preview = "";
19224
19705
  for (const part of reader.parts(detail, snapshotSeq))
@@ -19251,12 +19732,12 @@ function publicationRecord(store, reader, intent, link, run, request3, expected,
19251
19732
  record2.phase = "planning";
19252
19733
  delete record2.review;
19253
19734
  }
19254
- if (run) {
19255
- record2.phase = publicationPhase(run);
19735
+ if (run2) {
19736
+ record2.phase = publicationPhase(run2);
19256
19737
  delete record2.review;
19257
19738
  let result = request3.result ? retained(request3.result, "result") : "";
19258
19739
  if (!request3.result)
19259
- for (const child of run.children.values()) {
19740
+ for (const child of run2.children.values()) {
19260
19741
  if (child.completion?.recording.status === "committed") {
19261
19742
  const text2 = retained(child.completion.recording.detail.content, "result");
19262
19743
  if (Buffer.byteLength(result) < 32768)
@@ -19265,24 +19746,24 @@ ${text2}
19265
19746
  `;
19266
19747
  }
19267
19748
  }
19268
- if (run.settlement)
19269
- result = `Execution: ${settlementOutcome(run.settlement)} (checks and human review are separate).
19749
+ if (run2.settlement)
19750
+ result = `Execution: ${settlementOutcome(run2.settlement)} (checks and human review are separate).
19270
19751
  ${result}`;
19271
- if (run.admission?.kind === "generate-plan")
19752
+ if (run2.admission?.kind === "generate-plan")
19272
19753
  result = `Advisory plan proposal only; not saved or authorized for Start. Explicitly edit/accept and Save a plan before a separate Start.
19273
19754
  ${result}`;
19274
19755
  record2.result = summary(result, 16384, link.runId);
19275
- if (action.kind === "check" && run.check && run.settlement?.kind === "check") {
19756
+ if (action.kind === "check" && run2.check && run2.settlement?.kind === "check") {
19276
19757
  if (record2.checks.length >= 32)
19277
19758
  bad11();
19278
- const s = run.settlement;
19759
+ const s = run2.settlement;
19279
19760
  const fact = facts.findLast(({ link: l, fact: f }) => l.runId === link.runId && f.kind === "check-settled")?.fact;
19280
19761
  if (fact?.kind !== "check-settled")
19281
19762
  bad11();
19282
19763
  record2.checks.push({
19283
- name: run.check.selection.name,
19284
- command: run.check.selection.command,
19285
- timeoutMs: run.check.selection.timeoutMs,
19764
+ name: run2.check.selection.name,
19765
+ command: run2.check.selection.command,
19766
+ timeoutMs: run2.check.selection.timeoutMs,
19286
19767
  cwd: record2.cwd,
19287
19768
  exitCode: s.native.exitCode,
19288
19769
  durationMs: s.native.durationMs,
@@ -19320,10 +19801,10 @@ ${result}`;
19320
19801
  function syncTaskPublication(store, taskId2) {
19321
19802
  if (process.platform === "win32")
19322
19803
  return;
19323
- for (let path = join21(store.tasks, taskId2);; path = dirname14(path)) {
19804
+ for (let path = join23(store.tasks, taskId2);; path = dirname17(path)) {
19324
19805
  if (!safeDirectory(path))
19325
19806
  throw new ContractError("conflict");
19326
- const fd = openSync8(path, constants6.O_RDONLY | constants6.O_DIRECTORY);
19807
+ const fd = openSync8(path, constants7.O_RDONLY | constants7.O_DIRECTORY);
19327
19808
  try {
19328
19809
  fsyncSync5(fd);
19329
19810
  } finally {
@@ -19331,17 +19812,17 @@ function syncTaskPublication(store, taskId2) {
19331
19812
  }
19332
19813
  if (path === store.root)
19333
19814
  return;
19334
- if (dirname14(path) === path)
19815
+ if (dirname17(path) === path)
19335
19816
  throw new ContractError("conflict");
19336
19817
  }
19337
19818
  }
19338
19819
 
19339
19820
  // src/history/review.ts
19340
- function reviewIssues(run, current2, code2, epoch) {
19821
+ function reviewIssues(run2, current2, code2, epoch) {
19341
19822
  const issues = new Set;
19342
19823
  if (!current2.observation.complete)
19343
19824
  issues.add("incomplete-observation");
19344
- const projections = run.projections(epoch);
19825
+ const projections = run2.projections(epoch);
19345
19826
  if (projections.some((p) => p.outcome !== "completed"))
19346
19827
  issues.add("partial-results");
19347
19828
  if (projections.some((p) => p.coverage.observed !== "complete" || p.coverage.source !== "complete" || p.coverage.omissions.length))
@@ -19717,29 +20198,29 @@ class HistoryWriter {
19717
20198
  settled?.();
19718
20199
  return Promise.resolve(failure(false));
19719
20200
  }
19720
- let release;
20201
+ let release2;
19721
20202
  try {
19722
- release = this.files.retainOriginal(this.writeGeneration);
20203
+ release2 = this.files.retainOriginal(this.writeGeneration);
19723
20204
  } catch {
19724
20205
  this.fence();
19725
20206
  settled?.();
19726
20207
  return Promise.resolve(failure(false));
19727
20208
  }
19728
- let resolve8;
20209
+ let resolve9;
19729
20210
  const original = new Promise((yes) => {
19730
- resolve8 = yes;
20211
+ resolve9 = yes;
19731
20212
  });
19732
20213
  this.originals.add(original);
19733
20214
  original.then(() => {
19734
20215
  this.originals.delete(original);
19735
- release();
20216
+ release2();
19736
20217
  settled?.();
19737
20218
  });
19738
20219
  try {
19739
20220
  this.options.onOriginal?.(original, safety || continuation);
19740
20221
  } catch {
19741
20222
  this.fence();
19742
- resolve8(failure(false));
20223
+ resolve9(failure(false));
19743
20224
  return original;
19744
20225
  }
19745
20226
  if (this.queue.length && this.queue.reduce((n, j) => n + j.bytes, 0) + bytes > LIMITS.progressBatchBytes)
@@ -19747,7 +20228,7 @@ class HistoryWriter {
19747
20228
  this.queue.push({
19748
20229
  build: build2,
19749
20230
  bytes,
19750
- resolve: resolve8,
20231
+ resolve: resolve9,
19751
20232
  safety,
19752
20233
  continuation,
19753
20234
  control: immediate
@@ -19975,9 +20456,9 @@ class HistoryWriter {
19975
20456
  if (state.admission?.context.task)
19976
20457
  tasks.add(state.admission.context.task.id);
19977
20458
  for (const row of rows) {
19978
- const v = row.value, run = this.rowRunId(v);
19979
- if (run)
19980
- runs.add(run);
20459
+ const v = row.value, run2 = this.rowRunId(v);
20460
+ if (run2)
20461
+ runs.add(run2);
19981
20462
  if (v.kind === "owner" || v.kind === "capture" || v.kind === "launch" || v.kind === "settlement")
19982
20463
  tasks.add(v.link.taskId);
19983
20464
  if (v.kind === "admission" && v.intent.identity.kind === "action") {
@@ -20073,10 +20554,10 @@ class HistoryWriter {
20073
20554
  try {
20074
20555
  const budget = HistoryReadBudget.authority();
20075
20556
  const intent = this.files.readCommand(commandId, budget);
20076
- const directoryExists = this.files.files.directory(join22(this.files.directory, "commands", commandId));
20557
+ const directoryExists = this.files.files.directory(join24(this.files.directory, "commands", commandId));
20077
20558
  const wanted = intent ? decodeAdmissionIntent(json(intent, RECORD_BYTES)) : null;
20078
20559
  let found = null;
20079
- let run = null;
20560
+ let run2 = null;
20080
20561
  let operation = null;
20081
20562
  const scan = emptyScan();
20082
20563
  for (const batch of this.files.scan(scan, false, budget)) {
@@ -20086,19 +20567,19 @@ class HistoryWriter {
20086
20567
  return { status: "inconclusive" };
20087
20568
  found = row.value.record;
20088
20569
  if (row.value.intent.identity.kind === "action" && row.value.intent.runId)
20089
- run = new RunState(row.value.intent.runId);
20570
+ run2 = new RunState(row.value.intent.runId);
20090
20571
  else if (row.value.intent.identity.kind === "action")
20091
20572
  operation = new OperationState(row.value.intent.operationId);
20092
20573
  }
20093
20574
  for (const row of batch.rows) {
20094
- run?.apply(row, batch.marker.last);
20575
+ run2?.apply(row, batch.marker.last);
20095
20576
  operation?.apply(row, batch.marker.last);
20096
20577
  }
20097
20578
  }
20098
20579
  if (found)
20099
20580
  return {
20100
20581
  status: "found",
20101
- record: decodeStoredCommand(run?.receipt() ?? operation?.receipt() ?? found)
20582
+ record: decodeStoredCommand(run2?.receipt() ?? operation?.receipt() ?? found)
20102
20583
  };
20103
20584
  if (wanted || directoryExists || scan.tail)
20104
20585
  return { status: "inconclusive" };
@@ -20219,8 +20700,8 @@ class HistoryWriter {
20219
20700
  this.assertOrdinary();
20220
20701
  const bytes = encoded(intent);
20221
20702
  this.charge(Buffer.byteLength(bytes), intent.runId, true);
20222
- this.files.files.create(join22(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
20223
- this.files.syncParents(join22(this.files.directory, "commands", intent.commandId, "intent.json"));
20703
+ this.files.files.create(join24(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
20704
+ this.files.syncParents(join24(this.files.directory, "commands", intent.commandId, "intent.json"));
20224
20705
  await this.options.observeWrite?.("intent");
20225
20706
  const policy = this.resourcePolicy(intent.identity.kind === "action" ? intent.identity.expected.configRev : 1);
20226
20707
  return { kind: "admission", intent, record: record2, policy };
@@ -20354,11 +20835,11 @@ class HistoryWriter {
20354
20835
  continue;
20355
20836
  try {
20356
20837
  const checks = checkFold(this.files, taskId2, head.seq, HistoryReadBudget.authority()).state();
20357
- const run = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
20838
+ const run2 = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
20358
20839
  const plan = planFold(this.files, taskId2, head.seq, HistoryReadBudget.authority(), new HistoryNavigation(this.files), true).state();
20359
20840
  taskFoldMemory(this.files).remember(taskId2, head, {
20360
20841
  checks,
20361
- run,
20842
+ run: run2,
20362
20843
  plan
20363
20844
  });
20364
20845
  } catch {}
@@ -20418,10 +20899,10 @@ class HistoryWriter {
20418
20899
  }
20419
20900
  };
20420
20901
  assertContext();
20421
- const run = intent.runId ? this.retainedRun(intent.runId) : null;
20422
- if (run && !run.admission)
20902
+ const run2 = intent.runId ? this.retainedRun(intent.runId) : null;
20903
+ if (run2 && !run2.admission)
20423
20904
  throw new ContractError("conflict");
20424
- expected = run ? run.publicationExpected() : operation.state.publicationExpected();
20905
+ expected = run2 ? run2.publicationExpected() : operation.state.publicationExpected();
20425
20906
  link = {
20426
20907
  epoch: identity.expected.epoch,
20427
20908
  taskId: taskId2,
@@ -20431,7 +20912,7 @@ class HistoryWriter {
20431
20912
  const reader = HistoryReader.open(this.lease.coordination);
20432
20913
  if (!reader)
20433
20914
  throw new ContractError("unavailable");
20434
- record2 = publicationRecord(legacyTaskStore(this.lease.coordination), reader, intent, link, run, request3, expected, operation.facts, this.state.committedSeq);
20915
+ record2 = publicationRecord(legacyTaskStore(this.lease.coordination), reader, intent, link, run2, request3, expected, operation.facts, this.state.committedSeq);
20435
20916
  this.charge(2 * Buffer.byteLength(`${JSON.stringify(record2, null, 2)}
20436
20917
  `), intent.runId, true);
20437
20918
  return this.ownerValue({
@@ -20576,9 +21057,9 @@ class HistoryWriter {
20576
21057
  }
20577
21058
  childSlots() {
20578
21059
  let slots = 0;
20579
- for (const run of this.runs.values())
20580
- for (const auth of run.auth.values()) {
20581
- const child = run.children.get(auth.intent.childRunId);
21060
+ for (const run2 of this.runs.values())
21061
+ for (const auth of run2.auth.values()) {
21062
+ const child = run2.children.get(auth.intent.childRunId);
20582
21063
  if (child ? child.completion === null : auth.result === null || auth.result.outcome === "resolved" && !auth.result.admissionClosed)
20583
21064
  slots++;
20584
21065
  }
@@ -20954,10 +21435,10 @@ class HistoryWriter {
20954
21435
  const checks = decodeCheckObligations(review.checks);
20955
21436
  if (checks.taskId !== input.link.taskId || checks.revision !== fact.checksRevision || canonicalJson(review.observation) !== canonicalJson(changes.observation))
20956
21437
  throw new ContractError("conflict");
20957
- const run = this.retainedRun(fact.runId);
20958
- if (!run.drained || run.admission?.context.task?.id !== input.link.taskId)
21438
+ const run2 = this.retainedRun(fact.runId);
21439
+ if (!run2.drained || run2.admission?.context.task?.id !== input.link.taskId)
20959
21440
  throw new ContractError("conflict");
20960
- const issues = reviewIssues(run, { ...review, checks }, identity.expected.task?.kind === "code", input.link.epoch);
21441
+ const issues = reviewIssues(run2, { ...review, checks }, identity.expected.task?.kind === "code", input.link.epoch);
20961
21442
  if (issues.length && (fact.outcome !== "reviewed-with-issues" || !fact.acceptIssues))
20962
21443
  throw new ContractError("conflict");
20963
21444
  }
@@ -21015,11 +21496,11 @@ class HistoryWriter {
21015
21496
  throw new ContractError("conflict");
21016
21497
  }
21017
21498
  if (fact.kind === "gate" && fact.reservationId && fact.lane !== "check") {
21018
- const run = value.link.runId ? this.runs.get(value.link.runId) ?? this.retainedRun(value.link.runId) : null;
21019
- if (!run?.admission)
21499
+ const run2 = value.link.runId ? this.runs.get(value.link.runId) ?? this.retainedRun(value.link.runId) : null;
21500
+ if (!run2?.admission)
21020
21501
  throw new ContractError("conflict");
21021
- const selected2 = this.files.readAdmission(run.runId, run.admission);
21022
- const allocation = run.admission.assignments.find((a) => a.childRunId === fact.reservationId);
21502
+ const selected2 = this.files.readAdmission(run2.runId, run2.admission);
21503
+ const allocation = run2.admission.assignments.find((a) => a.childRunId === fact.reservationId);
21023
21504
  const assignment = selected2.graph?.assignments.find((a) => a.id === allocation?.assignmentId);
21024
21505
  if (!allocation || (assignment?.purpose === "edit" ? "writer" : "reader") !== fact.lane)
21025
21506
  throw new ContractError("conflict");
@@ -21123,7 +21604,7 @@ function digestHistory(files, exclude) {
21123
21604
  const walk = (path, depth) => {
21124
21605
  if (depth > 8 || !files.files.directory(path))
21125
21606
  throw new ContractError("corrupt-selected");
21126
- const directory = lstatSync13(path);
21607
+ const directory = lstatSync14(path);
21127
21608
  digest.update(`incarnation:${directory.dev}:${directory.ino}
21128
21609
  `);
21129
21610
  const dir = opendirSync8(path), names2 = [];
@@ -21137,11 +21618,11 @@ function digestHistory(files, exclude) {
21137
21618
  dir.closeSync();
21138
21619
  }
21139
21620
  for (const name of names2.sort()) {
21140
- const selected2 = join23(path, name);
21621
+ const selected2 = join25(path, name);
21141
21622
  if (selected2 === exclude)
21142
21623
  continue;
21143
21624
  const rel = relative7(files.directory, selected2);
21144
- if (lstatSync13(selected2).isDirectory()) {
21625
+ if (lstatSync14(selected2).isDirectory()) {
21145
21626
  digest.update(`directory:${Buffer.byteLength(rel)}:${rel}
21146
21627
  `);
21147
21628
  walk(selected2, depth + 1);
@@ -21198,7 +21679,7 @@ function damaged(error) {
21198
21679
  }
21199
21680
  async function healHistory(lease, log) {
21200
21681
  lease.assert();
21201
- const c = lease.coordination, directory = join23(c.directory, "history-v2");
21682
+ const c = lease.coordination, directory = join25(c.directory, "history-v2");
21202
21683
  let files;
21203
21684
  let broken = false;
21204
21685
  try {
@@ -21229,10 +21710,10 @@ async function healHistory(lease, log) {
21229
21710
  }
21230
21711
 
21231
21712
  // src/subagent-process.ts
21232
- import { spawn as spawn2 } from "node:child_process";
21233
- import { join as join24 } from "node:path";
21713
+ import { spawn as spawn3 } from "node:child_process";
21714
+ import { join as join26 } from "node:path";
21234
21715
  import { StringDecoder } from "node:string_decoder";
21235
- import { fileURLToPath as fileURLToPath4 } from "node:url";
21716
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
21236
21717
 
21237
21718
  // src/conversation-context.mjs
21238
21719
  var CONTEXT_BYTES = 2 * 1024 * 1024;
@@ -21838,11 +22319,11 @@ class WorkerRecording {
21838
22319
  try {
21839
22320
  await Promise.race([
21840
22321
  ...this.pending,
21841
- new Promise((resolve8) => {
21842
- abort = resolve8;
22322
+ new Promise((resolve9) => {
22323
+ abort = resolve9;
21843
22324
  signal.addEventListener("abort", abort, { once: true });
21844
22325
  if (signal.aborted)
21845
- resolve8();
22326
+ resolve9();
21846
22327
  })
21847
22328
  ]);
21848
22329
  } finally {
@@ -21870,11 +22351,11 @@ class WorkerRecording {
21870
22351
  let timer;
21871
22352
  await Promise.race([
21872
22353
  Promise.all([...this.pending]),
21873
- new Promise((resolve8) => {
22354
+ new Promise((resolve9) => {
21874
22355
  timer = setTimeout(() => {
21875
22356
  this.failure = "uncertain";
21876
22357
  this.stop();
21877
- resolve8();
22358
+ resolve9();
21878
22359
  }, LIMITS.recordingStallMs);
21879
22360
  })
21880
22361
  ]);
@@ -21904,7 +22385,7 @@ class WorkerRecording {
21904
22385
  // src/subagent-process.ts
21905
22386
  function terminateWindowsTree(pid, fallback) {
21906
22387
  const root = process.env.SystemRoot;
21907
- const taskkill = spawn2(root ? join24(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
22388
+ const taskkill = spawn3(root ? join26(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
21908
22389
  taskkill.once("error", fallback);
21909
22390
  taskkill.once("close", (code2) => {
21910
22391
  if (code2 !== 0)
@@ -21942,8 +22423,8 @@ function runProcess(spec) {
21942
22423
  throw new Error("Invalid service check context");
21943
22424
  if (spec.input !== undefined && Buffer.byteLength(spec.input) > 128 * 1024)
21944
22425
  return Promise.resolve(early("failed", "Worker input exceeds bound"));
21945
- return new Promise((resolve8) => {
21946
- const child = spawn2(spec.command, spec.args, {
22426
+ return new Promise((resolve9) => {
22427
+ const child = spawn3(spec.command, spec.args, {
21947
22428
  cwd: spec.cwd,
21948
22429
  env: spec.env ?? safeChildEnv(),
21949
22430
  detached: process.platform !== "win32",
@@ -22032,7 +22513,7 @@ function runProcess(spec) {
22032
22513
  omissions: ["gap"]
22033
22514
  }
22034
22515
  }, capture);
22035
- resolve8({
22516
+ resolve9({
22036
22517
  outcome,
22037
22518
  closed: closed2,
22038
22519
  exitCode,
@@ -22380,7 +22861,7 @@ function launchEncoded(encoded2, signal, timeoutMs, extra = {}) {
22380
22861
  throw new Error("network");
22381
22862
  return runProcess({
22382
22863
  command: process.execPath,
22383
- args: [fileURLToPath4(new URL("./sdk-worker.mjs", import.meta.url))],
22864
+ args: [fileURLToPath5(new URL("./sdk-worker.mjs", import.meta.url))],
22384
22865
  cwd: encoded2.material.cwd,
22385
22866
  input: encoded2.input,
22386
22867
  env: encoded2.selected.env,
@@ -22562,7 +23043,7 @@ class CheckoutGate {
22562
23043
  throw new ContractError("conflict");
22563
23044
  if (this.waiting.length >= CHECKOUT_WAITERS)
22564
23045
  throw new ContractError("capacity");
22565
- const result = new Promise((resolve8, reject) => {
23046
+ const result = new Promise((resolve9, reject) => {
22566
23047
  const abort = () => {
22567
23048
  const at = this.waiting.indexOf(waiter);
22568
23049
  if (at >= 0)
@@ -22572,7 +23053,7 @@ class CheckoutGate {
22572
23053
  id,
22573
23054
  resolve: (permit) => {
22574
23055
  signal.removeEventListener("abort", abort);
22575
- resolve8(permit);
23056
+ resolve9(permit);
22576
23057
  },
22577
23058
  reject: (error) => {
22578
23059
  signal.removeEventListener("abort", abort);
@@ -22704,8 +23185,8 @@ class OwnerModelChoice {
22704
23185
  }
22705
23186
 
22706
23187
  // src/service/model-config.ts
22707
- import { lstatSync as lstatSync14, realpathSync as realpathSync7 } from "node:fs";
22708
- import { dirname as dirname15, isAbsolute as isAbsolute8, join as join25, resolve as resolve8 } from "node:path";
23188
+ import { lstatSync as lstatSync15, realpathSync as realpathSync9 } from "node:fs";
23189
+ import { dirname as dirname18, isAbsolute as isAbsolute9, join as join27, resolve as resolve9 } from "node:path";
22709
23190
  var CONFIG_BYTES2 = 1024 * 1024;
22710
23191
  var ENTRY_LIMIT = 256;
22711
23192
  function refuse2() {
@@ -22770,16 +23251,16 @@ function captureEnvironment(value) {
22770
23251
  return Object.freeze(out);
22771
23252
  }
22772
23253
  function piSource(agentDir, home, cwd, env) {
22773
- if (!isAbsolute8(home) || !isAbsolute8(cwd))
23254
+ if (!isAbsolute9(home) || !isAbsolute9(cwd))
22774
23255
  refuse2();
22775
- let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join25(home, ".pi", "agent");
23256
+ let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join27(home, ".pi", "agent");
22776
23257
  if (!selected2 || selected2.includes("\x00"))
22777
23258
  refuse2();
22778
23259
  if (selected2 === "~" || selected2.startsWith("~/"))
22779
23260
  selected2 = home + selected2.slice(1);
22780
- selected2 = resolve8(cwd, selected2);
22781
- const directory = join25(realpathSync7(dirname15(selected2)), selected2.slice(dirname15(selected2).length + 1));
22782
- if (!lstatSync14(directory).isDirectory() || lstatSync14(directory).isSymbolicLink())
23261
+ selected2 = resolve9(cwd, selected2);
23262
+ const directory = join27(realpathSync9(dirname18(selected2)), selected2.slice(dirname18(selected2).length + 1));
23263
+ if (!lstatSync15(directory).isDirectory() || lstatSync15(directory).isSymbolicLink())
22783
23264
  refuse2();
22784
23265
  const files = new PrivateFiles(directory, false);
22785
23266
  if (!files.directory(directory))
@@ -22787,8 +23268,8 @@ function piSource(agentDir, home, cwd, env) {
22787
23268
  return {
22788
23269
  directory,
22789
23270
  files,
22790
- authPath: join25(directory, "auth.json"),
22791
- modelsPath: join25(directory, "models.json")
23271
+ authPath: join27(directory, "auth.json"),
23272
+ modelsPath: join27(directory, "models.json")
22792
23273
  };
22793
23274
  }
22794
23275
  function templateNames(value) {
@@ -23736,10 +24217,10 @@ class OwnerModelContext {
23736
24217
  closed2 = true;
23737
24218
  };
23738
24219
  let reportClosed;
23739
- const closedWait = new Promise((resolve9) => {
24220
+ const closedWait = new Promise((resolve10) => {
23740
24221
  reportClosed = () => {
23741
24222
  close();
23742
- resolve9(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
24223
+ resolve10(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
23743
24224
  };
23744
24225
  });
23745
24226
  input.signal.addEventListener("abort", reportClosed, { once: true });
@@ -24173,8 +24654,8 @@ class ServiceOwner {
24173
24654
  if (!this.attempt) {
24174
24655
  this.reportingExpired = false;
24175
24656
  let complete;
24176
- this.attempt = new Promise((resolve9) => {
24177
- complete = resolve9;
24657
+ this.attempt = new Promise((resolve10) => {
24658
+ complete = resolve10;
24178
24659
  });
24179
24660
  const finish = () => {
24180
24661
  this.attempt = undefined;
@@ -24192,11 +24673,11 @@ class ServiceOwner {
24192
24673
  try {
24193
24674
  await Promise.race([
24194
24675
  this.attempt,
24195
- new Promise((resolve9) => {
24676
+ new Promise((resolve10) => {
24196
24677
  timer = setTimeout(() => {
24197
24678
  this.reportingExpired = true;
24198
24679
  this.persistPhase("quarantined");
24199
- resolve9();
24680
+ resolve10();
24200
24681
  }, waitMs);
24201
24682
  })
24202
24683
  ]);
@@ -24227,12 +24708,12 @@ class ServiceOwner {
24227
24708
 
24228
24709
  // src/service/workbench.ts
24229
24710
  import { opendirSync as opendirSync14 } from "node:fs";
24230
- import { join as join31 } from "node:path";
24711
+ import { join as join33 } from "node:path";
24231
24712
 
24232
24713
  // src/service/conversation-workflow.ts
24233
24714
  import { randomUUID as randomUUID21 } from "node:crypto";
24234
24715
  import { opendirSync as opendirSync11 } from "node:fs";
24235
- import { dirname as dirname17, join as join27 } from "node:path";
24716
+ import { dirname as dirname20, join as join29 } from "node:path";
24236
24717
 
24237
24718
  // src/cadence-instructions.ts
24238
24719
  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.
@@ -24244,12 +24725,12 @@ During accepted work answer questions, report actual retained progress, and let
24244
24725
 
24245
24726
  // src/service/conversations.ts
24246
24727
  import { randomUUID as randomUUID20 } from "node:crypto";
24247
- import { lstatSync as lstatSync16, opendirSync as opendirSync10, realpathSync as realpathSync8, statfsSync as statfsSync2 } from "node:fs";
24248
- import { dirname as dirname16, join as join26 } from "node:path";
24728
+ import { lstatSync as lstatSync17, opendirSync as opendirSync10, realpathSync as realpathSync10, statfsSync as statfsSync2 } from "node:fs";
24729
+ import { dirname as dirname19, join as join28 } from "node:path";
24249
24730
 
24250
24731
  // src/service/conversation-history.ts
24251
24732
  import { randomUUID as randomUUID19 } from "node:crypto";
24252
- import { lstatSync as lstatSync15, opendirSync as opendirSync9 } from "node:fs";
24733
+ import { lstatSync as lstatSync16, opendirSync as opendirSync9 } from "node:fs";
24253
24734
  var CONVERSATION_PAGE = 50;
24254
24735
  var SCAN_ENTRIES = 8;
24255
24736
  var SCANS = 16;
@@ -24268,7 +24749,7 @@ class ConversationHistory {
24268
24749
  this.summary = summary2;
24269
24750
  }
24270
24751
  incarnation() {
24271
- const st = lstatSync15(this.path, { bigint: true });
24752
+ const st = lstatSync16(this.path, { bigint: true });
24272
24753
  if (!st.isDirectory() || st.isSymbolicLink())
24273
24754
  throw new ContractError("corrupt-selected");
24274
24755
  return `${st.dev}:${st.ino}`;
@@ -24490,7 +24971,7 @@ var OMITTED_FLAG = {
24490
24971
  };
24491
24972
  function observedFile(path) {
24492
24973
  try {
24493
- const s = lstatSync16(path);
24974
+ const s = lstatSync17(path);
24494
24975
  return [s.dev, s.ino, s.size, s.mode, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
24495
24976
  } catch (error) {
24496
24977
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
@@ -24629,9 +25110,9 @@ class Conversations {
24629
25110
  summaries = new Map;
24630
25111
  constructor(o) {
24631
25112
  this.o = o;
24632
- this.root = join26(o.coordination.directory, "conversations-v1");
24633
- this.cwd = realpathSync8(o.cwd);
24634
- const sessions = join26(this.root, "sessions");
25113
+ this.root = join28(o.coordination.directory, "conversations-v1");
25114
+ this.cwd = realpathSync10(o.cwd);
25115
+ const sessions = join28(this.root, "sessions");
24635
25116
  this.history = new ConversationHistory(sessions, () => {
24636
25117
  this.o.owner.lease.assert();
24637
25118
  return this.files.directory(sessions);
@@ -24645,13 +25126,13 @@ class Conversations {
24645
25126
  return this.o.coordination.files;
24646
25127
  }
24647
25128
  path(id, name) {
24648
- return join26(this.root, "turns", decodeId(id), name);
25129
+ return join28(this.root, "turns", decodeId(id), name);
24649
25130
  }
24650
25131
  identityPath(id) {
24651
- return join26(this.root, "identities", `${decodeId(id)}.json`);
25132
+ return join28(this.root, "identities", `${decodeId(id)}.json`);
24652
25133
  }
24653
25134
  metadataPath(id) {
24654
- return join26(this.root, "sessions", `${decodeId(id)}.json`);
25135
+ return join28(this.root, "sessions", `${decodeId(id)}.json`);
24655
25136
  }
24656
25137
  read(path, max) {
24657
25138
  const value = this.files.read(path, max);
@@ -24704,7 +25185,7 @@ class Conversations {
24704
25185
  return meta;
24705
25186
  }
24706
25187
  slotPath(id, ordinal) {
24707
- return join26(this.root, "indices", decodeId(id), `${integer(ordinal, 0)}.json`);
25188
+ return join28(this.root, "indices", decodeId(id), `${integer(ordinal, 0)}.json`);
24708
25189
  }
24709
25190
  turnAt(meta, ordinal) {
24710
25191
  if (ordinal < 0 || ordinal >= meta.count)
@@ -24750,7 +25231,7 @@ class Conversations {
24750
25231
  } : turn;
24751
25232
  }
24752
25233
  controlBound(id) {
24753
- const path = join26(this.root, "control-links", `${decodeId(id)}.json`);
25234
+ const path = join28(this.root, "control-links", `${decodeId(id)}.json`);
24754
25235
  const value = this.read(path, META_BYTES);
24755
25236
  if (value === undefined)
24756
25237
  return false;
@@ -24760,11 +25241,11 @@ class Conversations {
24760
25241
  return true;
24761
25242
  }
24762
25243
  controlKey(id) {
24763
- return observedFile(join26(this.root, "control-links", `${decodeId(id)}.json`));
25244
+ return observedFile(join28(this.root, "control-links", `${decodeId(id)}.json`));
24764
25245
  }
24765
25246
  bindControl(id) {
24766
25247
  if (!this.controlBound(id))
24767
- this.write(join26(this.root, "control-links", `${decodeId(id)}.json`), { schema: "cadence-conversation-control/1", conversationId: id }, META_BYTES);
25248
+ this.write(join28(this.root, "control-links", `${decodeId(id)}.json`), { schema: "cadence-conversation-control/1", conversationId: id }, META_BYTES);
24768
25249
  }
24769
25250
  hasTurn(id, turnId) {
24770
25251
  const meta = this.metadata(id);
@@ -24840,7 +25321,7 @@ class Conversations {
24840
25321
  }
24841
25322
  assertSettled() {
24842
25323
  this.o.owner.lease.assert();
24843
- const path = join26(this.root, "sessions");
25324
+ const path = join28(this.root, "sessions");
24844
25325
  if (!this.files.directory(path))
24845
25326
  return;
24846
25327
  const dir = opendirSync10(path);
@@ -24916,7 +25397,7 @@ class Conversations {
24916
25397
  attempted(conversationId, commandId) {
24917
25398
  this.o.owner.lease.assert();
24918
25399
  const meta = this.metadata(conversationId);
24919
- return this.active.has(commandId) || this.files.directory(dirname16(this.path(commandId, "accepted.json"))) || !!meta && this.contains(meta, commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
25400
+ return this.active.has(commandId) || this.files.directory(dirname19(this.path(commandId, "accepted.json"))) || !!meta && this.contains(meta, commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
24920
25401
  }
24921
25402
  command(input, reply) {
24922
25403
  return {
@@ -24940,7 +25421,7 @@ class Conversations {
24940
25421
  const receipt = this.receipt(input, !!control?.reply);
24941
25422
  if (receipt)
24942
25423
  return receipt;
24943
- if (this.files.directory(dirname16(this.path(input.commandId, "accepted.json"))))
25424
+ if (this.files.directory(dirname19(this.path(input.commandId, "accepted.json"))))
24944
25425
  throw new ContractError("corrupt-selected");
24945
25426
  if (this.o.owner.state !== "idle")
24946
25427
  throw new ContractError("quarantine");
@@ -24998,8 +25479,8 @@ class Conversations {
24998
25479
  throw new ContractError("corrupt-selected");
24999
25480
  const abort = new AbortController;
25000
25481
  let begin;
25001
- const ready2 = new Promise((resolve9) => {
25002
- begin = resolve9;
25482
+ const ready2 = new Promise((resolve10) => {
25483
+ begin = resolve10;
25003
25484
  });
25004
25485
  const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort, control));
25005
25486
  const live2 = {
@@ -25041,7 +25522,7 @@ class Conversations {
25041
25522
  }
25042
25523
  origin(taskId2) {
25043
25524
  this.o.owner.lease.assert();
25044
- const value = this.read(join26(this.root, "task-links", `${decodeId(taskId2)}.json`), META_BYTES);
25525
+ const value = this.read(join28(this.root, "task-links", `${decodeId(taskId2)}.json`), META_BYTES);
25045
25526
  if (value === undefined)
25046
25527
  return { kind: "task-origin", taskId: taskId2, conversationId: null };
25047
25528
  const row = closed(value, ["conversationId"]);
@@ -25309,10 +25790,10 @@ class ConversationWorkflow {
25309
25790
  grants = new Map;
25310
25791
  constructor(o) {
25311
25792
  this.o = o;
25312
- this.root = join27(o.coordination.directory, "conversation-workflows-v1");
25793
+ this.root = join29(o.coordination.directory, "conversation-workflows-v1");
25313
25794
  }
25314
25795
  path(id) {
25315
- return join27(this.root, decodeId(id), "state.json");
25796
+ return join29(this.root, decodeId(id), "state.json");
25316
25797
  }
25317
25798
  read(id) {
25318
25799
  this.o.owner.lease.assert();
@@ -25321,7 +25802,7 @@ class ConversationWorkflow {
25321
25802
  const bound = this.o.conversations.controlBound(id);
25322
25803
  const file = this.o.coordination.files.read(path, BYTES);
25323
25804
  if (!file)
25324
- return bound || this.o.coordination.files.directory(dirname17(path)) ? unusable2(id) : { state: fresh2(id) };
25805
+ return bound || this.o.coordination.files.directory(dirname20(path)) ? unusable2(id) : { state: fresh2(id) };
25325
25806
  const record2 = closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
25326
25807
  "schema",
25327
25808
  "state"
@@ -25417,7 +25898,7 @@ class ConversationWorkflow {
25417
25898
  return loaded.state;
25418
25899
  }
25419
25900
  runLink(runId) {
25420
- return join27(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
25901
+ return join29(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
25421
25902
  }
25422
25903
  links(runIds) {
25423
25904
  this.o.owner.lease.assert();
@@ -25499,14 +25980,14 @@ class ConversationWorkflow {
25499
25980
  }, current2.file);
25500
25981
  } catch {}
25501
25982
  }
25502
- preview(run, bytes, steps) {
25983
+ preview(run2, bytes, steps) {
25503
25984
  const clip = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
25504
25985
  return {
25505
- ...run,
25506
- goal: clip(run.goal, 320),
25507
- notice: clip(run.notice, 512),
25508
- stepsOmitted: Math.max(0, run.steps.length - steps),
25509
- steps: run.steps.slice(-steps).map((s) => {
25986
+ ...run2,
25987
+ goal: clip(run2.goal, 320),
25988
+ notice: clip(run2.notice, 512),
25989
+ stepsOmitted: Math.max(0, run2.steps.length - steps),
25990
+ steps: run2.steps.slice(-steps).map((s) => {
25510
25991
  const text2 = clip(s.text, bytes);
25511
25992
  return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
25512
25993
  })
@@ -25703,7 +26184,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25703
26184
  approval(c, caller) {
25704
26185
  if (!caller)
25705
26186
  throw new ContractError("forbidden");
25706
- const evidence = join27(this.root, decodeId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
26187
+ const evidence = join29(this.root, decodeId(c.conversationId), "approvals", `${decodeId(c.commandId)}.json`);
25707
26188
  let effects = true;
25708
26189
  try {
25709
26190
  effects = this.o.owner.state !== "idle";
@@ -25829,21 +26310,21 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25829
26310
  // src/service/workflows.ts
25830
26311
  import { randomUUID as randomUUID23 } from "node:crypto";
25831
26312
  import {
25832
- lstatSync as lstatSync20,
26313
+ lstatSync as lstatSync21,
25833
26314
  opendirSync as opendirSync13,
25834
- realpathSync as realpathSync10,
26315
+ realpathSync as realpathSync12,
25835
26316
  rmdirSync,
25836
26317
  statfsSync as statfsSync3,
25837
- writeFileSync as writeFileSync4
26318
+ writeFileSync as writeFileSync5
25838
26319
  } from "node:fs";
25839
- import { basename as basename3, dirname as dirname19, join as join30, resolve as resolve10 } from "node:path";
25840
- import { fileURLToPath as fileURLToPath5 } from "node:url";
26320
+ import { basename as basename3, dirname as dirname22, join as join32, resolve as resolve11 } from "node:path";
26321
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
25841
26322
 
25842
26323
  // src/task-diff.ts
25843
- import { spawnSync as spawnSync3 } from "node:child_process";
26324
+ import { spawnSync as spawnSync5 } from "node:child_process";
25844
26325
  import { createHash as createHash24 } from "node:crypto";
25845
- import { lstatSync as lstatSync17, readdirSync as readdirSync3, readlinkSync } from "node:fs";
25846
- import { join as join28, relative as relative8 } from "node:path";
26326
+ import { lstatSync as lstatSync18, readdirSync as readdirSync3, readlinkSync } from "node:fs";
26327
+ import { join as join30, relative as relative8 } from "node:path";
25847
26328
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
25848
26329
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
25849
26330
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -25862,7 +26343,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25862
26343
  if (Date.now() >= deadline)
25863
26344
  outcome = "time budget exhausted";
25864
26345
  else {
25865
- const result = spawnSync3("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
26346
+ const result = spawnSync5("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
25866
26347
  cwd: root,
25867
26348
  encoding: "buffer",
25868
26349
  timeout: Math.max(1, deadline - Date.now()),
@@ -25886,8 +26367,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25886
26367
  return;
25887
26368
  }
25888
26369
  try {
25889
- const path = join28(root, name);
25890
- const st = lstatSync17(path);
26370
+ const path = join30(root, name);
26371
+ const st = lstatSync18(path);
25891
26372
  add(name, `${st.mode}:${st.size}`);
25892
26373
  if (st.isSymbolicLink()) {
25893
26374
  add(name, readlinkSync(path));
@@ -25912,7 +26393,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25912
26393
  limits.push(`Unreadable/changing: ${name}`);
25913
26394
  }
25914
26395
  };
25915
- const probe2 = spawnSync3("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
26396
+ const probe2 = spawnSync5("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
25916
26397
  cwd: root,
25917
26398
  env: gitEnvironment(),
25918
26399
  timeout: 3000,
@@ -26027,7 +26508,7 @@ ${data2.toString("utf8")}`);
26027
26508
  return;
26028
26509
  }
26029
26510
  for (const name of names2) {
26030
- const path = join28(dir, name);
26511
+ const path = join30(dir, name);
26031
26512
  const rel = relative8(root, path).split("\\").join("/");
26032
26513
  if (rel === ".git" || admin(rel))
26033
26514
  continue;
@@ -26036,7 +26517,7 @@ ${data2.toString("utf8")}`);
26036
26517
  break;
26037
26518
  }
26038
26519
  try {
26039
- const st = lstatSync17(path);
26520
+ const st = lstatSync18(path);
26040
26521
  if (st.isDirectory())
26041
26522
  walk(path, depth + 1);
26042
26523
  else
@@ -26062,21 +26543,21 @@ ${data2.toString("utf8")}`);
26062
26543
  }
26063
26544
 
26064
26545
  // src/service/workflow-git.ts
26065
- import { spawn as spawn3, spawnSync as spawnSync4 } from "node:child_process";
26546
+ import { spawn as spawn4, spawnSync as spawnSync6 } from "node:child_process";
26066
26547
  import { createHash as createHash25 } from "node:crypto";
26067
26548
  import {
26068
26549
  closeSync as closeSync9,
26069
- constants as constants7,
26550
+ constants as constants8,
26070
26551
  fstatSync as fstatSync6,
26071
- lstatSync as lstatSync18,
26552
+ lstatSync as lstatSync19,
26072
26553
  openSync as openSync9,
26073
26554
  readdirSync as readdirSync4,
26074
26555
  readlinkSync as readlinkSync2,
26075
26556
  readSync as readSync5,
26076
- realpathSync as realpathSync9
26557
+ realpathSync as realpathSync11
26077
26558
  } from "node:fs";
26078
26559
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
26079
- import { dirname as dirname18, isAbsolute as isAbsolute9, join as join29, relative as relative9, resolve as resolve9, sep as sep6 } from "node:path";
26560
+ import { dirname as dirname21, isAbsolute as isAbsolute10, join as join31, relative as relative9, resolve as resolve10, sep as sep7 } from "node:path";
26080
26561
  var NAMES_BYTES = 64 * 1024 * 1024;
26081
26562
  var SYNC_MS = 30000;
26082
26563
  var READ_MS = 120000;
@@ -26092,7 +26573,7 @@ class WorkflowRefusal extends ContractError {
26092
26573
  }
26093
26574
  }
26094
26575
  function gitRead(cwd, args) {
26095
- const r = spawnSync4("git", gitArguments(args), {
26576
+ const r = spawnSync6("git", gitArguments(args), {
26096
26577
  cwd,
26097
26578
  env: gitEnvironment(),
26098
26579
  encoding: "utf8",
@@ -26105,7 +26586,7 @@ function gitRead(cwd, args) {
26105
26586
  return r.stdout;
26106
26587
  }
26107
26588
  function gitAnswer(cwd, args) {
26108
- const r = spawnSync4("git", gitArguments(args), {
26589
+ const r = spawnSync6("git", gitArguments(args), {
26109
26590
  cwd,
26110
26591
  env: gitEnvironment(),
26111
26592
  encoding: "utf8",
@@ -26119,7 +26600,7 @@ function gitAnswer(cwd, args) {
26119
26600
  }
26120
26601
  function gitRun(cwd, args, timeoutMs = READ_MS) {
26121
26602
  return new Promise((done, fail2) => {
26122
- const child = spawn3("git", gitArguments(args), {
26603
+ const child = spawn4("git", gitArguments(args), {
26123
26604
  cwd,
26124
26605
  env: gitEnvironment(),
26125
26606
  stdio: ["ignore", "pipe", "ignore"],
@@ -26162,19 +26643,19 @@ async function gitHead(cwd) {
26162
26643
  }
26163
26644
  function contains2(root, path) {
26164
26645
  const within = relative9(root, path);
26165
- return !within || !within.startsWith(`..${sep6}`) && within !== ".." && !isAbsolute9(within);
26646
+ return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute10(within);
26166
26647
  }
26167
26648
  function nested(a, b) {
26168
26649
  return contains2(a, b) || contains2(b, a);
26169
26650
  }
26170
26651
  function safeWorkflowFile(cwd, name) {
26171
26652
  workflowPath(name);
26172
- const p = resolve9(cwd, name);
26653
+ const p = resolve10(cwd, name);
26173
26654
  if (relative9(cwd, p).startsWith(".."))
26174
26655
  throw new ContractError("forbidden");
26175
- safeDirectory(dirname18(p));
26656
+ safeDirectory(dirname21(p));
26176
26657
  try {
26177
- const st = lstatSync18(p);
26658
+ const st = lstatSync19(p);
26178
26659
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
26179
26660
  throw new ContractError("forbidden");
26180
26661
  } catch (e) {
@@ -26185,12 +26666,12 @@ function safeWorkflowFile(cwd, name) {
26185
26666
  }
26186
26667
  function declaredTarget(cwd, name) {
26187
26668
  workflowPath(name);
26188
- const p = resolve9(cwd, name);
26669
+ const p = resolve10(cwd, name);
26189
26670
  if (relative9(cwd, p).startsWith(".."))
26190
26671
  throw new ContractError("forbidden");
26191
- safeDirectory(dirname18(p));
26672
+ safeDirectory(dirname21(p));
26192
26673
  try {
26193
- const st = lstatSync18(p);
26674
+ const st = lstatSync19(p);
26194
26675
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
26195
26676
  throw new ContractError("forbidden");
26196
26677
  } catch (e) {
@@ -26216,7 +26697,7 @@ function fileIdentity(p, st, hashBytes) {
26216
26697
  return quick;
26217
26698
  let fd;
26218
26699
  try {
26219
- fd = openSync9(p, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
26700
+ fd = openSync9(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
26220
26701
  } catch (e) {
26221
26702
  if (absent2(e))
26222
26703
  return null;
@@ -26241,7 +26722,7 @@ async function fileIdentityAsync(p, st, hashBytes) {
26241
26722
  return quick;
26242
26723
  let handle;
26243
26724
  try {
26244
- handle = await open2(p, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
26725
+ handle = await open2(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
26245
26726
  } catch (e) {
26246
26727
  if (absent2(e))
26247
26728
  return null;
@@ -26270,8 +26751,8 @@ function directoryIdentity(root, name) {
26270
26751
  continue;
26271
26752
  if (++count2 > DIRECTORY_ENTRIES)
26272
26753
  throw tooLarge(name);
26273
- const full = join29(directory, entry), relative10 = `${prefix}${entry}`;
26274
- const st = lstatSync18(full);
26754
+ const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
26755
+ const st = lstatSync19(full);
26275
26756
  if (st.isDirectory()) {
26276
26757
  rows.push(`${relative10}/`);
26277
26758
  visit(full, `${relative10}/`);
@@ -26292,7 +26773,7 @@ async function directoryIdentityAsync(root, name) {
26292
26773
  continue;
26293
26774
  if (++count2 > DIRECTORY_ENTRIES)
26294
26775
  throw tooLarge(name);
26295
- const full = join29(directory, entry), relative10 = `${prefix}${entry}`;
26776
+ const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
26296
26777
  const st = await lstat(full);
26297
26778
  if (st.isDirectory()) {
26298
26779
  rows.push(`${relative10}/`);
@@ -26306,12 +26787,12 @@ async function directoryIdentityAsync(root, name) {
26306
26787
  `))}`;
26307
26788
  }
26308
26789
  function pathIdentity(cwd, name, walk = true) {
26309
- const p = resolve9(cwd, name);
26790
+ const p = resolve10(cwd, name);
26310
26791
  if (relative9(cwd, p).startsWith(".."))
26311
26792
  throw new ContractError("forbidden");
26312
26793
  let st;
26313
26794
  try {
26314
- st = lstatSync18(p);
26795
+ st = lstatSync19(p);
26315
26796
  } catch (e) {
26316
26797
  if (absent2(e))
26317
26798
  return null;
@@ -26322,7 +26803,7 @@ function pathIdentity(cwd, name, walk = true) {
26322
26803
  return fileIdentity(p, st, HASH_BYTES);
26323
26804
  }
26324
26805
  async function pathIdentityAsync(cwd, name) {
26325
- const p = resolve9(cwd, name);
26806
+ const p = resolve10(cwd, name);
26326
26807
  if (relative9(cwd, p).startsWith(".."))
26327
26808
  throw new ContractError("forbidden");
26328
26809
  let st;
@@ -26526,20 +27007,20 @@ ${block}
26526
27007
  async function assertWorktree(root, cwd) {
26527
27008
  if (!safeDirectory(cwd))
26528
27009
  throw new ContractError("stale");
26529
- const real = (p) => realpathSync9(resolve9(p));
27010
+ const real = (p) => realpathSync11(resolve10(p));
26530
27011
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
26531
27012
  throw new ContractError("stale");
26532
- const common = async (p) => real(resolve9(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
27013
+ const common = async (p) => real(resolve10(p, (await gitText(p, ["rev-parse", "--git-common-dir"])).trim()));
26533
27014
  if (await common(root) !== await common(cwd))
26534
27015
  throw new ContractError("stale");
26535
- const marker2 = resolve9(cwd, ".git");
26536
- if (!lstatSync18(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
27016
+ const marker2 = resolve10(cwd, ".git");
27017
+ if (!lstatSync19(marker2).isFile() || !(readBounded(marker2, 8192)?.toString("utf8") ?? "").startsWith("gitdir: "))
26537
27018
  throw new ContractError("stale");
26538
27019
  }
26539
27020
 
26540
27021
  // src/service/workflow-history.ts
26541
27022
  import { randomUUID as randomUUID22 } from "node:crypto";
26542
- import { lstatSync as lstatSync19, opendirSync as opendirSync12 } from "node:fs";
27023
+ import { lstatSync as lstatSync20, opendirSync as opendirSync12 } from "node:fs";
26543
27024
  class WorkflowHistoryScanner {
26544
27025
  path;
26545
27026
  directory;
@@ -26550,7 +27031,7 @@ class WorkflowHistoryScanner {
26550
27031
  this.directory = directory;
26551
27032
  }
26552
27033
  incarnation() {
26553
- const st = lstatSync19(this.path, { bigint: true });
27034
+ const st = lstatSync20(this.path, { bigint: true });
26554
27035
  if (!st.isDirectory() || st.isSymbolicLink())
26555
27036
  throw new ContractError("corrupt-selected");
26556
27037
  return `${st.dev}:${st.ino}`;
@@ -26639,9 +27120,9 @@ class WorkflowHistoryScanner {
26639
27120
 
26640
27121
  // src/service/workflows.ts
26641
27122
  var OWNER_RUNTIME = Object.freeze({
26642
- version: "2.0.28",
26643
- build: "87bcf7aa64bfe005d9861522dc15aa94185c48c56a4e41b1a1e18645b2d075d5",
26644
- entry: fileURLToPath5(import.meta.url),
27123
+ version: "2.0.29",
27124
+ build: "159ebb3ba7182c899b19bd0e5349d74397c5f1bbb6ae29dc9f03848edd457b24",
27125
+ entry: fileURLToPath6(import.meta.url),
26645
27126
  pid: process.pid,
26646
27127
  node: process.versions.node,
26647
27128
  platform: process.platform,
@@ -26827,12 +27308,12 @@ class Workflows {
26827
27308
  grants = new Map;
26828
27309
  constructor(o) {
26829
27310
  this.o = o;
26830
- this.root = join30(o.coordination.directory, "workflows-v1");
26831
- this.cwd = realpathSync10(o.coordination.store.root);
26832
- this.worktreeRoot = join30(o.coordination.stateHome, "cadence-worktrees-v1", basename3(o.coordination.store.privateRoot));
26833
- this.historyScanner = new WorkflowHistoryScanner(join30(this.root, "runs"), () => {
27311
+ this.root = join32(o.coordination.directory, "workflows-v1");
27312
+ this.cwd = realpathSync12(o.coordination.store.root);
27313
+ this.worktreeRoot = join32(o.coordination.stateHome, "cadence-worktrees-v1", basename3(o.coordination.store.privateRoot));
27314
+ this.historyScanner = new WorkflowHistoryScanner(join32(this.root, "runs"), () => {
26834
27315
  this.o.owner.lease.assert();
26835
- return this.files.directory(join30(this.root, "runs"));
27316
+ return this.files.directory(join32(this.root, "runs"));
26836
27317
  });
26837
27318
  this.recover();
26838
27319
  }
@@ -26840,7 +27321,7 @@ class Workflows {
26840
27321
  return this.o.coordination.files;
26841
27322
  }
26842
27323
  path(id, name) {
26843
- return join30(this.root, "runs", decodeId(id), name);
27324
+ return join32(this.root, "runs", decodeId(id), name);
26844
27325
  }
26845
27326
  write(path, value, expected, max = RECORD_BYTES2) {
26846
27327
  this.o.owner.lease.assert();
@@ -26857,7 +27338,7 @@ class Workflows {
26857
27338
  `), 2048, this.o.secrets());
26858
27339
  }
26859
27340
  recover() {
26860
- const runs = join30(this.root, "runs");
27341
+ const runs = join32(this.root, "runs");
26861
27342
  if (!this.files.directory(runs))
26862
27343
  return;
26863
27344
  const ids = [];
@@ -26892,7 +27373,7 @@ class Workflows {
26892
27373
  const accepted2 = this.retained(this.path(id, "accepted.json"));
26893
27374
  if (!accepted2)
26894
27375
  return;
26895
- let run2;
27376
+ let run3;
26896
27377
  try {
26897
27378
  const o = closed(parseWireJson(accepted2.bytes.toString("utf8"), RECORD_BYTES2), ["epoch", "request"]);
26898
27379
  const request3 = decodeWorkflowRequest(o.request);
@@ -26901,7 +27382,7 @@ class Workflows {
26901
27382
  try {
26902
27383
  goal = this.proposal(request3.proposalId).plan.goal;
26903
27384
  } catch {}
26904
- run2 = {
27385
+ run3 = {
26905
27386
  id,
26906
27387
  epoch: decodeId(o.epoch),
26907
27388
  goal,
@@ -26915,30 +27396,30 @@ class Workflows {
26915
27396
  } catch {
26916
27397
  return;
26917
27398
  }
26918
- this.write(path, run2);
27399
+ this.write(path, run3);
26919
27400
  return;
26920
27401
  }
26921
- let run;
27402
+ let run2;
26922
27403
  try {
26923
- run = decodeWorkflowRun(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
27404
+ run2 = decodeWorkflowRun(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
26924
27405
  } catch {
26925
27406
  return;
26926
27407
  }
26927
- if (run.id !== id || !["queued", "running"].includes(run.status) && run.phase === "finished")
27408
+ if (run2.id !== id || !["queued", "running"].includes(run2.status) && run2.phase === "finished")
26928
27409
  return;
26929
- const integrating = run.phase === "integrating";
26930
- run.status = "unknown";
26931
- run.phase = "finished";
26932
- for (const step of run.steps)
27410
+ const integrating = run2.phase === "integrating";
27411
+ run2.status = "unknown";
27412
+ run2.phase = "finished";
27413
+ for (const step of run2.steps)
26933
27414
  if (step.status === "running")
26934
27415
  step.status = "unknown";
26935
- run.notice = diagnosticText([
26936
- run.notice,
27416
+ run2.notice = diagnosticText([
27417
+ run2.notice,
26937
27418
  RESTARTED,
26938
27419
  integrating ? "Integration had started: inspect the target branch; a fast-forward may have completed." : ""
26939
27420
  ].filter(Boolean).join(`
26940
27421
  `), 2048);
26941
- this.write(path, run, file);
27422
+ this.write(path, run2, file);
26942
27423
  }
26943
27424
  current() {
26944
27425
  this.o.owner.lease.assert();
@@ -26968,7 +27449,7 @@ class Workflows {
26968
27449
  };
26969
27450
  }
26970
27451
  proposal(id) {
26971
- const file = this.files.read(join30(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
27452
+ const file = this.files.read(join32(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
26972
27453
  if (!file)
26973
27454
  throw new ContractError("unavailable");
26974
27455
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
@@ -26990,9 +27471,9 @@ class Workflows {
26990
27471
  this.o.owner.lease.assert();
26991
27472
  return {
26992
27473
  kind: "workflow-active",
26993
- runs: [...this.active.values()].map(({ run }) => ({
26994
- ...structuredClone(run),
26995
- goal: clipUnits(run.goal, 320),
27474
+ runs: [...this.active.values()].map(({ run: run2 }) => ({
27475
+ ...structuredClone(run2),
27476
+ goal: clipUnits(run2.goal, 320),
26996
27477
  steps: []
26997
27478
  }))
26998
27479
  };
@@ -27007,13 +27488,13 @@ class Workflows {
27007
27488
  const view = this.view(id);
27008
27489
  if (view.kind !== "workflow" || view.response.type !== "run")
27009
27490
  throw new ContractError("invalid");
27010
- const run = view.response.run;
27491
+ const run2 = view.response.run;
27011
27492
  return {
27012
27493
  id,
27013
27494
  run: {
27014
- ...run,
27015
- goal: clipUnits(sanitizeText(run.goal, this.o.secrets()), 320),
27016
- notice: this.notice(run.notice),
27495
+ ...run2,
27496
+ goal: clipUnits(sanitizeText(run2.goal, this.o.secrets()), 320),
27497
+ notice: this.notice(run2.notice),
27017
27498
  steps: []
27018
27499
  }
27019
27500
  };
@@ -27039,27 +27520,27 @@ class Workflows {
27039
27520
  const file = live2 ? undefined : this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
27040
27521
  if (!live2 && !file)
27041
27522
  throw new ContractError("unavailable");
27042
- const run = decodeWorkflowRun(live2 ? live2.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
27043
- if (run.id !== id)
27523
+ const run2 = decodeWorkflowRun(live2 ? live2.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
27524
+ if (run2.id !== id)
27044
27525
  throw new ContractError("corrupt-selected");
27045
- if (!live2 && ["running", "queued"].includes(run.status))
27046
- run.status = "unknown";
27526
+ if (!live2 && ["running", "queued"].includes(run2.status))
27527
+ run2.status = "unknown";
27047
27528
  return {
27048
27529
  kind: "workflow",
27049
27530
  commandId: null,
27050
- response: { type: "run", run }
27531
+ response: { type: "run", run: run2 }
27051
27532
  };
27052
27533
  }
27053
27534
  transcript(id, stepId) {
27054
27535
  const view = this.view(id);
27055
27536
  if (view.kind !== "workflow" || view.response.type !== "run")
27056
27537
  throw new ContractError("unavailable");
27057
- const run = view.response.run, step = run.steps.find((s) => s.id === stepId);
27538
+ const run2 = view.response.run, step = run2.steps.find((s) => s.id === stepId);
27058
27539
  if (!step?.childRunId)
27059
27540
  throw new ContractError("unavailable");
27060
27541
  const file = this.files.read(this.path(id, `transcripts/${step.childRunId}.json`), RECORD_BYTES2);
27061
27542
  const turn = file ? decodeChatTurn(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2)) : null;
27062
- if (turn && (turn.id !== step.childRunId || turn.epoch !== run.epoch))
27543
+ if (turn && (turn.id !== step.childRunId || turn.epoch !== run2.epoch))
27063
27544
  throw new ContractError("corrupt-selected");
27064
27545
  if (turn) {
27065
27546
  const secrets = this.o.secrets();
@@ -27122,8 +27603,8 @@ class Workflows {
27122
27603
  if (action === "prepare")
27123
27604
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
27124
27605
  if (action === "propose")
27125
- return !!this.files.read(join30(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
27126
- return this.files.directory(join30(this.root, "runs", id));
27606
+ return !!this.files.read(join32(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
27607
+ return this.files.directory(join32(this.root, "runs", id));
27127
27608
  }
27128
27609
  admit(commandId, epoch, r, effect) {
27129
27610
  this.current();
@@ -27152,7 +27633,7 @@ class Workflows {
27152
27633
  };
27153
27634
  if (sanitizeData(p, secrets) !== canonicalJson(p))
27154
27635
  throw new ContractError("forbidden");
27155
- const target3 = join30(this.root, "proposals", `${commandId}.json`);
27636
+ const target3 = join32(this.root, "proposals", `${commandId}.json`);
27156
27637
  const previous = this.files.read(target3, RECORD_BYTES2);
27157
27638
  if (previous) {
27158
27639
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -27203,7 +27684,7 @@ class Workflows {
27203
27684
  throw new ContractError("conflict");
27204
27685
  return { ...this.view(commandId), commandId };
27205
27686
  }
27206
- if (this.files.directory(dirname19(acceptedPath)))
27687
+ if (this.files.directory(dirname22(acceptedPath)))
27207
27688
  throw new ContractError("quarantine");
27208
27689
  let proposal;
27209
27690
  let target2;
@@ -27231,7 +27712,7 @@ class Workflows {
27231
27712
  this.capacity();
27232
27713
  } else
27233
27714
  throw new ContractError("invalid");
27234
- const run = {
27715
+ const run2 = {
27235
27716
  id: commandId,
27236
27717
  epoch,
27237
27718
  goal: proposal?.plan.goal ?? (request3.action === "research" ? request3.goal : ""),
@@ -27253,11 +27734,11 @@ class Workflows {
27253
27734
  };
27254
27735
  const abort = new AbortController;
27255
27736
  let begin;
27256
- const ready2 = new Promise((resolve11) => {
27257
- begin = resolve11;
27737
+ const ready2 = new Promise((resolve12) => {
27738
+ begin = resolve12;
27258
27739
  });
27259
27740
  const live2 = {
27260
- run,
27741
+ run: run2,
27261
27742
  abort,
27262
27743
  original: ready2.then(() => this.execute(live2, request3)),
27263
27744
  proposal,
@@ -27271,7 +27752,7 @@ class Workflows {
27271
27752
  this.o.owner.trackConversation(live2.original, () => abort.abort());
27272
27753
  try {
27273
27754
  this.write(acceptedPath, { epoch, request: request3 });
27274
- live2.file = this.write(this.path(commandId, "state.json"), run);
27755
+ live2.file = this.write(this.path(commandId, "state.json"), run2);
27275
27756
  } catch (e) {
27276
27757
  abort.abort();
27277
27758
  begin();
@@ -27281,7 +27762,7 @@ class Workflows {
27281
27762
  return {
27282
27763
  kind: "workflow",
27283
27764
  commandId,
27284
- response: { type: "run", run: structuredClone(run) }
27765
+ response: { type: "run", run: structuredClone(run2) }
27285
27766
  };
27286
27767
  }
27287
27768
  capacity() {
@@ -27463,7 +27944,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27463
27944
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, cwd, live2.abort.signal, {
27464
27945
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
27465
27946
  ownerSecrets: this.o.secrets(),
27466
- roots: roots?.length ? roots.map((p) => resolve10(cwd, p)) : [cwd],
27947
+ roots: roots?.length ? roots.map((p) => resolve11(cwd, p)) : [cwd],
27467
27948
  onLifecycle: (event) => {
27468
27949
  if (!step.timing)
27469
27950
  return;
@@ -27558,7 +28039,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27558
28039
  command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
27559
28040
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
27560
28041
  "-c",
27561
- `core.hooksPath=${join30(this.root, "empty-hooks")}`,
28042
+ `core.hooksPath=${join32(this.root, "empty-hooks")}`,
27562
28043
  "-c",
27563
28044
  "commit.gpgsign=false",
27564
28045
  "-c",
@@ -27795,9 +28276,9 @@ ${changed.map((p) => `- ${p}`).join(`
27795
28276
  publish(live2, cwd, plan, names3, changed) {
27796
28277
  for (const name of names3) {
27797
28278
  const file = safeWorkflowFile(cwd, name);
27798
- if (!safeDirectory(dirname19(file), true))
28279
+ if (!safeDirectory(dirname22(file), true))
27799
28280
  throw new ContractError("forbidden");
27800
- writeFileSync4(file, this.documentBody(live2, cwd, plan, name, changed), {
28281
+ writeFileSync5(file, this.documentBody(live2, cwd, plan, name, changed), {
27801
28282
  flag: name === ".cadence/project.md" ? "w" : "wx"
27802
28283
  });
27803
28284
  }
@@ -27805,17 +28286,17 @@ ${changed.map((p) => `- ${p}`).join(`
27805
28286
  worktreeHome(id) {
27806
28287
  if (nested(this.cwd, this.worktreeRoot))
27807
28288
  throw new ContractError("unsupported-context");
27808
- for (const directory of [dirname19(this.worktreeRoot), this.worktreeRoot]) {
28289
+ for (const directory of [dirname22(this.worktreeRoot), this.worktreeRoot]) {
27809
28290
  if (!safeDirectory(directory, true))
27810
28291
  throw new ContractError("forbidden");
27811
- const st = lstatSync20(directory);
28292
+ const st = lstatSync21(directory);
27812
28293
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
27813
28294
  throw new ContractError("forbidden");
27814
28295
  }
27815
- const home = join30(this.worktreeRoot, decodeId(id));
28296
+ const home = join32(this.worktreeRoot, decodeId(id));
27816
28297
  if (safeDirectory(home))
27817
28298
  throw new ContractError("conflict");
27818
- safeDirectory(join30(home, "tasks"), true);
28299
+ safeDirectory(join32(home, "tasks"), true);
27819
28300
  return home;
27820
28301
  }
27821
28302
  async merge(live2, candidate) {
@@ -27883,7 +28364,7 @@ ${result.output}`}`);
27883
28364
  } finally {
27884
28365
  this.closeStep(live2, step);
27885
28366
  }
27886
- for (const directory of [join30(home, "tasks"), home])
28367
+ for (const directory of [join32(home, "tasks"), home])
27887
28368
  try {
27888
28369
  rmdirSync(directory);
27889
28370
  } catch {}
@@ -27915,8 +28396,8 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
27915
28396
  throw new ContractError("invalid");
27916
28397
  const base = target2.head;
27917
28398
  const home = this.worktreeHome(live2.run.id);
27918
- const taskHome = join30(home, "tasks");
27919
- const integration = join30(home, "integration");
28399
+ const taskHome = join32(home, "tasks");
28400
+ const integration = join32(home, "integration");
27920
28401
  await this.gitStep(live2, this.cwd, "worktree-integration", (git) => git(["worktree", "add", "--detach", integration, base]));
27921
28402
  await assertWorktree(this.cwd, integration);
27922
28403
  await this.setup(live2, integration, plan);
@@ -27933,7 +28414,7 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
27933
28414
  live2.run.phase = "implementing";
27934
28415
  this.save(live2);
27935
28416
  const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
27936
- const cwd = join30(taskHome, task.id);
28417
+ const cwd = join32(taskHome, task.id);
27937
28418
  await this.gitStep(live2, this.cwd, `worktree-${task.id}`, (git) => git(["worktree", "add", "--detach", cwd, base]));
27938
28419
  const picks2 = workflowAncestors(plan.tasks, task.id).map((dep) => commits.get(dep.id)).filter((c) => !!c);
27939
28420
  if (picks2.length)
@@ -27998,9 +28479,9 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
27998
28479
  const file = safeWorkflowFile(this.cwd, name), before = documentBefore.get(name) ?? null;
27999
28480
  if (before !== pathIdentity(this.cwd, name))
28000
28481
  throw new WorkflowRefusal("conflict", `${name} changed during the run; the generated note was not written.`);
28001
- if (!safeDirectory(dirname19(file), true))
28482
+ if (!safeDirectory(dirname22(file), true))
28002
28483
  throw new ContractError("unavailable");
28003
- writeFileSync4(file, this.documentBody(live2, this.cwd, plan, name, [...live2.delivered].sort(), true), { flag: before ? "w" : "wx" });
28484
+ writeFileSync5(file, this.documentBody(live2, this.cwd, plan, name, [...live2.delivered].sort(), true), { flag: before ? "w" : "wx" });
28004
28485
  }
28005
28486
  if (!await this.checks(live2, this.cwd, plan))
28006
28487
  throw new Error("Local merge completed, but post-merge checks failed. No reset or rollback was attempted.");
@@ -28113,7 +28594,7 @@ class Workbench {
28113
28594
  });
28114
28595
  this.conversations.assertSettled();
28115
28596
  this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
28116
- this.projectRoot = join31(o.coordination.files.namespace, "workbench-projects-v1");
28597
+ this.projectRoot = join33(o.coordination.files.namespace, "workbench-projects-v1");
28117
28598
  }
28118
28599
  closeReads() {
28119
28600
  try {
@@ -28132,7 +28613,7 @@ class Workbench {
28132
28613
  const active2 = this.workflows.activeRuns();
28133
28614
  return {
28134
28615
  ...active2,
28135
- links: this.cadence.links(active2.runs.map((run) => run.id))
28616
+ links: this.cadence.links(active2.runs.map((run2) => run2.id))
28136
28617
  };
28137
28618
  }
28138
28619
  case "workflow-history":
@@ -28217,7 +28698,7 @@ class Workbench {
28217
28698
  for (let e = directory.readSync();e; e = directory.readSync()) {
28218
28699
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries2.length > 128)
28219
28700
  throw new ContractError("corrupt-selected");
28220
- const saved = files.read(join31(this.projectRoot, e.name));
28701
+ const saved = files.read(join33(this.projectRoot, e.name));
28221
28702
  if (!saved)
28222
28703
  throw new ContractError("corrupt-selected");
28223
28704
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -28286,7 +28767,7 @@ class Workbench {
28286
28767
  if (this.opening.size >= 64)
28287
28768
  throw new ContractError("capacity");
28288
28769
  const path = this.files.directory(request3.path);
28289
- const marker2 = join31(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
28770
+ const marker2 = join33(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
28290
28771
  const files = this.o.coordination.files;
28291
28772
  if (files.read(marker2))
28292
28773
  throw new ContractError("receipt-inconclusive");
@@ -28304,7 +28785,7 @@ class Workbench {
28304
28785
  }
28305
28786
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
28306
28787
  for (const root of [this.o.cwd, opened.path]) {
28307
- const entry = join31(this.projectRoot, `${hash2(root)}.json`);
28788
+ const entry = join33(this.projectRoot, `${hash2(root)}.json`);
28308
28789
  const saved = files.read(entry);
28309
28790
  if (!saved)
28310
28791
  files.create(entry, canonicalJson({ path: root }));
@@ -28334,7 +28815,7 @@ async function predecessorExited() {
28334
28815
  } catch {
28335
28816
  return;
28336
28817
  }
28337
- await new Promise((resolve11) => setTimeout(resolve11, 100));
28818
+ await new Promise((resolve12) => setTimeout(resolve12, 100));
28338
28819
  }
28339
28820
  }
28340
28821
  async function healBeforeStart(c) {
@@ -28372,8 +28853,8 @@ function legacy(store, budget, reader) {
28372
28853
  decodeId(entry.name);
28373
28854
  if (created.has(entry.name))
28374
28855
  continue;
28375
- const path = join32(store.tasks, entry.name, "task.json");
28376
- const size2 = lstatSync21(path).size;
28856
+ const path = join34(store.tasks, entry.name, "task.json");
28857
+ const size2 = lstatSync22(path).size;
28377
28858
  if (size2 > 128 * 1024)
28378
28859
  throw new ContractError("corrupt-selected");
28379
28860
  budget.reserve(size2);
@@ -28405,9 +28886,9 @@ var processLifetime = {
28405
28886
  const restarts = process.uptime() > 600 ? 0 : previous;
28406
28887
  if (!Number.isSafeInteger(restarts) || restarts >= SELF_RESTARTS)
28407
28888
  return;
28408
- const child = spawn4(process.execPath, [
28889
+ const child = spawn5(process.execPath, [
28409
28890
  ...process.execArgv,
28410
- fileURLToPath6(new URL("./service-host.mjs", import.meta.url))
28891
+ fileURLToPath7(new URL("./service-host.mjs", import.meta.url))
28411
28892
  ], {
28412
28893
  detached: true,
28413
28894
  stdio: ["pipe", "ignore", "ignore"],
@@ -28426,7 +28907,7 @@ var processLifetime = {
28426
28907
  }
28427
28908
  };
28428
28909
  async function createServiceHost(value, sourceBuild, lifetime) {
28429
- const embedded = "45f3666b0fc0d853e95e618b50156819f6282ce648e9703b876d9658ae15b78f";
28910
+ const embedded = "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65";
28430
28911
  if (embedded && sourceBuild)
28431
28912
  throw new ContractError("unsupported-context");
28432
28913
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -28510,8 +28991,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
28510
28991
  let timer;
28511
28992
  await Promise.race([
28512
28993
  owner?.idle(),
28513
- new Promise((resolve11) => {
28514
- timer = setTimeout(resolve11, FAULT_SETTLE_MS);
28994
+ new Promise((resolve12) => {
28995
+ timer = setTimeout(resolve12, FAULT_SETTLE_MS);
28515
28996
  })
28516
28997
  ]);
28517
28998
  clearTimeout(timer);
@@ -28702,6 +29183,7 @@ async function createServiceHost(value, sourceBuild, lifetime) {
28702
29183
  return {
28703
29184
  status: heldOwner.state === "idle" ? ready2 ? "alive" : "unavailable" : heldOwner.state,
28704
29185
  epoch: native.epoch,
29186
+ work: heldOwner.acceptedPending,
28705
29187
  actions: heldOwner.state === "idle" && !!workbench && ready2 && !!choice.snapshot().selected,
28706
29188
  ...operation === "diagnose" ? {
28707
29189
  recording: heldWriter.quarantined ? "quarantined" : "available",