@abelxiaoxing/cadence 2.0.27 → 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
@@ -4070,6 +4072,10 @@ function decodeCadenceConversation(v) {
4070
4072
  ...degraded ? { notice: text(o.notice, 1024, true) } : {}
4071
4073
  };
4072
4074
  }
4075
+ function decodeChatCursor(value) {
4076
+ const o = closed(value, ["id", "updatedAt"]);
4077
+ return { id: decodeId(o.id), updatedAt: integer(o.updatedAt, 0) };
4078
+ }
4073
4079
  var statuses = [
4074
4080
  "queued",
4075
4081
  "running",
@@ -4082,6 +4088,15 @@ var statuses = [
4082
4088
  function decodeWorkbenchRead(v) {
4083
4089
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4084
4090
  switch (kind) {
4091
+ case "conversation-transcript": {
4092
+ const o = closed(v, ["kind", "id", "turnId", "page"]);
4093
+ return {
4094
+ kind,
4095
+ id: decodeId(o.id),
4096
+ turnId: decodeId(o.turnId),
4097
+ page: integer(o.page, 0)
4098
+ };
4099
+ }
4085
4100
  case "cadence-conversation": {
4086
4101
  const o = closed(v, ["kind", "id"]);
4087
4102
  return { kind, id: decodeId(o.id) };
@@ -4107,7 +4122,20 @@ function decodeWorkbenchRead(v) {
4107
4122
  const o = closed(v, ["kind", "id"]);
4108
4123
  return { kind, id: decodeId(o.id) };
4109
4124
  }
4110
- case "conversations":
4125
+ case "conversations": {
4126
+ const after = Object.hasOwn(v, "after"), scan = Object.hasOwn(v, "scan");
4127
+ const o = closed(v, [
4128
+ "kind",
4129
+ ...after ? ["after"] : [],
4130
+ ...scan ? ["scan"] : []
4131
+ ]);
4132
+ return {
4133
+ kind,
4134
+ ...after ? { after: nullable(o.after, decodeChatCursor) } : {},
4135
+ ...scan ? { scan: decodeId(o.scan) } : {}
4136
+ };
4137
+ }
4138
+ case "conversation-active":
4111
4139
  case "projects":
4112
4140
  closed(v, ["kind"]);
4113
4141
  return { kind };
@@ -4246,13 +4274,20 @@ function decodeWorkbenchCommand(v) {
4246
4274
  function decodeChatTurn(v) {
4247
4275
  const keys2 = ["id", "epoch", "status", "items", "notice"];
4248
4276
  const current = v !== null && typeof v === "object" && Object.hasOwn(v, "omitted");
4249
- const o = closed(v, current ? [...keys2, "omitted"] : keys2);
4277
+ const paged = v !== null && typeof v === "object" && Object.hasOwn(v, "transcript");
4278
+ const o = closed(v, [
4279
+ ...keys2,
4280
+ ...current ? ["omitted"] : [],
4281
+ ...paged ? ["transcript"] : []
4282
+ ]);
4283
+ const transcript = paged ? closed(o.transcript, ["pages"]) : null;
4250
4284
  const omitted = current ? closed(o.omitted, ["thinking", "media", "other"]) : null;
4251
4285
  return {
4252
4286
  id: decodeId(o.id),
4253
4287
  epoch: decodeId(o.epoch),
4254
4288
  status: oneOf(o.status, statuses),
4255
4289
  notice: text(o.notice, 1024),
4290
+ ...transcript ? { transcript: { pages: integer(transcript.pages, 0) } } : {},
4256
4291
  omitted: {
4257
4292
  thinking: omitted ? bool(omitted.thinking) : false,
4258
4293
  media: omitted ? bool(omitted.media) : false,
@@ -4293,6 +4328,13 @@ function decodeChatSummary(v) {
4293
4328
  function decodeWorkbenchResult(v) {
4294
4329
  canonicalJson(v, 512 * 1024);
4295
4330
  const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4331
+ if (k === "conversation-transcript") {
4332
+ const o2 = closed(v, ["kind", "conversationId", "page", "turn"]);
4333
+ const turn = decodeChatTurn(o2.turn), page = integer(o2.page, 0);
4334
+ if (!turn.transcript || page >= turn.transcript.pages)
4335
+ throw new ContractError("invalid");
4336
+ return { kind: k, conversationId: decodeId(o2.conversationId), page, turn };
4337
+ }
4296
4338
  if (k === "workflow-transcript") {
4297
4339
  const o2 = closed(v, ["kind", "runId", "stepId", "turn"]);
4298
4340
  return {
@@ -4378,9 +4420,26 @@ function decodeWorkbenchResult(v) {
4378
4420
  conversationId: nullable(o2.conversationId, decodeId)
4379
4421
  };
4380
4422
  }
4381
- if (kind === "conversations") {
4423
+ if (kind === "conversations-progress") {
4424
+ const o2 = closed(v, ["kind", "after", "scan"]);
4425
+ return {
4426
+ kind,
4427
+ after: nullable(o2.after, decodeChatCursor),
4428
+ scan: decodeId(o2.scan)
4429
+ };
4430
+ }
4431
+ if (kind === "conversation-active") {
4382
4432
  const o2 = closed(v, ["kind", "entries"]);
4383
- return { kind, entries: list(o2.entries, 200, decodeChatSummary) };
4433
+ return { kind, entries: list(o2.entries, 8, decodeChatSummary) };
4434
+ }
4435
+ if (kind === "conversations") {
4436
+ const paged = Object.hasOwn(v, "next");
4437
+ const o2 = closed(v, ["kind", "entries", ...paged ? ["next"] : []]);
4438
+ return {
4439
+ kind,
4440
+ entries: list(o2.entries, 200, decodeChatSummary),
4441
+ ...paged ? { next: nullable(o2.next, decodeChatCursor) } : {}
4442
+ };
4384
4443
  }
4385
4444
  if (kind === "conversation") {
4386
4445
  const o2 = closed(v, ["kind", "summary", "turns", "before"]);
@@ -5541,11 +5600,167 @@ class HttpAuthentication {
5541
5600
  }
5542
5601
  }
5543
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
+
5544
5759
  // src/service/cli.ts
5545
- import { spawn } from "node:child_process";
5760
+ import { spawn as spawn2 } from "node:child_process";
5546
5761
  import { request } from "node:http";
5547
- import { homedir as homedir3 } from "node:os";
5548
- 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";
5549
5764
  import { fileURLToPath as fileURLToPath2 } from "node:url";
5550
5765
 
5551
5766
  // src/sdk-network.ts
@@ -5683,29 +5898,103 @@ function sdkNetworkEnvironment(ambient, scoped) {
5683
5898
  return { env, redactionLiterals: route ? [route] : [] };
5684
5899
  }
5685
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
+
5686
5975
  // src/service/coordination.ts
5687
5976
  import { randomBytes as randomBytes2, randomUUID as randomUUID4 } from "node:crypto";
5688
5977
  import { opendirSync } from "node:fs";
5689
5978
  import { hostname as hostname3 } from "node:os";
5690
- 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";
5691
5980
 
5692
5981
  // src/service/checkout-lock.ts
5693
5982
  import { randomUUID as randomUUID3 } from "node:crypto";
5694
5983
  import {
5695
5984
  closeSync as closeSync3,
5696
5985
  fsyncSync as fsyncSync2,
5697
- lstatSync as lstatSync5,
5986
+ lstatSync as lstatSync6,
5698
5987
  openSync as openSync3,
5699
- realpathSync as realpathSync3,
5988
+ realpathSync as realpathSync4,
5700
5989
  unlinkSync as unlinkSync2,
5701
- writeFileSync as writeFileSync2
5990
+ writeFileSync as writeFileSync3
5702
5991
  } from "node:fs";
5703
5992
  import { hostname as hostname2 } from "node:os";
5704
- import { dirname as dirname5, join as join6 } from "node:path";
5993
+ import { dirname as dirname6, join as join7 } from "node:path";
5705
5994
 
5706
5995
  // src/service/liveness.ts
5707
- import { spawnSync as spawnSync2 } from "node:child_process";
5708
- import { readFileSync } from "node:fs";
5996
+ import { spawnSync as spawnSync3 } from "node:child_process";
5997
+ import { readFileSync as readFileSync2 } from "node:fs";
5709
5998
  import { hostname, uptime } from "node:os";
5710
5999
  var LEGACY_BOOT_MARGIN_MS = 10 * 60 * 1000;
5711
6000
  var REUSE_SLACK_MS = 5000;
@@ -5717,11 +6006,11 @@ function bootId() {
5717
6006
  cachedBoot = null;
5718
6007
  try {
5719
6008
  if (process.platform === "linux") {
5720
- const id = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
6009
+ const id = readFileSync2("/proc/sys/kernel/random/boot_id", "utf8").trim();
5721
6010
  if (/^[0-9a-f-]{36}$/.test(id))
5722
6011
  cachedBoot = id;
5723
6012
  } else if (process.platform === "darwin") {
5724
- const r = spawnSync2("sysctl", ["-n", "kern.bootsessionuuid"], {
6013
+ const r = spawnSync3("sysctl", ["-n", "kern.bootsessionuuid"], {
5725
6014
  encoding: "utf8",
5726
6015
  timeout: 2000
5727
6016
  });
@@ -5737,7 +6026,7 @@ function bootId() {
5737
6026
  function bootTime() {
5738
6027
  if (process.platform === "linux")
5739
6028
  try {
5740
- const line = /^btime (\d+)$/m.exec(readFileSync("/proc/stat", "utf8"));
6029
+ const line = /^btime (\d+)$/m.exec(readFileSync2("/proc/stat", "utf8"));
5741
6030
  if (line)
5742
6031
  return Number(line[1]) * 1000;
5743
6032
  } catch {}
@@ -5745,7 +6034,7 @@ function bootTime() {
5745
6034
  }
5746
6035
  function linuxStat(pid) {
5747
6036
  try {
5748
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
6037
+ const stat = readFileSync2(`/proc/${pid}/stat`, "utf8");
5749
6038
  return stat.slice(stat.lastIndexOf(")") + 2).trim().split(" ");
5750
6039
  } catch {
5751
6040
  return null;
@@ -5760,7 +6049,7 @@ function processStart(pid) {
5760
6049
  return ticks && /^\d+$/.test(ticks) ? `ticks:${ticks}` : null;
5761
6050
  }
5762
6051
  if (process.platform === "darwin") {
5763
- const r = spawnSync2("ps", ["-o", "lstart=", "-p", String(pid)], {
6052
+ const r = spawnSync3("ps", ["-o", "lstart=", "-p", String(pid)], {
5764
6053
  encoding: "utf8",
5765
6054
  timeout: 2000,
5766
6055
  env: { ...process.env, LC_ALL: "C" }
@@ -5869,14 +6158,14 @@ async function stopProcessGroup(pgid, waitMs = 5000) {
5869
6158
  send("SIGTERM");
5870
6159
  const deadline = Date.now() + waitMs;
5871
6160
  while (Date.now() < deadline) {
5872
- await new Promise((resolve3) => setTimeout(resolve3, 100));
6161
+ await new Promise((resolve4) => setTimeout(resolve4, 100));
5873
6162
  if (gone())
5874
6163
  return true;
5875
6164
  if (Date.now() > deadline - waitMs / 2)
5876
6165
  send("SIGKILL");
5877
6166
  }
5878
6167
  send("SIGKILL");
5879
- await new Promise((resolve3) => setTimeout(resolve3, 200));
6168
+ await new Promise((resolve4) => setTimeout(resolve4, 200));
5880
6169
  return gone();
5881
6170
  }
5882
6171
 
@@ -5885,7 +6174,7 @@ class CheckoutStore {
5885
6174
  root;
5886
6175
  privateRoot;
5887
6176
  constructor(root, stateHome = defaultStateHome()) {
5888
- this.root = realpathSync3(root);
6177
+ this.root = realpathSync4(root);
5889
6178
  if (privateWorkspace(this.root, stateHome))
5890
6179
  throw new Error("Private state cannot be a workspace");
5891
6180
  this.privateRoot = privateRootFor(this.root, stateHome);
@@ -5893,14 +6182,14 @@ class CheckoutStore {
5893
6182
  throw new Error("Private state home must be outside the working copy");
5894
6183
  }
5895
6184
  get lockPath() {
5896
- return join6(this.privateRoot, "checkout.lock");
6185
+ return join7(this.privateRoot, "checkout.lock");
5897
6186
  }
5898
6187
  inspectPrivate() {
5899
- const namespace = dirname5(this.privateRoot);
6188
+ const namespace = dirname6(this.privateRoot);
5900
6189
  for (const path of [namespace, this.privateRoot]) {
5901
6190
  if (!safeDirectory(path))
5902
6191
  continue;
5903
- const st = lstatSync5(path);
6192
+ const st = lstatSync6(path);
5904
6193
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
5905
6194
  throw new Error("Private state permissions refused");
5906
6195
  }
@@ -5910,7 +6199,7 @@ class CheckoutStore {
5910
6199
  if (!safeDirectory(this.privateRoot))
5911
6200
  return;
5912
6201
  try {
5913
- const st = lstatSync5(path);
6202
+ const st = lstatSync6(path);
5914
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()))
5915
6204
  throw new Error("Unsafe private state file");
5916
6205
  } catch (error) {
@@ -5949,7 +6238,7 @@ class CheckoutStore {
5949
6238
  throw new Error("Checkout busy or unresolved lock; inspect and explicitly recover only a dead owner");
5950
6239
  }
5951
6240
  try {
5952
- writeFileSync2(fd, JSON.stringify(lock));
6241
+ writeFileSync3(fd, JSON.stringify(lock));
5953
6242
  fsyncSync2(fd);
5954
6243
  } finally {
5955
6244
  closeSync3(fd);
@@ -5985,7 +6274,7 @@ var registrationKeys = [
5985
6274
  var reservationKeys = registrationKeys.filter((k) => !["schema", "phase", "checkoutToken"].includes(k));
5986
6275
  function pathValue(value) {
5987
6276
  const path = text(value, 4096, true);
5988
- if (!isAbsolute4(path))
6277
+ if (!isAbsolute5(path))
5989
6278
  refused();
5990
6279
  return path;
5991
6280
  }
@@ -6042,7 +6331,7 @@ function decodeRegistration(value) {
6042
6331
  function rootsOverlap(a, b) {
6043
6332
  const within = (x, y) => {
6044
6333
  const r = relative3(x, y);
6045
- return r === "" || r !== ".." && !r.startsWith(`..${sep3}`) && !isAbsolute4(r);
6334
+ return r === "" || r !== ".." && !r.startsWith(`..${sep4}`) && !isAbsolute5(r);
6046
6335
  };
6047
6336
  return within(a, b) || within(b, a);
6048
6337
  }
@@ -6091,10 +6380,10 @@ class ServiceCoordination {
6091
6380
  stateHome;
6092
6381
  constructor(workspace, stateHome) {
6093
6382
  this.project = workspace === null ? undefined : new CheckoutStore(resolveWorkspace(workspace).root, stateHome);
6094
- this.stateHome = this.project ? dirname6(dirname6(this.project.privateRoot)) : canonicalAmbientRoot(stateHome ?? defaultStateHome());
6095
- 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");
6096
6385
  this.files = new PrivateFiles(namespace);
6097
- this.registryDirectory = join7(namespace, "service-registry-v1");
6386
+ this.registryDirectory = join8(namespace, "service-registry-v1");
6098
6387
  }
6099
6388
  get store() {
6100
6389
  if (!this.project)
@@ -6102,13 +6391,13 @@ class ServiceCoordination {
6102
6391
  return this.project;
6103
6392
  }
6104
6393
  get directory() {
6105
- return join7(this.store.privateRoot, "service-v1");
6394
+ return join8(this.store.privateRoot, "service-v1");
6106
6395
  }
6107
6396
  path(name) {
6108
- return join7(this.directory, name);
6397
+ return join8(this.directory, name);
6109
6398
  }
6110
6399
  registryPath(name) {
6111
- return join7(this.registryDirectory, name);
6400
+ return join8(this.registryDirectory, name);
6112
6401
  }
6113
6402
  registry() {
6114
6403
  if (!this.files.directory(this.registryDirectory))
@@ -6155,14 +6444,14 @@ class ServiceCoordination {
6155
6444
  "conversation-workflows-v1",
6156
6445
  "workflows-v1"
6157
6446
  ]);
6158
- this.files.directory(join7(directory, "history-v2"), false, walks);
6447
+ this.files.directory(join8(directory, "history-v2"), false, walks);
6159
6448
  }
6160
6449
  selected(directory = this.directory, root = this.store.root, stoppedOnly = false) {
6161
6450
  const walks = new DirectoryWalks;
6162
6451
  if (!this.files.directory(directory, false, walks))
6163
6452
  return;
6164
6453
  this.assertNamespace(walks, directory);
6165
- const path = (name) => join7(directory, name);
6454
+ const path = (name) => join8(directory, name);
6166
6455
  const manifest = this.files.read(path("format.json"), undefined, walks);
6167
6456
  const config = this.files.read(path("config.json"), undefined, walks);
6168
6457
  if (!manifest || !config)
@@ -6184,7 +6473,7 @@ class ServiceCoordination {
6184
6473
  const registration = this.files.read(path("registration.json"), undefined, walks);
6185
6474
  const owner = this.files.read(path("owner.lock"), undefined, walks);
6186
6475
  const capability = this.files.read(path("local-capability.json"), undefined, walks);
6187
- 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);
6188
6477
  const value = registration ? decodeRegistration(json(registration)) : undefined;
6189
6478
  if (value && (value.root !== root || value.stateHome !== this.stateHome || value.configIdentity !== config.identity || !endpointMatches(c.endpoint, value.endpoint)))
6190
6479
  refused();
@@ -6533,37 +6822,7 @@ import { isatty } from "node:tty";
6533
6822
  import { randomBytes as randomBytes3, randomUUID as randomUUID5 } from "node:crypto";
6534
6823
  import { opendirSync as opendirSync2 } from "node:fs";
6535
6824
  import { hostname as hostname4 } from "node:os";
6536
- import { join as join8, resolve as resolve3 } from "node:path";
6537
-
6538
- // src/service/contracts/gateway.ts
6539
- function decodeProjectEntry(value) {
6540
- const o = closed(value, ["id", "path", "cwd", "epoch"]);
6541
- return {
6542
- id: decodeHash(o.id),
6543
- path: text(o.path, 4096, true),
6544
- cwd: text(o.cwd, 4096, true),
6545
- epoch: decodeId(o.epoch)
6546
- };
6547
- }
6548
- var RECOVERY_SCOPES = ["registry", "workbench", "project"];
6549
- var RECOVERY_CAUSES = [
6550
- "reboot",
6551
- "crash",
6552
- "restart",
6553
- "storage"
6554
- ];
6555
- var RECOVERY_ACTIONS = [
6556
- "released-locks",
6557
- "stopped-workers",
6558
- "stopped-owner",
6559
- "continued-history",
6560
- "archived-history",
6561
- "archived-state",
6562
- "rebuilt-registry",
6563
- "removed-temporaries"
6564
- ];
6565
-
6566
- // src/service/gateway-store.ts
6825
+ import { join as join9, resolve as resolve4 } from "node:path";
6567
6826
  function decodeGatewayInput(value) {
6568
6827
  const o = closed(value, [
6569
6828
  "kind",
@@ -6574,7 +6833,7 @@ function decodeGatewayInput(value) {
6574
6833
  ]);
6575
6834
  const absolute = (v) => {
6576
6835
  const p = text(v, 4096, true);
6577
- if (resolve3(p) !== p)
6836
+ if (resolve4(p) !== p)
6578
6837
  throw new ContractError("invalid");
6579
6838
  return p;
6580
6839
  };
@@ -6588,7 +6847,7 @@ function decodeGatewayInput(value) {
6588
6847
  }
6589
6848
  function decodeGatewayProject(value) {
6590
6849
  const project = decodeProjectEntry(value);
6591
- if (resolve3(project.path) !== project.path || resolve3(project.cwd) !== project.cwd)
6850
+ if (resolve4(project.path) !== project.path || resolve4(project.cwd) !== project.cwd)
6592
6851
  throw new ContractError("corrupt-selected");
6593
6852
  return project;
6594
6853
  }
@@ -6648,11 +6907,11 @@ class GatewayStore {
6648
6907
  constructor(serverConfig, stateHome = defaultStateHome()) {
6649
6908
  this.serverConfig = serverConfig;
6650
6909
  this.stateHome = canonicalAmbientRoot(stateHome);
6651
- this.files = new PrivateFiles(join8(this.stateHome, "cadence-assistant-v1"));
6652
- 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)));
6653
6912
  }
6654
6913
  path(name) {
6655
- return join8(this.directory, name);
6914
+ return join9(this.directory, name);
6656
6915
  }
6657
6916
  read() {
6658
6917
  const file = this.files.read(this.path("gateway.json"));
@@ -6751,7 +7010,7 @@ class GatewayStore {
6751
7010
  for (let entry = stream.readSync();entry; entry = stream.readSync()) {
6752
7011
  if (!entry.isFile() || !/^[a-f0-9]{64}\.json$/.test(entry.name) || out.length >= 128)
6753
7012
  throw new ContractError("corrupt-selected");
6754
- const file = this.files.read(join8(directory, entry.name));
7013
+ const file = this.files.read(join9(directory, entry.name));
6755
7014
  if (!file)
6756
7015
  throw new ContractError("corrupt-selected");
6757
7016
  const project = decodeGatewayProject(json(file));
@@ -6797,12 +7056,12 @@ class GatewayStore {
6797
7056
  // src/service/recovery-log.ts
6798
7057
  import { randomUUID as randomUUID6 } from "node:crypto";
6799
7058
  import {
6800
- lstatSync as lstatSync6,
7059
+ lstatSync as lstatSync7,
6801
7060
  opendirSync as opendirSync3,
6802
- renameSync as renameSync2,
6803
- rmSync
7061
+ renameSync as renameSync3,
7062
+ rmSync as rmSync2
6804
7063
  } from "node:fs";
6805
- import { basename, join as join9, relative as relative4 } from "node:path";
7064
+ import { basename, join as join10, relative as relative4 } from "node:path";
6806
7065
  var RECOVERY_NOTICE_MS = 7 * 24 * 60 * 60 * 1000;
6807
7066
  var RECOVERY_EVENTS = 50;
6808
7067
  var RECOVERY_ARCHIVE_MS = 30 * 24 * 60 * 60 * 1000;
@@ -6855,7 +7114,7 @@ function entries(path, maximum = 4096) {
6855
7114
  function size(path, limit = { left: 1e5 }) {
6856
7115
  let st;
6857
7116
  try {
6858
- st = lstatSync6(path);
7117
+ st = lstatSync7(path);
6859
7118
  } catch {
6860
7119
  return 0;
6861
7120
  }
@@ -6865,7 +7124,7 @@ function size(path, limit = { left: 1e5 }) {
6865
7124
  return st.size;
6866
7125
  let total = 0;
6867
7126
  for (const name of entries(path, 1e5))
6868
- total += size(join9(path, name), limit);
7127
+ total += size(join10(path, name), limit);
6869
7128
  return total;
6870
7129
  }
6871
7130
 
@@ -6875,12 +7134,12 @@ class RecoveryLog {
6875
7134
  archiveDirectory;
6876
7135
  constructor(files) {
6877
7136
  this.files = files;
6878
- this.logDirectory = join9(files.namespace, "recovery-log-v1");
6879
- 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");
6880
7139
  }
6881
7140
  archive() {
6882
7141
  const name = `${Date.now()}-${randomUUID6()}`;
6883
- const directory = join9(this.archiveDirectory, name);
7142
+ const directory = join10(this.archiveDirectory, name);
6884
7143
  let used = false;
6885
7144
  return {
6886
7145
  name,
@@ -6889,8 +7148,8 @@ class RecoveryLog {
6889
7148
  if (!rel || rel.startsWith(".."))
6890
7149
  throw new ContractError("forbidden");
6891
7150
  this.files.directory(directory, true);
6892
- const target = join9(directory, as ?? rel.split(/[\\/]/).join("--"));
6893
- retryWindowsFileOperation(() => renameSync2(path, target));
7151
+ const target = join10(directory, as ?? rel.split(/[\\/]/).join("--"));
7152
+ retryWindowsFileOperation(() => renameSync3(path, target));
6894
7153
  used = true;
6895
7154
  },
6896
7155
  used: () => used
@@ -6918,7 +7177,7 @@ class RecoveryLog {
6918
7177
  };
6919
7178
  decodeRecoveryEvent(value);
6920
7179
  try {
6921
- 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);
6922
7181
  this.prune();
6923
7182
  } catch {}
6924
7183
  return value;
@@ -6927,7 +7186,7 @@ class RecoveryLog {
6927
7186
  for (const name of entries(this.logDirectory).reverse()) {
6928
7187
  if (!/^[0-9]{13}-[0-9a-f-]{36}\.json$/.test(name))
6929
7188
  continue;
6930
- const path = join9(this.logDirectory, name);
7189
+ const path = join10(this.logDirectory, name);
6931
7190
  const snapshot = this.files.read(path, EVENT_BYTES);
6932
7191
  if (!snapshot)
6933
7192
  return;
@@ -6947,7 +7206,7 @@ class RecoveryLog {
6947
7206
  if (!/^[0-9]{13}-[0-9a-f-]{36}\.json$/.test(name))
6948
7207
  continue;
6949
7208
  try {
6950
- const file = this.files.read(join9(this.logDirectory, name), EVENT_BYTES);
7209
+ const file = this.files.read(join10(this.logDirectory, name), EVENT_BYTES);
6951
7210
  if (file)
6952
7211
  out.push(decodeRecoveryEvent(json(file, EVENT_BYTES)));
6953
7212
  } catch {}
@@ -6957,13 +7216,13 @@ class RecoveryLog {
6957
7216
  prune(now = Date.now()) {
6958
7217
  const names2 = entries(this.logDirectory);
6959
7218
  for (const name of names2.slice(0, Math.max(0, names2.length - RECOVERY_EVENTS)))
6960
- rmSync(join9(this.logDirectory, name), { force: true });
7219
+ rmSync2(join10(this.logDirectory, name), { force: true });
6961
7220
  const archived = entries(this.archiveDirectory).filter((name) => /^[0-9]{13}-[0-9a-f-]{36}$/.test(name));
6962
7221
  const kept = [];
6963
7222
  for (const name of archived) {
6964
- const path = join9(this.archiveDirectory, name);
7223
+ const path = join10(this.archiveDirectory, name);
6965
7224
  if (now - Number(name.slice(0, 13)) > RECOVERY_ARCHIVE_MS)
6966
- rmSync(path, { recursive: true, force: true });
7225
+ rmSync2(path, { recursive: true, force: true });
6967
7226
  else
6968
7227
  kept.push({ name, bytes: size(path) });
6969
7228
  }
@@ -6971,7 +7230,7 @@ class RecoveryLog {
6971
7230
  for (const entry of kept) {
6972
7231
  if (total <= RECOVERY_ARCHIVE_BYTES)
6973
7232
  break;
6974
- rmSync(join9(this.archiveDirectory, entry.name), {
7233
+ rmSync2(join10(this.archiveDirectory, entry.name), {
6975
7234
  recursive: true,
6976
7235
  force: true
6977
7236
  });
@@ -6994,23 +7253,23 @@ class RecoveryLog {
6994
7253
  const names2 = entries(this.archiveDirectory);
6995
7254
  return {
6996
7255
  entries: names2.length,
6997
- 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)
6998
7257
  };
6999
7258
  }
7000
7259
  }
7001
7260
  function strayTemporaries(directory) {
7002
- 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));
7003
7262
  }
7004
7263
 
7005
7264
  // src/service/self-heal.ts
7006
7265
  import { createHash as createHash5, randomUUID as randomUUID7 } from "node:crypto";
7007
- import { lstatSync as lstatSync7, opendirSync as opendirSync4 } from "node:fs";
7266
+ import { lstatSync as lstatSync8, opendirSync as opendirSync4 } from "node:fs";
7008
7267
  import { hostname as hostname5 } from "node:os";
7009
- import { join as join11 } from "node:path";
7268
+ import { join as join12 } from "node:path";
7010
7269
 
7011
7270
  // src/service/process-ledger.ts
7012
- import { rmSync as rmSync2 } from "node:fs";
7013
- import { join as join10 } from "node:path";
7271
+ import { rmSync as rmSync3 } from "node:fs";
7272
+ import { join as join11 } from "node:path";
7014
7273
  var LEDGER_BYTES = 64 * 1024;
7015
7274
  var LEDGER_WORKERS = 512;
7016
7275
  function decode2(value) {
@@ -7035,10 +7294,10 @@ class ProcessLedger {
7035
7294
  directory;
7036
7295
  constructor(files) {
7037
7296
  this.files = files;
7038
- this.directory = join10(files.namespace, "process-ledger-v1");
7297
+ this.directory = join11(files.namespace, "process-ledger-v1");
7039
7298
  }
7040
7299
  path(epoch) {
7041
- return join10(this.directory, `${decodeId(epoch)}.json`);
7300
+ return join11(this.directory, `${decodeId(epoch)}.json`);
7042
7301
  }
7043
7302
  file(epoch) {
7044
7303
  try {
@@ -7057,7 +7316,7 @@ class ProcessLedger {
7057
7316
  }
7058
7317
  remove(epoch) {
7059
7318
  try {
7060
- rmSync2(this.path(epoch), { force: true });
7319
+ rmSync3(this.path(epoch), { force: true });
7061
7320
  } catch {}
7062
7321
  }
7063
7322
  open(epoch) {
@@ -7232,7 +7491,7 @@ async function stopOwnerProcess(pid) {
7232
7491
  return gone();
7233
7492
  }
7234
7493
  for (let n = 0;n < 50; n++) {
7235
- await new Promise((resolve4) => setTimeout(resolve4, 100));
7494
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
7236
7495
  if (gone())
7237
7496
  return true;
7238
7497
  }
@@ -7240,7 +7499,7 @@ async function stopOwnerProcess(pid) {
7240
7499
  process.kill(pid, "SIGKILL");
7241
7500
  } catch {}
7242
7501
  for (let n = 0;n < 20; n++) {
7243
- await new Promise((resolve4) => setTimeout(resolve4, 100));
7502
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
7244
7503
  if (gone())
7245
7504
  return true;
7246
7505
  }
@@ -7257,7 +7516,7 @@ class RegistryHealer {
7257
7516
  this.ledger = new ProcessLedger(c.files);
7258
7517
  }
7259
7518
  path(name) {
7260
- return join11(this.c.registryDirectory, name);
7519
+ return join12(this.c.registryDirectory, name);
7261
7520
  }
7262
7521
  async heal(options = {}) {
7263
7522
  const lockPath = this.path("registry.lock");
@@ -7268,7 +7527,7 @@ class RegistryHealer {
7268
7527
  lock = undefined;
7269
7528
  const age = (() => {
7270
7529
  try {
7271
- return Date.now() - lstatSync7(lockPath).mtimeMs;
7530
+ return Date.now() - lstatSync8(lockPath).mtimeMs;
7272
7531
  } catch {
7273
7532
  return 0;
7274
7533
  }
@@ -7312,7 +7571,7 @@ class RegistryHealer {
7312
7571
  pid: mark?.pid ?? null
7313
7572
  };
7314
7573
  if (holder.state === "live") {
7315
- await new Promise((resolve4) => setTimeout(resolve4, 250));
7574
+ await new Promise((resolve5) => setTimeout(resolve5, 250));
7316
7575
  if (!this.c.files.read(lockPath))
7317
7576
  return { status: "clean" };
7318
7577
  return { status: "live" };
@@ -7422,14 +7681,14 @@ function liveReservations(c) {
7422
7681
  for (let e = dir.readSync();e; e = dir.readSync()) {
7423
7682
  if (!/^[a-f0-9]{64}$/.test(e.name))
7424
7683
  continue;
7425
- const service = join11(c.files.namespace, e.name, "service-v1");
7426
- 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);
7427
7686
  if (!registration2 || registration2 === "unreadable")
7428
7687
  continue;
7429
7688
  const r = registration2.value;
7430
7689
  if (!r || r.phase === "stopped")
7431
7690
  continue;
7432
- const owner = readFile(c.files, join11(service, "owner.lock"), decodeOwnerLock);
7691
+ const owner = readFile(c.files, join12(service, "owner.lock"), decodeOwnerLock);
7433
7692
  const mark = owner && owner !== "unreadable" && owner.value ? owner.value : r;
7434
7693
  if (holderState(mark, stampTime(registration2.snapshot.stamp)).state !== "live")
7435
7694
  continue;
@@ -7450,20 +7709,20 @@ function liveReservations(c) {
7450
7709
  return out;
7451
7710
  }
7452
7711
  function projectFiles(c, root) {
7453
- 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"));
7454
7713
  return {
7455
7714
  root,
7456
7715
  privateRoot,
7457
- service: join11(privateRoot, "service-v1"),
7458
- checkoutPath: join11(privateRoot, "checkout.lock")
7716
+ service: join12(privateRoot, "service-v1"),
7717
+ checkoutPath: join12(privateRoot, "checkout.lock")
7459
7718
  };
7460
7719
  }
7461
7720
  function snapshotProject(c, p) {
7462
7721
  const s = { temporaries: [] };
7463
- s.registration = readFile(c.files, join11(p.service, "registration.json"), decodeRegistrationLenient);
7464
- 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);
7465
7724
  try {
7466
- s.capability = c.files.read(join11(p.service, "local-capability.json"));
7725
+ s.capability = c.files.read(join12(p.service, "local-capability.json"));
7467
7726
  } catch {
7468
7727
  s.capability = "unreadable";
7469
7728
  }
@@ -7478,7 +7737,7 @@ function snapshotProject(c, p) {
7478
7737
  } catch {}
7479
7738
  s.temporaries = [
7480
7739
  ...strayTemporaries(p.service),
7481
- ...strayTemporaries(join11(p.service, "history-v2"))
7740
+ ...strayTemporaries(join12(p.service, "history-v2"))
7482
7741
  ];
7483
7742
  return s;
7484
7743
  }
@@ -7591,8 +7850,8 @@ function metadataDamaged(c, p) {
7591
7850
  return false;
7592
7851
  }
7593
7852
  try {
7594
- const format = c.files.read(join11(p.service, "format.json"));
7595
- 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"));
7596
7855
  if (!format || !config)
7597
7856
  return true;
7598
7857
  const f = closed(json(format), [
@@ -7604,10 +7863,10 @@ function metadataDamaged(c, p) {
7604
7863
  if (f.schema !== "cadence-service-format/1" || f.root !== p.root || f.stateHome !== c.stateHome || f.configIdentity !== config.identity)
7605
7864
  return true;
7606
7865
  const selected = decodeOwnerConfig(json(config));
7607
- const host = c.files.read(join11(p.service, "host-config.json"));
7866
+ const host = c.files.read(join12(p.service, "host-config.json"));
7608
7867
  if (host && host.identity !== selected.policyIdentity)
7609
7868
  return true;
7610
- const registration2 = c.files.read(join11(p.service, "registration.json"));
7869
+ const registration2 = c.files.read(join12(p.service, "registration.json"));
7611
7870
  if (registration2) {
7612
7871
  const r = decodeRegistration(json(registration2));
7613
7872
  if (r.root !== p.root || r.stateHome !== c.stateHome || r.configIdentity !== config.identity)
@@ -7630,7 +7889,7 @@ function reclaim(c, p, expected, archive) {
7630
7889
  mutate();
7631
7890
  const registration2 = s.registration;
7632
7891
  if (registration2 === "unreadable")
7633
- archive.keep(join11(p.service, "registration.json"));
7892
+ archive.keep(join12(p.service, "registration.json"));
7634
7893
  else if (registration2) {
7635
7894
  if (!registration2.value)
7636
7895
  archive.keep(registration2.path);
@@ -7638,7 +7897,7 @@ function reclaim(c, p, expected, archive) {
7638
7897
  c.files.replace(registration2.path, registration2.snapshot, encoded({ ...registration2.value, phase: "stopped" }));
7639
7898
  }
7640
7899
  if (s.row)
7641
- c.files.replace(join11(c.registryDirectory, "roots.json"), view.snapshot, encoded({
7900
+ c.files.replace(join12(c.registryDirectory, "roots.json"), view.snapshot, encoded({
7642
7901
  ...view.value,
7643
7902
  entries: view.value.entries.filter((row) => row.root !== p.root)
7644
7903
  }), 1024 * 1024);
@@ -7651,8 +7910,8 @@ function reclaim(c, p, expected, archive) {
7651
7910
  }
7652
7911
  c.files.remove(path, "snapshot" in value ? value.snapshot : value, maximum);
7653
7912
  };
7654
- drop(join11(p.service, "local-capability.json"), s.capability);
7655
- 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);
7656
7915
  drop(p.checkoutPath, s.checkout, 8192);
7657
7916
  });
7658
7917
  }
@@ -7819,7 +8078,7 @@ async function confirm(question) {
7819
8078
  return false;
7820
8079
  const rl = createInterface({ input: process.stdin, output: process.stderr });
7821
8080
  try {
7822
- 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));
7823
8082
  return /^y(es)?$/i.test(answer.trim());
7824
8083
  } finally {
7825
8084
  rl.close();
@@ -7861,12 +8120,12 @@ async function healProjectForStart(c, responsive) {
7861
8120
  }
7862
8121
 
7863
8122
  // src/service/runtime.ts
7864
- import { homedir as homedir2 } from "node:os";
7865
- 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";
7866
8125
  var STARTUP_INPUT_BYTES = 16 * 1024;
7867
8126
  function absolute(value) {
7868
8127
  const result = text(value, 4096, true);
7869
- if (!isAbsolute5(result))
8128
+ if (!isAbsolute6(result))
7870
8129
  throw new ContractError("invalid");
7871
8130
  return result;
7872
8131
  }
@@ -7956,7 +8215,7 @@ function selectStart(options, ambient) {
7956
8215
  throw new ContractError("invalid");
7957
8216
  let fromFile;
7958
8217
  if (options.config) {
7959
- const path = resolve4(options.config), f = new PrivateFiles(dirname7(path));
8218
+ const path = resolve5(options.config), f = new PrivateFiles(dirname8(path));
7960
8219
  const bytes = f.read(path);
7961
8220
  if (!bytes)
7962
8221
  throw new ContractError("corrupt-selected");
@@ -7971,11 +8230,11 @@ function selectStart(options, ambient) {
7971
8230
  port: options.port ?? 17423,
7972
8231
  proxy: null
7973
8232
  },
7974
- 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")),
7975
8234
  tokenSource: options.tokenFile ? "file" : env ? "environment" : "generated",
7976
- tokenFile: options.tokenFile ? resolve4(options.tokenFile) : null
8235
+ tokenFile: options.tokenFile ? resolve5(options.tokenFile) : null
7977
8236
  });
7978
- 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;
7979
8238
  let selected = base;
7980
8239
  if (server) {
7981
8240
  if (options.tokenFile !== undefined)
@@ -7988,7 +8247,7 @@ function selectStart(options, ambient) {
7988
8247
  tokenFile: server
7989
8248
  });
7990
8249
  }
7991
- 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)
7992
8251
  throw new ContractError("conflict");
7993
8252
  return {
7994
8253
  workspace: workspace.root,
@@ -8055,13 +8314,175 @@ function decodeStartupReport(value) {
8055
8314
  };
8056
8315
  }
8057
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
+
8058
8479
  // src/service/cli.ts
8059
8480
  function nativeCall(c, operation, reveal = false, controlBody) {
8060
8481
  const access = c.localAccess();
8061
8482
  const url = new URL(`${access.endpoint}/local/v1/admin/${operation}`);
8062
8483
  const write2 = !["status", "diagnose"].includes(operation);
8063
8484
  const body = write2 ? JSON.stringify(controlBody ?? (reveal ? { reveal: true } : {})) : undefined;
8064
- return new Promise((resolve6, reject) => {
8485
+ return new Promise((resolve7, reject) => {
8065
8486
  let timer;
8066
8487
  const fail = () => {
8067
8488
  clearTimeout(timer);
@@ -8102,7 +8523,7 @@ function nativeCall(c, operation, reveal = false, controlBody) {
8102
8523
  throw new ContractError("stale");
8103
8524
  }
8104
8525
  clearTimeout(timer);
8105
- resolve6(reply.value);
8526
+ resolve7(reply.value);
8106
8527
  } catch {
8107
8528
  fail();
8108
8529
  }
@@ -8117,7 +8538,7 @@ function nativeCall(c, operation, reveal = false, controlBody) {
8117
8538
  req.end(body);
8118
8539
  });
8119
8540
  }
8120
- var pause = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
8541
+ var pause = (ms) => new Promise((resolve7) => setTimeout(resolve7, ms));
8121
8542
  async function serviceStatus(c, diagnose = false) {
8122
8543
  const registryLock = c.registryLockDiagnostic?.();
8123
8544
  if (registryLock)
@@ -8217,10 +8638,10 @@ function startupGuidance(result, input) {
8217
8638
  return `Pi's agent directory ${agent} must be an existing real directory (not a symlink) owned by you.
8218
8639
  `;
8219
8640
  case "pi-auth":
8220
- 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.
8221
8642
  `;
8222
8643
  case "pi-models":
8223
- 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.
8224
8645
  `;
8225
8646
  case "pi-runtime":
8226
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.
@@ -8280,7 +8701,7 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8280
8701
  throw new ContractError("oversize");
8281
8702
  if (!sameNetwork(network, networkSnapshot(process.env)))
8282
8703
  throw new ContractError("stale");
8283
- const child = spawn(process.execPath, [
8704
+ const child = spawn2(process.execPath, [
8284
8705
  ...env.NODE_USE_ENV_PROXY === "1" ? ["--use-env-proxy"] : [],
8285
8706
  fileURLToPath2(hostUrl)
8286
8707
  ], {
@@ -8291,18 +8712,18 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8291
8712
  stdio: ["pipe", "pipe", "ignore"]
8292
8713
  });
8293
8714
  let completed = false;
8294
- const closure = new Promise((resolve6) => child.once("close", (code2, signal) => {
8715
+ const closure = new Promise((resolve7) => child.once("close", (code2, signal) => {
8295
8716
  completed = true;
8296
8717
  if (foreground && (code2 !== 0 || signal !== null))
8297
8718
  process.exitCode = 1;
8298
- resolve6();
8719
+ resolve7();
8299
8720
  }));
8300
- const startup = new Promise((resolve6) => {
8721
+ const startup = new Promise((resolve7) => {
8301
8722
  let bytes = "", resolved = false;
8302
8723
  const finish = (value) => {
8303
8724
  if (!resolved) {
8304
8725
  resolved = true;
8305
- resolve6(value);
8726
+ resolve7(value);
8306
8727
  }
8307
8728
  };
8308
8729
  child.on("error", () => finish({ status: "unconfirmed" }));
@@ -8342,8 +8763,8 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8342
8763
  let timer;
8343
8764
  const result = await Promise.race([
8344
8765
  startup,
8345
- new Promise((resolve6) => {
8346
- timer = setTimeout(() => resolve6({ status: "unconfirmed" }), LIMITS.startWaitMs);
8766
+ new Promise((resolve7) => {
8767
+ timer = setTimeout(() => resolve7({ status: "unconfirmed" }), LIMITS.startWaitMs);
8347
8768
  })
8348
8769
  ]);
8349
8770
  clearTimeout(timer);
@@ -8368,12 +8789,34 @@ async function launchHost(input, c, foreground, hostUrl, cwd, env, network) {
8368
8789
  }
8369
8790
  async function privateLink(workspace, stateHome, config) {
8370
8791
  try {
8371
- 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"]);
8372
8793
  return text(value.link, 4096, true);
8373
8794
  } catch {
8374
8795
  return;
8375
8796
  }
8376
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
+ };
8377
8820
  class ProjectOpenRefusal extends ContractError {
8378
8821
  noOwner;
8379
8822
  constructor(noOwner, code2 = "unavailable") {
@@ -8570,14 +9013,14 @@ Content-Length: 0\r
8570
9013
  async listen() {
8571
9014
  if (this.origin || this.stopped)
8572
9015
  throw new ContractError("conflict");
8573
- await new Promise((resolve6, reject) => {
9016
+ await new Promise((resolve7, reject) => {
8574
9017
  const failed = () => {
8575
9018
  this.server.off("listening", ready);
8576
9019
  reject(new ContractError("unavailable"));
8577
9020
  };
8578
9021
  const ready = () => {
8579
9022
  this.server.off("error", failed);
8580
- resolve6();
9023
+ resolve7();
8581
9024
  };
8582
9025
  this.server.once("error", failed);
8583
9026
  this.server.once("listening", ready);
@@ -8607,13 +9050,13 @@ Content-Length: 0\r
8607
9050
  close() {
8608
9051
  if (this.closePromise)
8609
9052
  return this.closePromise;
8610
- let resolve6;
9053
+ let resolve7;
8611
9054
  let reject;
8612
9055
  this.closePromise = new Promise((yes, no) => {
8613
- resolve6 = yes;
9056
+ resolve7 = yes;
8614
9057
  reject = no;
8615
9058
  });
8616
- this.closeTransport().then(resolve6, () => reject(new ContractError("unavailable")));
9059
+ this.closeTransport().then(resolve7, () => reject(new ContractError("unavailable")));
8617
9060
  return this.closePromise;
8618
9061
  }
8619
9062
  async closeTransport() {
@@ -8625,18 +9068,18 @@ Content-Length: 0\r
8625
9068
  request2.abort();
8626
9069
  for (const attachment of [...this.attachments.values()])
8627
9070
  this.detach(attachment);
8628
- const closedSockets = [...this.sockets].map((socket) => new Promise((resolve6) => {
9071
+ const closedSockets = [...this.sockets].map((socket) => new Promise((resolve7) => {
8629
9072
  if (socket.closed)
8630
- resolve6();
9073
+ resolve7();
8631
9074
  else {
8632
- socket.once("close", () => resolve6());
9075
+ socket.once("close", () => resolve7());
8633
9076
  socket.destroy();
8634
9077
  }
8635
9078
  }));
8636
- const listener = new Promise((resolve6, reject) => {
8637
- 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());
8638
9081
  });
8639
- const upgrades = new Promise((resolve6) => this.wss.close(() => resolve6()));
9082
+ const upgrades = new Promise((resolve7) => this.wss.close(() => resolve7()));
8640
9083
  await Promise.all([listener, upgrades, ...closedSockets]);
8641
9084
  }
8642
9085
  attachment(caller) {
@@ -9044,7 +9487,7 @@ Content-Length: 0\r
9044
9487
  if (signal.aborted || res.destroyed)
9045
9488
  unavailable();
9046
9489
  const chunk = data.subarray(offset, offset + LIMITS.detailPageBytes);
9047
- await new Promise((resolve6, reject) => {
9490
+ await new Promise((resolve7, reject) => {
9048
9491
  const stop = () => {
9049
9492
  res.destroy();
9050
9493
  reject(new ContractError("unavailable"));
@@ -9052,7 +9495,7 @@ Content-Length: 0\r
9052
9495
  signal.addEventListener("abort", stop, { once: true });
9053
9496
  res.write(chunk, (error) => {
9054
9497
  signal.removeEventListener("abort", stop);
9055
- error ? reject(new ContractError("unavailable")) : resolve6();
9498
+ error ? reject(new ContractError("unavailable")) : resolve7();
9056
9499
  });
9057
9500
  });
9058
9501
  activity();
@@ -9274,16 +9717,16 @@ Content-Length: 0\r
9274
9717
  // src/service/workbench-files.ts
9275
9718
  import {
9276
9719
  closeSync as closeSync4,
9277
- constants as constants3,
9720
+ constants as constants4,
9278
9721
  fstatSync as fstatSync3,
9279
- lstatSync as lstatSync8,
9722
+ lstatSync as lstatSync9,
9280
9723
  opendirSync as opendirSync5,
9281
9724
  openSync as openSync4,
9282
9725
  readSync as readSync3,
9283
- realpathSync as realpathSync4
9726
+ realpathSync as realpathSync6
9284
9727
  } from "node:fs";
9285
- import { homedir as homedir4 } from "node:os";
9286
- 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";
9287
9730
 
9288
9731
  // src/worker-redaction.mjs
9289
9732
  var marker = "[redacted]";
@@ -9742,7 +10185,7 @@ class DetailSanitizer {
9742
10185
  // src/service/workbench-files.ts
9743
10186
  function inside(root, path) {
9744
10187
  const r = relative5(root, path);
9745
- return r === "" || !isAbsolute6(r) && r !== ".." && !r.startsWith(`..${sep4}`);
10188
+ return r === "" || !isAbsolute7(r) && r !== ".." && !r.startsWith(`..${sep5}`);
9746
10189
  }
9747
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);
9748
10191
 
@@ -9752,39 +10195,39 @@ class WorkbenchFiles {
9752
10195
  excluded;
9753
10196
  constructor(root, excluded, secrets) {
9754
10197
  this.secrets = secrets;
9755
- this.root = realpathSync4(root);
10198
+ this.root = realpathSync6(root);
9756
10199
  this.excluded = excluded.flatMap((path) => [
9757
- resolve6(path),
10200
+ resolve7(path),
9758
10201
  canonicalAmbientRoot(path)
9759
10202
  ]);
9760
10203
  }
9761
10204
  allowed(path) {
9762
10205
  if (path.split(/[\\/]/).some(sensitive2) || this.excluded.some((root) => inside(root, path)))
9763
10206
  throw new ContractError("forbidden");
9764
- const stat = lstatSync8(path);
10207
+ const stat = lstatSync9(path);
9765
10208
  if (stat.isSymbolicLink() || stat.isFile() && stat.nlink !== 1 || process.platform !== "win32" && process.getuid && stat.uid !== process.getuid())
9766
10209
  throw new ContractError("forbidden");
9767
10210
  }
9768
10211
  directory(path) {
9769
- if (!isAbsolute6(path) || !safeDirectory(path))
10212
+ if (!isAbsolute7(path) || !safeDirectory(path))
9770
10213
  throw new ContractError("invalid");
9771
- const canonical = realpathSync4(path);
10214
+ const canonical = realpathSync6(path);
9772
10215
  this.allowed(canonical);
9773
10216
  return canonical;
9774
10217
  }
9775
10218
  selected(path) {
9776
- if (isAbsolute6(path) || path.split(/[\\/]/).some((part) => part === ".." || sensitive2(part)))
10219
+ if (isAbsolute7(path) || path.split(/[\\/]/).some((part) => part === ".." || sensitive2(part)))
9777
10220
  throw new ContractError("forbidden");
9778
- const target = resolve6(this.root, path);
9779
- if (!inside(this.root, target) || !safeDirectory(dirname9(target)))
10221
+ const target = resolve7(this.root, path);
10222
+ if (!inside(this.root, target) || !safeDirectory(dirname11(target)))
9780
10223
  throw new ContractError("forbidden");
9781
10224
  this.allowed(target);
9782
- if (lstatSync8(target).isSymbolicLink())
10225
+ if (lstatSync9(target).isSymbolicLink())
9783
10226
  throw new ContractError("forbidden");
9784
10227
  return target;
9785
10228
  }
9786
10229
  browsed(path) {
9787
- 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;
9788
10231
  try {
9789
10232
  return this.directory(full);
9790
10233
  } catch (error) {
@@ -9807,13 +10250,13 @@ class WorkbenchFiles {
9807
10250
  }
9808
10251
  if (sensitive2(entry.name) || entry.isSymbolicLink() || !entry.isFile() && !entry.isDirectory() || directories && !entry.isDirectory())
9809
10252
  continue;
9810
- const absolute2 = join14(selected, entry.name);
10253
+ const absolute2 = join16(selected, entry.name);
9811
10254
  try {
9812
10255
  this.allowed(absolute2);
9813
10256
  } catch {
9814
10257
  continue;
9815
10258
  }
9816
- const wire = directories ? absolute2 : relative5(this.root, absolute2).split(sep4).join("/");
10259
+ const wire = directories ? absolute2 : relative5(this.root, absolute2).split(sep5).join("/");
9817
10260
  if (sanitizeText(wire, this.secrets()) !== wire)
9818
10261
  continue;
9819
10262
  if (entries2.length >= 200) {
@@ -9830,20 +10273,20 @@ class WorkbenchFiles {
9830
10273
  dir.closeSync();
9831
10274
  }
9832
10275
  entries2.sort((a, b) => Number(b.directory) - Number(a.directory) || a.name.localeCompare(b.name));
9833
- const parent = dirname9(selected);
10276
+ const parent = dirname11(selected);
9834
10277
  return {
9835
10278
  kind: directories ? "directories" : "files",
9836
10279
  path: directories ? selected : path,
9837
- 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("/"),
9838
10281
  entries: entries2,
9839
10282
  limited
9840
10283
  };
9841
10284
  }
9842
10285
  read(path) {
9843
- const selected = this.selected(path), before = lstatSync8(selected);
10286
+ const selected = this.selected(path), before = lstatSync9(selected);
9844
10287
  if (!before.isFile())
9845
10288
  throw new ContractError("forbidden");
9846
- const fd = openSync4(selected, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
10289
+ const fd = openSync4(selected, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
9847
10290
  try {
9848
10291
  const opened = fstatSync3(fd);
9849
10292
  if (!opened.isFile() || opened.nlink !== 1 || before.dev !== opened.dev || before.ino !== opened.ino)
@@ -9856,7 +10299,7 @@ class WorkbenchFiles {
9856
10299
  break;
9857
10300
  at += n;
9858
10301
  }
9859
- const after = fstatSync3(fd), current = lstatSync8(selected);
10302
+ const after = fstatSync3(fd), current = lstatSync9(selected);
9860
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)
9861
10304
  throw new ContractError("stale");
9862
10305
  const decoded2 = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, at), { stream: at < opened.size });
@@ -9890,7 +10333,7 @@ async function createGateway(value, hostUrl, source) {
9890
10333
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
9891
10334
  const web = loadWebAssets(source?.webDirectory);
9892
10335
  const build2 = {
9893
- contractHash: "b6935a8daa09f70de094136c18d8e3588fdd34fc24b9a8fe95e465de11ddae8d",
10336
+ contractHash: "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65",
9894
10337
  assets: {
9895
10338
  sourceHash: web.manifest.sourceHash,
9896
10339
  contractHash: web.manifest.contractHash,
@@ -9942,11 +10385,11 @@ Content-Length: 0\r
9942
10385
  \r
9943
10386
  `));
9944
10387
  server.on("checkContinue", (_req, res) => reply(res, 400, { kind: "error", error: publicError("invalid") }));
9945
- await new Promise((resolve7, reject) => {
10388
+ await new Promise((resolve8, reject) => {
9946
10389
  server.once("error", reject);
9947
10390
  server.listen(input.policy.port, input.policy.host, () => {
9948
10391
  server.off("error", reject);
9949
- resolve7();
10392
+ resolve8();
9950
10393
  });
9951
10394
  });
9952
10395
  const address = server.address();
@@ -9992,12 +10435,90 @@ Content-Length: 0\r
9992
10435
  server.close();
9993
10436
  throw error;
9994
10437
  }
9995
- 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());
9996
10439
  const assert = () => {
9997
10440
  store.assert();
9998
10441
  if (!accepting)
9999
10442
  throw new ContractError("quarantine");
10000
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
+ }
10001
10522
  async function open(path, id, epoch) {
10002
10523
  assert();
10003
10524
  if (epoch !== auth.epoch)
@@ -10080,14 +10601,14 @@ Content-Length: 0\r
10080
10601
  const secret = link.searchParams.get("token");
10081
10602
  if (!secret)
10082
10603
  throw new ContractError("unavailable");
10083
- const cookie = await new Promise((resolve7, reject) => {
10604
+ const cookie = await new Promise((resolve8, reject) => {
10084
10605
  const req = request2(`${local.endpoint}/?token=${encodeURIComponent(secret)}`, { agent: false }, (res) => {
10085
10606
  const cookie2 = res.headers["set-cookie"];
10086
10607
  res.resume();
10087
10608
  if (res.statusCode !== 303 || cookie2?.length !== 1)
10088
10609
  reject(new ContractError("unavailable"));
10089
10610
  else
10090
- resolve7(cookie2[0].split(";")[0]);
10611
+ resolve8(cookie2[0].split(";")[0]);
10091
10612
  });
10092
10613
  req.setTimeout(2000, () => req.destroy(new Error));
10093
10614
  req.on("error", () => reject(new ContractError("unavailable")));
@@ -10253,20 +10774,20 @@ Content-Length: 0\r
10253
10774
  const project = target(raw);
10254
10775
  const caller = auth.authenticate(boundary, randomUUID9(), !project && req.method === "POST");
10255
10776
  if (project) {
10256
- const route = readRoute(project.tail, req.method ?? "");
10257
- if (!route)
10777
+ const route2 = readRoute(project.tail, req.method ?? "");
10778
+ if (!route2)
10258
10779
  throw new ContractError("invalid");
10259
10780
  const attachment = boundary.headers.get("x-cadence-attachment");
10260
10781
  if (attachment && attachments.get(attachment) !== project.id || req.method === "POST" && !attachment)
10261
10782
  throw new ContractError("stale");
10262
- if (route.operation === "session" && !attachment && attachments.size >= 2048)
10783
+ if (route2.operation === "session" && !attachment && attachments.size >= 2048)
10263
10784
  throw new ContractError("capacity");
10264
10785
  if (req.method === "POST" && boundary.headers.get("origin") !== boundary.origin)
10265
10786
  throw new ContractError("forbidden");
10266
10787
  if (req.headers["content-encoding"] || req.headers["transfer-encoding"] || Number(req.headers["content-length"] ?? 0) > LIMITS.controlBytes)
10267
10788
  throw new ContractError("oversize");
10268
10789
  let commandBody;
10269
- if (route.operation === "workbenchCommand") {
10790
+ if (route2.operation === "workbenchCommand") {
10270
10791
  const command = decodeWorkbenchCommand(await body(req, LIMITS.controlBytes));
10271
10792
  if (command.kind === "open-project")
10272
10793
  throw new ContractError("forbidden");
@@ -10292,7 +10813,7 @@ Content-Length: 0\r
10292
10813
  }
10293
10814
  if (commandBody !== undefined)
10294
10815
  headers["content-length"] = String(Buffer.byteLength(commandBody));
10295
- await new Promise((resolve7) => {
10816
+ await new Promise((resolve8) => {
10296
10817
  const upstream = request2(`${b.endpoint}${project.tail}`, { method: req.method, headers, agent: false }, (incoming) => {
10297
10818
  try {
10298
10819
  auth.current(caller);
@@ -10300,7 +10821,7 @@ Content-Length: 0\r
10300
10821
  close();
10301
10822
  return;
10302
10823
  }
10303
- if (route.operation === "session" && incoming.statusCode === 200) {
10824
+ if (route2.operation === "session" && incoming.statusCode === 200) {
10304
10825
  try {
10305
10826
  attachments.set(decodeId(incoming.headers["x-cadence-attachment"]), project.id);
10306
10827
  } catch {
@@ -10308,7 +10829,7 @@ Content-Length: 0\r
10308
10829
  return;
10309
10830
  }
10310
10831
  }
10311
- if (route.operation === "detach" && incoming.statusCode === 200 && attachment)
10832
+ if (route2.operation === "detach" && incoming.statusCode === 200 && attachment)
10312
10833
  attachments.delete(attachment);
10313
10834
  res.statusCode = incoming.statusCode ?? 502;
10314
10835
  for (const key of [
@@ -10328,7 +10849,7 @@ Content-Length: 0\r
10328
10849
  relays.delete(close);
10329
10850
  res.off("close", close);
10330
10851
  res.off("finish", done);
10331
- resolve7();
10852
+ resolve8();
10332
10853
  }
10333
10854
  function close() {
10334
10855
  upstream.destroy();
@@ -10360,7 +10881,7 @@ Content-Length: 0\r
10360
10881
  kind: "workbench",
10361
10882
  epoch: auth.epoch,
10362
10883
  csrf: auth.csrf,
10363
- home: homedir5(),
10884
+ home: homedir6(),
10364
10885
  projects: store.projects(),
10365
10886
  recoveries: new RecoveryLog(store.files).notices(),
10366
10887
  build: build2
@@ -10371,10 +10892,27 @@ Content-Length: 0\r
10371
10892
  reply(res, 200, files.list(text(url.searchParams.get("path"), 4096, true), true));
10372
10893
  return;
10373
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
+ }
10374
10914
  if (raw === "/workbench/v1/open" && req.method === "POST") {
10375
- const clientBuild = decodeClientBuild(parseWireJson(boundary.headers.get("x-cadence-build") ?? "null", 1024));
10376
- if (clientBuild.kind !== "browser" || !compatibleBuild(build2, clientBuild))
10377
- throw new ContractError("unsupported-context");
10915
+ browserBuild(boundary);
10378
10916
  const o = closed(await body(req), ["commandId", "path", "epoch"]);
10379
10917
  const id = decodeId(o.commandId), path = text(o.path, 4096, true), epoch = decodeId(o.epoch);
10380
10918
  auth.current(caller);
@@ -10474,14 +11012,14 @@ Content-Length: 0\r
10474
11012
  }
10475
11013
 
10476
11014
  // src/service/host.ts
10477
- import { spawn as spawn4 } from "node:child_process";
10478
- import { lstatSync as lstatSync20, opendirSync as opendirSync14 } from "node:fs";
10479
- import { join as join32 } from "node:path";
10480
- 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";
10481
11019
 
10482
11020
  // src/agent-registry.ts
10483
11021
  import { createHash as createHash7 } from "node:crypto";
10484
- import { fileURLToPath as fileURLToPath3 } from "node:url";
11022
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
10485
11023
  var AGENT_FILES = [
10486
11024
  "design-explorer.md",
10487
11025
  "implementation-worker.md",
@@ -10489,7 +11027,7 @@ var AGENT_FILES = [
10489
11027
  ];
10490
11028
  function loadAgentDefinitions() {
10491
11029
  return AGENT_FILES.map((fileName) => {
10492
- const path = fileURLToPath3(new URL(`../agents/${fileName}`, import.meta.url));
11030
+ const path = fileURLToPath4(new URL(`../agents/${fileName}`, import.meta.url));
10493
11031
  const data = readBounded(path, 32768, true);
10494
11032
  if (!data)
10495
11033
  throw new Error("Missing package Agent");
@@ -10505,18 +11043,18 @@ function loadAgentDefinitions() {
10505
11043
  }
10506
11044
 
10507
11045
  // src/cadence-preferences.ts
10508
- import { realpathSync as realpathSync5 } from "node:fs";
10509
- 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";
10510
11048
  function agentNamespace(agentDir) {
10511
- let at = resolve7(agentDir);
11049
+ let at = resolve8(agentDir);
10512
11050
  const missing2 = [];
10513
11051
  for (;; ) {
10514
11052
  try {
10515
- return join15(realpathSync5(at), ...missing2.reverse());
11053
+ return join17(realpathSync7(at), ...missing2.reverse());
10516
11054
  } catch {
10517
- const parent = dirname10(at);
11055
+ const parent = dirname13(at);
10518
11056
  if (parent === at)
10519
- return resolve7(agentDir);
11057
+ return resolve8(agentDir);
10520
11058
  missing2.push(basename2(at));
10521
11059
  at = parent;
10522
11060
  }
@@ -10528,7 +11066,7 @@ class CadencePreferences {
10528
11066
  files;
10529
11067
  constructor(agentDir) {
10530
11068
  const namespace = agentNamespace(agentDir);
10531
- this.path = join15(namespace, "cadence", "settings.json");
11069
+ this.path = join17(namespace, "cadence", "settings.json");
10532
11070
  this.files = new PrivateFiles(namespace, false);
10533
11071
  }
10534
11072
  read() {
@@ -10576,12 +11114,12 @@ class CadencePreferences {
10576
11114
  function scopedSnapshot(source, scope) {
10577
11115
  if (scope.kind === "task" || source.scope.kind === "child")
10578
11116
  return;
10579
- 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))
10580
11118
  return;
10581
11119
  return decodeSnapshot({
10582
11120
  ...source,
10583
11121
  scope,
10584
- 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),
10585
11123
  horizon: {
10586
11124
  ...source.horizon,
10587
11125
  historicalRuns: { ...source.horizon.historicalRuns, scope }
@@ -10821,40 +11359,40 @@ class HistoryLive {
10821
11359
 
10822
11360
  // src/history/navigation.ts
10823
11361
  import { createHash as createHash11 } from "node:crypto";
10824
- import { lstatSync as lstatSync12 } from "node:fs";
10825
- 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";
10826
11364
 
10827
11365
  // src/history/index-tree.ts
10828
- import { lstatSync as lstatSync10 } from "node:fs";
10829
- import { join as join16 } from "node:path";
11366
+ import { lstatSync as lstatSync11 } from "node:fs";
11367
+ import { join as join18 } from "node:path";
10830
11368
 
10831
11369
  // src/history/read-io.ts
10832
11370
  import { createHash as createHash8 } from "node:crypto";
10833
11371
  import {
10834
11372
  closeSync as closeSync5,
10835
- constants as constants4,
11373
+ constants as constants5,
10836
11374
  fstatSync as fstatSync4,
10837
- lstatSync as lstatSync9,
11375
+ lstatSync as lstatSync10,
10838
11376
  openSync as openSync5,
10839
11377
  readSync as readSync4
10840
11378
  } from "node:fs";
10841
- import { dirname as dirname11 } from "node:path";
11379
+ import { dirname as dirname14 } from "node:path";
10842
11380
  function bad() {
10843
11381
  throw new ContractError("corrupt-selected");
10844
11382
  }
10845
11383
  var stamp2 = (s) => [s.dev, s.ino, s.size, s.mode, s.uid, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
10846
11384
  function selected(files, path, read, walks) {
10847
- if (!files.files.directory(dirname11(path), false, walks))
11385
+ if (!files.files.directory(dirname14(path), false, walks))
10848
11386
  bad();
10849
- const before = lstatSync9(path);
11387
+ const before = lstatSync10(path);
10850
11388
  if (!before.isFile() || before.nlink !== 1 || process.platform !== "win32" && (before.mode & 63 || process.getuid && before.uid !== process.getuid()))
10851
11389
  bad();
10852
- const fd = openSync5(path, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
11390
+ const fd = openSync5(path, constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0));
10853
11391
  try {
10854
11392
  if (stamp2(fstatSync4(fd)) !== stamp2(before))
10855
11393
  bad();
10856
11394
  const result = read(fd, before.size, stamp2(before));
10857
- if (stamp2(fstatSync4(fd)) !== stamp2(before) || stamp2(lstatSync9(path)) !== stamp2(before))
11395
+ if (stamp2(fstatSync4(fd)) !== stamp2(before) || stamp2(lstatSync10(path)) !== stamp2(before))
10858
11396
  bad();
10859
11397
  return result;
10860
11398
  } finally {
@@ -10955,7 +11493,7 @@ class IndexTree {
10955
11493
  this.files = files;
10956
11494
  }
10957
11495
  path(id) {
10958
- 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`);
10959
11497
  }
10960
11498
  load(id, budget, unit) {
10961
11499
  decodeHash(id);
@@ -10970,7 +11508,7 @@ class IndexTree {
10970
11508
  if (budget) {
10971
11509
  const path = this.path(id);
10972
11510
  budget.reserve(0);
10973
- const selected2 = lstatSync10(path).size;
11511
+ const selected2 = lstatSync11(path).size;
10974
11512
  if (selected2 > MAX_NODE)
10975
11513
  throw new ContractError("receipt-inconclusive");
10976
11514
  bytes = readRange(this.files, path, 0, selected2, budget);
@@ -11090,16 +11628,16 @@ class IndexTree {
11090
11628
  import { createHash as createHash10, randomBytes as randomBytes4, randomUUID as randomUUID10 } from "node:crypto";
11091
11629
  import {
11092
11630
  closeSync as closeSync6,
11093
- constants as constants5,
11631
+ constants as constants6,
11094
11632
  fstatSync as fstatSync5,
11095
11633
  fsyncSync as fsyncSync3,
11096
- lstatSync as lstatSync11,
11634
+ lstatSync as lstatSync12,
11097
11635
  opendirSync as opendirSync7,
11098
11636
  openSync as openSync6,
11099
11637
  statfsSync
11100
11638
  } from "node:fs";
11101
11639
  import { open } from "node:fs/promises";
11102
- import { dirname as dirname12, join as join17 } from "node:path";
11640
+ import { dirname as dirname15, join as join19 } from "node:path";
11103
11641
 
11104
11642
  // src/history/admission.ts
11105
11643
  function decodeRunAdmission(value) {
@@ -11584,7 +12122,7 @@ async function retryStalled(read) {
11584
12122
  } catch (error) {
11585
12123
  if (!(error instanceof StalledQuantum) || retry >= STALL_RETRIES)
11586
12124
  throw error;
11587
- await new Promise((resolve8) => setImmediate(resolve8));
12125
+ await new Promise((resolve9) => setImmediate(resolve9));
11588
12126
  }
11589
12127
  }
11590
12128
  }
@@ -11605,14 +12143,14 @@ class HistoryFiles {
11605
12143
  this.coordination = coordination;
11606
12144
  this.format = format;
11607
12145
  this.formatSnapshot = formatSnapshot;
11608
- this.directory = join17(coordination.directory, "history-v2");
12146
+ this.directory = join19(coordination.directory, "history-v2");
11609
12147
  this.files = coordination.files;
11610
12148
  }
11611
12149
  static open(coordination) {
11612
- const dir = join17(coordination.directory, "history-v2");
12150
+ const dir = join19(coordination.directory, "history-v2");
11613
12151
  if (!coordination.files.directory(dir))
11614
12152
  return;
11615
- const file = coordination.files.read(join17(dir, "format.json"));
12153
+ const file = coordination.files.read(join19(dir, "format.json"));
11616
12154
  if (!file)
11617
12155
  corrupt();
11618
12156
  const format = decodeFormat(json(file));
@@ -11628,7 +12166,7 @@ class HistoryFiles {
11628
12166
  existing.assertWritable();
11629
12167
  return existing;
11630
12168
  }
11631
- const dir = join17(c.directory, "history-v2");
12169
+ const dir = join19(c.directory, "history-v2");
11632
12170
  const format = {
11633
12171
  schema: FORMAT,
11634
12172
  storeId: randomUUID10(),
@@ -11638,19 +12176,19 @@ class HistoryFiles {
11638
12176
  c.files.directory(dir, true);
11639
12177
  for (const name of ["commands", "ledger", "runs", "indexes"]) {
11640
12178
  lease.assert();
11641
- c.files.directory(join17(dir, name), true);
12179
+ c.files.directory(join19(dir, name), true);
11642
12180
  }
11643
12181
  lease.assert();
11644
- const keyPath = join17(dir, "read-proof-key.json");
12182
+ const keyPath = join19(dir, "read-proof-key.json");
11645
12183
  c.files.create(keyPath, encoded({
11646
12184
  schema: "cadence-history-read-key/1",
11647
12185
  storeId: format.storeId,
11648
12186
  key: randomBytes4(32).toString("base64url")
11649
12187
  }));
11650
12188
  lease.assert();
11651
- const snapshot = c.files.create(join17(dir, "format.json"), encoded(format));
12189
+ const snapshot = c.files.create(join19(dir, "format.json"), encoded(format));
11652
12190
  const result = new HistoryFiles(c, format, snapshot);
11653
- result.syncParents(join17(dir, "format.json"));
12191
+ result.syncParents(join19(dir, "format.json"));
11654
12192
  result.assertWritable();
11655
12193
  return result;
11656
12194
  }
@@ -11685,7 +12223,7 @@ class HistoryFiles {
11685
12223
  throw new ContractError("quarantine");
11686
12224
  }
11687
12225
  assertFormat() {
11688
- this.files.assert(join17(this.directory, "format.json"), this.formatSnapshot);
12226
+ this.files.assert(join19(this.directory, "format.json"), this.formatSnapshot);
11689
12227
  }
11690
12228
  readProofMaterial(budget) {
11691
12229
  if (this.format.schema !== FORMAT)
@@ -11694,7 +12232,7 @@ class HistoryFiles {
11694
12232
  this.assertReadFormat(budget);
11695
12233
  else
11696
12234
  this.assertFormat();
11697
- 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);
11698
12236
  if (!selected2 || this.proofSnapshot && (selected2.identity !== this.proofSnapshot.identity || selected2.stamp !== this.proofSnapshot.stamp))
11699
12237
  corrupt();
11700
12238
  try {
@@ -11722,17 +12260,17 @@ class HistoryFiles {
11722
12260
  return;
11723
12261
  }
11724
12262
  this.assertFormat();
11725
- 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);
11726
12264
  }
11727
12265
  segmentPath(segment) {
11728
- return join17(this.directory, "ledger", `${String(segment).padStart(12, "0")}.jsonl`);
12266
+ return join19(this.directory, "ledger", `${String(segment).padStart(12, "0")}.jsonl`);
11729
12267
  }
11730
12268
  artifactPath(ref) {
11731
- 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`);
11732
12270
  }
11733
12271
  admissionPath(runId) {
11734
12272
  decodeId(runId);
11735
- return join17(this.directory, "runs", runId, "admission.json");
12273
+ return join19(this.directory, "runs", runId, "admission.json");
11736
12274
  }
11737
12275
  writeAdmission(lease, input) {
11738
12276
  lease.assert();
@@ -11746,7 +12284,7 @@ class HistoryFiles {
11746
12284
  return this.files.read(path, maximum);
11747
12285
  let size2;
11748
12286
  try {
11749
- size2 = lstatSync11(path).size;
12287
+ size2 = lstatSync12(path).size;
11750
12288
  } catch {
11751
12289
  return this.files.read(path, 0, budget.walks);
11752
12290
  }
@@ -11758,7 +12296,7 @@ class HistoryFiles {
11758
12296
  readCommand(commandId, budget) {
11759
12297
  decodeId(commandId);
11760
12298
  this.assertReadFormat(budget);
11761
- 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);
11762
12300
  }
11763
12301
  readAdmission(runId, identity, budget) {
11764
12302
  return this.readAdmissionIdentity(runId, hash2(canonicalJson(identity)), budget);
@@ -11779,10 +12317,10 @@ class HistoryFiles {
11779
12317
  syncParents(file) {
11780
12318
  if (process.platform === "win32")
11781
12319
  return;
11782
- for (let path = dirname12(file);; path = dirname12(path)) {
12320
+ for (let path = dirname15(file);; path = dirname15(path)) {
11783
12321
  if (!this.files.directory(path))
11784
12322
  corrupt();
11785
- const fd = openSync6(path, constants5.O_RDONLY | constants5.O_DIRECTORY);
12323
+ const fd = openSync6(path, constants6.O_RDONLY | constants6.O_DIRECTORY);
11786
12324
  try {
11787
12325
  fsyncSync3(fd);
11788
12326
  } finally {
@@ -11790,13 +12328,13 @@ class HistoryFiles {
11790
12328
  }
11791
12329
  if (path === this.coordination.directory)
11792
12330
  break;
11793
- if (path === dirname12(path))
12331
+ if (path === dirname15(path))
11794
12332
  corrupt();
11795
12333
  }
11796
12334
  }
11797
12335
  assertReadFormat(budget) {
11798
12336
  budget.reserve(this.formatSnapshot.bytes.length);
11799
- 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);
11800
12338
  }
11801
12339
  assertPublished(segment, end, seq) {
11802
12340
  const fence = publicationFences.get(this.directory);
@@ -11834,7 +12372,7 @@ class HistoryFiles {
11834
12372
  const dir = opendirSync7(path);
11835
12373
  try {
11836
12374
  for (let e = dir.readSync();e; e = dir.readSync()) {
11837
- const p = join17(path, e.name), st = lstatSync11(p);
12375
+ const p = join19(path, e.name), st = lstatSync12(p);
11838
12376
  if (st.isDirectory())
11839
12377
  bytes += walk(p, depth + 1);
11840
12378
  else {
@@ -11869,7 +12407,7 @@ class HistoryFiles {
11869
12407
  state.bytes = 0;
11870
12408
  state.identity = null;
11871
12409
  let count = 0;
11872
- const ledger = join17(this.directory, "ledger");
12410
+ const ledger = join19(this.directory, "ledger");
11873
12411
  if (!this.files.directory(ledger))
11874
12412
  corrupt();
11875
12413
  const dir = opendirSync7(ledger);
@@ -12032,9 +12570,9 @@ class HistoryFiles {
12032
12570
  this.activity().generation++;
12033
12571
  const before = this.files.create(path, "", LIMITS.segmentBytes);
12034
12572
  let committed;
12035
- 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));
12036
12574
  const assertOriginal = (bytes) => {
12037
- const original = fstatSync5(fd.fd), selected2 = lstatSync11(path);
12575
+ const original = fstatSync5(fd.fd), selected2 = lstatSync12(path);
12038
12576
  if (original.dev !== selected2.dev || original.ino !== selected2.ino || original.nlink !== 1)
12039
12577
  corrupt();
12040
12578
  const snapshot = this.files.read(path, LIMITS.segmentBytes);
@@ -12147,11 +12685,11 @@ class HistoryFiles {
12147
12685
  }
12148
12686
  if (!before || segment === state.segment && (before.bytes.length !== state.bytes || before.identity !== state.identity))
12149
12687
  corrupt();
12150
- 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));
12151
12689
  try {
12152
12690
  lease.assert();
12153
12691
  this.files.assert(path, before, LIMITS.segmentBytes);
12154
- const opened = await fd.stat(), selected2 = lstatSync11(path);
12692
+ const opened = await fd.stat(), selected2 = lstatSync12(path);
12155
12693
  if (opened.ino !== selected2.ino || opened.dev !== selected2.dev || opened.nlink !== 1)
12156
12694
  corrupt();
12157
12695
  beforeEffect?.();
@@ -12186,7 +12724,7 @@ class HistoryFiles {
12186
12724
  checkpoint(lease, state) {
12187
12725
  lease.assert();
12188
12726
  this.assertWritable();
12189
- 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);
12190
12728
  const body = encoded({
12191
12729
  schema: "cadence-history-checkpoint/2",
12192
12730
  storeId: this.format.storeId,
@@ -12895,7 +13433,7 @@ class HistoryNavigation {
12895
13433
  cacheBytes = 0;
12896
13434
  blocks = new Map;
12897
13435
  block(path, at, size2, budget) {
12898
- 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));
12899
13437
  let old = this.blocks.get(key);
12900
13438
  if (!old || old.budget !== budget || old.stamp !== st) {
12901
13439
  const bytes = readRange(this.files, path, start, Math.min(1024 * 1024, size2 - start), budget);
@@ -12933,9 +13471,9 @@ class HistoryNavigation {
12933
13471
  if (row.value.kind === "auth-preparation")
12934
13472
  auth.set(row.value.intent.operationId, row.value.intent.runId);
12935
13473
  if (row.value.kind === "auth-settlement") {
12936
- const run = auth.get(row.value.result.operationId);
12937
- if (run)
12938
- keys2.add(run);
13474
+ const run2 = auth.get(row.value.result.operationId);
13475
+ if (run2)
13476
+ keys2.add(run2);
12939
13477
  auth.delete(row.value.result.operationId);
12940
13478
  }
12941
13479
  }
@@ -12973,7 +13511,7 @@ class HistoryNavigation {
12973
13511
  }
12974
13512
  }
12975
13513
  indexPath(group, id) {
12976
- return join18(this.files.directory, "indexes", group, `${id}.json`);
13514
+ return join20(this.files.directory, "indexes", group, `${id}.json`);
12977
13515
  }
12978
13516
  hintKey(group, id) {
12979
13517
  return `${this.files.directory}/${this.files.format.storeId}/${group}/${id}`;
@@ -13030,9 +13568,9 @@ class HistoryNavigation {
13030
13568
  return structuredClone(source.value);
13031
13569
  }
13032
13570
  try {
13033
- if (!this.files.files.directory(dirname13(path), false, budget.walks))
13571
+ if (!this.files.files.directory(dirname16(path), false, budget.walks))
13034
13572
  return source ? structuredClone(source.value) : undefined;
13035
- const size2 = lstatSync12(path).size;
13573
+ const size2 = lstatSync13(path).size;
13036
13574
  if (size2 > RECORD_BYTES)
13037
13575
  return source ? structuredClone(source.value) : undefined;
13038
13576
  return parseWireJson(readRange(this.files, path, 0, size2, budget).toString("utf8"), RECORD_BYTES);
@@ -13111,10 +13649,10 @@ class HistoryNavigation {
13111
13649
  if (row.value.kind === "auth-preparation")
13112
13650
  this.authRuns.set(row.value.intent.operationId, row.value.intent.runId);
13113
13651
  if (row.value.kind === "auth-settlement") {
13114
- const run = this.authRuns.get(row.value.result.operationId);
13115
- if (run) {
13116
- keys2.add(run);
13117
- runKeys.add(run);
13652
+ const run2 = this.authRuns.get(row.value.result.operationId);
13653
+ if (run2) {
13654
+ keys2.add(run2);
13655
+ runKeys.add(run2);
13118
13656
  }
13119
13657
  this.authRuns.delete(row.value.result.operationId);
13120
13658
  }
@@ -13164,7 +13702,7 @@ class HistoryNavigation {
13164
13702
  }
13165
13703
  batch(p, budget) {
13166
13704
  const key = canonicalJson(p), cached = this.cache.get(key), path = this.files.segmentPath(p.segment);
13167
- if (cached && cached.budget === budget && cached.stamp === stamp3(lstatSync12(path))) {
13705
+ if (cached && cached.budget === budget && cached.stamp === stamp3(lstatSync13(path))) {
13168
13706
  this.validateBridge(cached.batch.rows, p, budget);
13169
13707
  this.rememberBoundary(p, cached.batch.navigationRoot, budget);
13170
13708
  return cached.batch;
@@ -13175,7 +13713,7 @@ class HistoryNavigation {
13175
13713
  if (cached.identity !== identity)
13176
13714
  bad2();
13177
13715
  cached.budget = budget;
13178
- cached.stamp = stamp3(lstatSync12(path));
13716
+ cached.stamp = stamp3(lstatSync13(path));
13179
13717
  this.files.assertPublished(p.segment, p.offset + p.bytes, p.seq);
13180
13718
  this.validateBridge(cached.batch.rows, p, budget);
13181
13719
  this.rememberBoundary(p, cached.batch.navigationRoot, budget);
@@ -13226,7 +13764,7 @@ class HistoryNavigation {
13226
13764
  identity,
13227
13765
  batch,
13228
13766
  bytes: bytes.length,
13229
- stamp: stamp3(lstatSync12(path)),
13767
+ stamp: stamp3(lstatSync13(path)),
13230
13768
  budget
13231
13769
  });
13232
13770
  this.cacheBytes += bytes.length;
@@ -13243,7 +13781,7 @@ class HistoryNavigation {
13243
13781
  const path = this.files.segmentPath(segment);
13244
13782
  let size2;
13245
13783
  try {
13246
- size2 = lstatSync12(path).size;
13784
+ size2 = lstatSync13(path).size;
13247
13785
  } catch (e) {
13248
13786
  if (e instanceof Error && "code" in e && e.code === "ENOENT")
13249
13787
  return null;
@@ -14104,7 +14642,7 @@ function materializeEntity(s, sources) {
14104
14642
 
14105
14643
  // src/history/export.ts
14106
14644
  import { createHash as createHash15, randomUUID as randomUUID11 } from "node:crypto";
14107
- import { readFileSync as readFileSync2 } from "node:fs";
14645
+ import { readFileSync as readFileSync4 } from "node:fs";
14108
14646
 
14109
14647
  // src/history/search.ts
14110
14648
  import { createHash as createHash14 } from "node:crypto";
@@ -15957,14 +16495,14 @@ async function searchQuantum(reader, value, limit = LIMITS.pageEntries) {
15957
16495
  // src/history/export.ts
15958
16496
  var exporterIdentity;
15959
16497
  function buildIdentity() {
15960
- 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");
15961
16499
  return exporterIdentity;
15962
16500
  }
15963
16501
  function aborted(signal) {
15964
16502
  if (signal.aborted)
15965
16503
  throw new ContractError("unavailable");
15966
16504
  }
15967
- var yieldTurn = () => new Promise((resolve8) => setImmediate(resolve8));
16505
+ var yieldTurn = () => new Promise((resolve9) => setImmediate(resolve9));
15968
16506
  function* textChunks(text2) {
15969
16507
  const bytes = Buffer.from(text2);
15970
16508
  for (let at = 0;at < bytes.length; ) {
@@ -16692,14 +17230,14 @@ function decodeState(value) {
16692
17230
  legacyIdentity: o.legacyIdentity
16693
17231
  };
16694
17232
  }
16695
- function target(entity, run, stop = null) {
17233
+ function target(entity, run2, stop = null) {
16696
17234
  return {
16697
17235
  phase: "scan",
16698
17236
  proof: freshValidator(),
16699
17237
  row: 0,
16700
17238
  event: 0,
16701
17239
  entity,
16702
- run,
17240
+ run: run2,
16703
17241
  stop
16704
17242
  };
16705
17243
  }
@@ -17803,7 +18341,7 @@ class HistoryProjection {
17803
18341
  // src/history/reader.ts
17804
18342
  import { createHash as createHash18 } from "node:crypto";
17805
18343
  import { existsSync as existsSync2 } from "node:fs";
17806
- import { join as join19 } from "node:path";
18344
+ import { join as join21 } from "node:path";
17807
18345
 
17808
18346
  // src/history/saved-graph-state.ts
17809
18347
  var freshSavedGraph = () => ({
@@ -18202,12 +18740,12 @@ class HistoryReader {
18202
18740
  }
18203
18741
  reviewSelection(taskId2, runId, snapshotSeq) {
18204
18742
  const budget = HistoryReadBudget.authority();
18205
- const run = this.reviewRun(taskId2, runId, snapshotSeq, budget);
18206
- if (!run.admission)
18743
+ const run2 = this.reviewRun(taskId2, runId, snapshotSeq, budget);
18744
+ if (!run2.admission)
18207
18745
  throw new ContractError("corrupt-selected");
18208
- const { graph } = this.files.readAdmission(runId, run.admission, budget);
18746
+ const { graph } = this.files.readAdmission(runId, run2.admission, budget);
18209
18747
  if (!graph)
18210
- return { run, graph, readablePlan: "" };
18748
+ return { run: run2, graph, readablePlan: "" };
18211
18749
  const ref = graph.plan;
18212
18750
  const { detail, bytes } = this.planText({
18213
18751
  storeId: this.storeId,
@@ -18221,7 +18759,7 @@ class HistoryReader {
18221
18759
  }, budget);
18222
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)
18223
18761
  throw new ContractError("corrupt-selected");
18224
- return { run, graph, readablePlan: bytes.toString("utf8") };
18762
+ return { run: run2, graph, readablePlan: bytes.toString("utf8") };
18225
18763
  }
18226
18764
  async graph(value) {
18227
18765
  const request3 = decodeGraphReadRequest(value);
@@ -18571,7 +19109,7 @@ class HistoryReader {
18571
19109
  }
18572
19110
  async readDetail(value) {
18573
19111
  const cursor = decodeCursor(value);
18574
- 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")))
18575
19113
  return readRetainedDetail(this, cursor);
18576
19114
  if (this.files.format.schema !== FORMAT)
18577
19115
  return this.detail(cursor);
@@ -18773,12 +19311,12 @@ class HistoryReader {
18773
19311
 
18774
19312
  // src/history/recovery.ts
18775
19313
  import { createHash as createHash22, randomUUID as randomUUID15 } from "node:crypto";
18776
- import { lstatSync as lstatSync13, opendirSync as opendirSync8 } from "node:fs";
18777
- 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";
18778
19316
 
18779
19317
  // src/history/writer.ts
18780
19318
  import { createHash as createHash21, randomUUID as randomUUID14 } from "node:crypto";
18781
- import { join as join22 } from "node:path";
19319
+ import { join as join24 } from "node:path";
18782
19320
 
18783
19321
  // src/task-store.ts
18784
19322
  import { createHash as createHash19, randomUUID as randomUUID12 } from "node:crypto";
@@ -18787,12 +19325,12 @@ import {
18787
19325
  fsyncSync as fsyncSync4,
18788
19326
  openSync as openSync7,
18789
19327
  readdirSync as readdirSync2,
18790
- renameSync as renameSync3,
19328
+ renameSync as renameSync4,
18791
19329
  unlinkSync as unlinkSync3,
18792
- writeFileSync as writeFileSync3
19330
+ writeFileSync as writeFileSync4
18793
19331
  } from "node:fs";
18794
19332
  import { hostname as hostname6 } from "node:os";
18795
- import { join as join20 } from "node:path";
19333
+ import { join as join22 } from "node:path";
18796
19334
  // src/task-types.ts
18797
19335
  var TASK_SCHEMA = "cadence-workflow-assistant/1";
18798
19336
  var MAX_RECORD_BYTES = 128 * 1024;
@@ -18879,7 +19417,7 @@ class TaskStore extends CheckoutStore {
18879
19417
  tasks;
18880
19418
  constructor(root, stateHome = defaultStateHome()) {
18881
19419
  super(root, stateHome);
18882
- this.tasks = join20(this.root, ".cadence", "assistant", "tasks");
19420
+ this.tasks = join22(this.root, ".cadence", "assistant", "tasks");
18883
19421
  }
18884
19422
  recover(expected, acknowledgeEscapedProcesses) {
18885
19423
  if (!acknowledgeEscapedProcesses || expected.host !== hostname6())
@@ -18902,10 +19440,10 @@ class TaskStore extends CheckoutStore {
18902
19440
  loadSnapshot(id) {
18903
19441
  if (!validId(id))
18904
19442
  throw new Error("Invalid task id");
18905
- const directory = join20(this.tasks, id);
19443
+ const directory = join22(this.tasks, id);
18906
19444
  if (safeDirectory(directory) && readdirSync2(directory).some((name) => name !== "task.json"))
18907
19445
  throw new Error("Unknown task directory content; preserved without reset");
18908
- 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);
18909
19447
  if (!data)
18910
19448
  return;
18911
19449
  const record2 = decodeTask(parseRecord(data));
@@ -18943,25 +19481,25 @@ class TaskStore extends CheckoutStore {
18943
19481
  throw new Error("Revision conflict");
18944
19482
  if (current2?.identity !== expectedIdentity)
18945
19483
  throw new Error("Task content changed; reopen it");
18946
- const dir = join20(this.tasks, next.id);
19484
+ const dir = join22(this.tasks, next.id);
18947
19485
  safeDirectory(dir, true);
18948
19486
  if (!current2 && readdirSync2(dir).length)
18949
19487
  throw new Error("Unknown task directory");
18950
- const temporary = join20(dir, `task.${randomUUID12()}.tmp`);
19488
+ const temporary = join22(dir, `task.${randomUUID12()}.tmp`);
18951
19489
  const fd = openSync7(temporary, "wx", 384);
18952
19490
  try {
18953
- writeFileSync3(fd, text2);
19491
+ writeFileSync4(fd, text2);
18954
19492
  fsyncSync4(fd);
18955
19493
  } finally {
18956
19494
  closeSync7(fd);
18957
19495
  }
18958
19496
  this.assertOwner(lock);
18959
- const latest = readBounded(join20(dir, "task.json"), MAX_RECORD_BYTES);
19497
+ const latest = readBounded(join22(dir, "task.json"), MAX_RECORD_BYTES);
18960
19498
  if ((latest ? contentIdentity(latest) : undefined) !== expectedIdentity)
18961
19499
  throw new Error("Task content changed; replacement preserved without overwrite");
18962
- retryWindowsFileOperation(() => renameSync3(temporary, join20(dir, "task.json")), () => {
19500
+ retryWindowsFileOperation(() => renameSync4(temporary, join22(dir, "task.json")), () => {
18963
19501
  this.assertOwner(lock);
18964
- const now = readBounded(join20(dir, "task.json"), MAX_RECORD_BYTES);
19502
+ const now = readBounded(join22(dir, "task.json"), MAX_RECORD_BYTES);
18965
19503
  if ((now ? contentIdentity(now) : undefined) !== expectedIdentity)
18966
19504
  throw new Error("Task content changed; replacement preserved without overwrite");
18967
19505
  });
@@ -18972,7 +19510,7 @@ class TaskStore extends CheckoutStore {
18972
19510
  }
18973
19511
  }
18974
19512
  checks() {
18975
- const data = readBounded(join20(this.root, ".cadence", "assistant", "config.json"), 32768);
19513
+ const data = readBounded(join22(this.root, ".cadence", "assistant", "config.json"), 32768);
18976
19514
  if (!data)
18977
19515
  return [];
18978
19516
  const value = parseRecord(data);
@@ -18986,8 +19524,8 @@ class TaskStore extends CheckoutStore {
18986
19524
  readLog(name) {
18987
19525
  if (!/^[a-f0-9-]{36}\.log$/.test(name))
18988
19526
  throw new Error("Invalid diagnostic name");
18989
- this.inspectPrivateFile(join20(this.privateRoot, name), 65536);
18990
- 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);
18991
19529
  return data ? diagnosticText(data.toString("utf8"), 65536) : "Private diagnostic unavailable";
18992
19530
  }
18993
19531
  writeLog(lock, output) {
@@ -18995,7 +19533,7 @@ class TaskStore extends CheckoutStore {
18995
19533
  throw new Error("Not the lock owner");
18996
19534
  this.assertOwner(lock);
18997
19535
  const name = `${randomUUID12()}.log`;
18998
- writeFileSync3(join20(this.privateRoot, name), diagnosticText(output, 65536), {
19536
+ writeFileSync4(join22(this.privateRoot, name), diagnosticText(output, 65536), {
18999
19537
  flag: "wx",
19000
19538
  mode: 384
19001
19539
  });
@@ -19073,12 +19611,12 @@ function planRecording(plan, graph, operationId, epoch) {
19073
19611
  // src/history/publication.ts
19074
19612
  import {
19075
19613
  closeSync as closeSync8,
19076
- constants as constants6,
19614
+ constants as constants7,
19077
19615
  fsyncSync as fsyncSync5,
19078
19616
  openSync as openSync8,
19079
- realpathSync as realpathSync6
19617
+ realpathSync as realpathSync8
19080
19618
  } from "node:fs";
19081
- 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";
19082
19620
  function summary(text2, maximum, runId) {
19083
19621
  const label = `[Cadence summary${runId ? `; run ${runId}` : ""}; retained history is separate]
19084
19622
  `;
@@ -19093,12 +19631,12 @@ function summary(text2, maximum, runId) {
19093
19631
  end--;
19094
19632
  return label + bytes.subarray(0, end).toString("utf8") + tail;
19095
19633
  }
19096
- function publicationPhase(run) {
19097
- if (!run.settlement)
19634
+ function publicationPhase(run2) {
19635
+ if (!run2.settlement)
19098
19636
  return "running";
19099
- switch (settlementOutcome(run.settlement)) {
19637
+ switch (settlementOutcome(run2.settlement)) {
19100
19638
  case "completed":
19101
- return run.admission?.kind === "generate-plan" ? "planning" : "review";
19639
+ return run2.admission?.kind === "generate-plan" ? "planning" : "review";
19102
19640
  case "failed":
19103
19641
  case "blocked":
19104
19642
  return "failed";
@@ -19111,7 +19649,7 @@ function publicationPhase(run) {
19111
19649
  function bad11() {
19112
19650
  throw new ContractError("conflict");
19113
19651
  }
19114
- function publicationRecord(store, reader, intent, link, run, request3, expected, facts, snapshotSeq) {
19652
+ function publicationRecord(store, reader, intent, link, run2, request3, expected, facts, snapshotSeq) {
19115
19653
  const identity = intent.identity;
19116
19654
  if (identity.kind !== "action")
19117
19655
  bad11();
@@ -19127,8 +19665,8 @@ function publicationRecord(store, reader, intent, link, run, request3, expected,
19127
19665
  else {
19128
19666
  if (action.kind !== "create" || !request3.cwd || store.list().length >= 1000)
19129
19667
  bad11();
19130
- const cwd = realpathSync6(request3.cwd), within = relative6(store.root, cwd);
19131
- 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}`))
19132
19670
  bad11();
19133
19671
  record2 = {
19134
19672
  schema: TASK_SCHEMA,
@@ -19161,7 +19699,7 @@ function publicationRecord(store, reader, intent, link, run, request3, expected,
19161
19699
  if (mode === "baseline") {
19162
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)))
19163
19701
  bad11();
19164
- } 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)))
19165
19703
  bad11();
19166
19704
  let preview = "";
19167
19705
  for (const part of reader.parts(detail, snapshotSeq))
@@ -19194,12 +19732,12 @@ function publicationRecord(store, reader, intent, link, run, request3, expected,
19194
19732
  record2.phase = "planning";
19195
19733
  delete record2.review;
19196
19734
  }
19197
- if (run) {
19198
- record2.phase = publicationPhase(run);
19735
+ if (run2) {
19736
+ record2.phase = publicationPhase(run2);
19199
19737
  delete record2.review;
19200
19738
  let result = request3.result ? retained(request3.result, "result") : "";
19201
19739
  if (!request3.result)
19202
- for (const child of run.children.values()) {
19740
+ for (const child of run2.children.values()) {
19203
19741
  if (child.completion?.recording.status === "committed") {
19204
19742
  const text2 = retained(child.completion.recording.detail.content, "result");
19205
19743
  if (Buffer.byteLength(result) < 32768)
@@ -19208,24 +19746,24 @@ ${text2}
19208
19746
  `;
19209
19747
  }
19210
19748
  }
19211
- if (run.settlement)
19212
- 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).
19213
19751
  ${result}`;
19214
- if (run.admission?.kind === "generate-plan")
19752
+ if (run2.admission?.kind === "generate-plan")
19215
19753
  result = `Advisory plan proposal only; not saved or authorized for Start. Explicitly edit/accept and Save a plan before a separate Start.
19216
19754
  ${result}`;
19217
19755
  record2.result = summary(result, 16384, link.runId);
19218
- if (action.kind === "check" && run.check && run.settlement?.kind === "check") {
19756
+ if (action.kind === "check" && run2.check && run2.settlement?.kind === "check") {
19219
19757
  if (record2.checks.length >= 32)
19220
19758
  bad11();
19221
- const s = run.settlement;
19759
+ const s = run2.settlement;
19222
19760
  const fact = facts.findLast(({ link: l, fact: f }) => l.runId === link.runId && f.kind === "check-settled")?.fact;
19223
19761
  if (fact?.kind !== "check-settled")
19224
19762
  bad11();
19225
19763
  record2.checks.push({
19226
- name: run.check.selection.name,
19227
- command: run.check.selection.command,
19228
- timeoutMs: run.check.selection.timeoutMs,
19764
+ name: run2.check.selection.name,
19765
+ command: run2.check.selection.command,
19766
+ timeoutMs: run2.check.selection.timeoutMs,
19229
19767
  cwd: record2.cwd,
19230
19768
  exitCode: s.native.exitCode,
19231
19769
  durationMs: s.native.durationMs,
@@ -19263,10 +19801,10 @@ ${result}`;
19263
19801
  function syncTaskPublication(store, taskId2) {
19264
19802
  if (process.platform === "win32")
19265
19803
  return;
19266
- for (let path = join21(store.tasks, taskId2);; path = dirname14(path)) {
19804
+ for (let path = join23(store.tasks, taskId2);; path = dirname17(path)) {
19267
19805
  if (!safeDirectory(path))
19268
19806
  throw new ContractError("conflict");
19269
- const fd = openSync8(path, constants6.O_RDONLY | constants6.O_DIRECTORY);
19807
+ const fd = openSync8(path, constants7.O_RDONLY | constants7.O_DIRECTORY);
19270
19808
  try {
19271
19809
  fsyncSync5(fd);
19272
19810
  } finally {
@@ -19274,17 +19812,17 @@ function syncTaskPublication(store, taskId2) {
19274
19812
  }
19275
19813
  if (path === store.root)
19276
19814
  return;
19277
- if (dirname14(path) === path)
19815
+ if (dirname17(path) === path)
19278
19816
  throw new ContractError("conflict");
19279
19817
  }
19280
19818
  }
19281
19819
 
19282
19820
  // src/history/review.ts
19283
- function reviewIssues(run, current2, code2, epoch) {
19821
+ function reviewIssues(run2, current2, code2, epoch) {
19284
19822
  const issues = new Set;
19285
19823
  if (!current2.observation.complete)
19286
19824
  issues.add("incomplete-observation");
19287
- const projections = run.projections(epoch);
19825
+ const projections = run2.projections(epoch);
19288
19826
  if (projections.some((p) => p.outcome !== "completed"))
19289
19827
  issues.add("partial-results");
19290
19828
  if (projections.some((p) => p.coverage.observed !== "complete" || p.coverage.source !== "complete" || p.coverage.omissions.length))
@@ -19660,29 +20198,29 @@ class HistoryWriter {
19660
20198
  settled?.();
19661
20199
  return Promise.resolve(failure(false));
19662
20200
  }
19663
- let release;
20201
+ let release2;
19664
20202
  try {
19665
- release = this.files.retainOriginal(this.writeGeneration);
20203
+ release2 = this.files.retainOriginal(this.writeGeneration);
19666
20204
  } catch {
19667
20205
  this.fence();
19668
20206
  settled?.();
19669
20207
  return Promise.resolve(failure(false));
19670
20208
  }
19671
- let resolve8;
20209
+ let resolve9;
19672
20210
  const original = new Promise((yes) => {
19673
- resolve8 = yes;
20211
+ resolve9 = yes;
19674
20212
  });
19675
20213
  this.originals.add(original);
19676
20214
  original.then(() => {
19677
20215
  this.originals.delete(original);
19678
- release();
20216
+ release2();
19679
20217
  settled?.();
19680
20218
  });
19681
20219
  try {
19682
20220
  this.options.onOriginal?.(original, safety || continuation);
19683
20221
  } catch {
19684
20222
  this.fence();
19685
- resolve8(failure(false));
20223
+ resolve9(failure(false));
19686
20224
  return original;
19687
20225
  }
19688
20226
  if (this.queue.length && this.queue.reduce((n, j) => n + j.bytes, 0) + bytes > LIMITS.progressBatchBytes)
@@ -19690,7 +20228,7 @@ class HistoryWriter {
19690
20228
  this.queue.push({
19691
20229
  build: build2,
19692
20230
  bytes,
19693
- resolve: resolve8,
20231
+ resolve: resolve9,
19694
20232
  safety,
19695
20233
  continuation,
19696
20234
  control: immediate
@@ -19918,9 +20456,9 @@ class HistoryWriter {
19918
20456
  if (state.admission?.context.task)
19919
20457
  tasks.add(state.admission.context.task.id);
19920
20458
  for (const row of rows) {
19921
- const v = row.value, run = this.rowRunId(v);
19922
- if (run)
19923
- runs.add(run);
20459
+ const v = row.value, run2 = this.rowRunId(v);
20460
+ if (run2)
20461
+ runs.add(run2);
19924
20462
  if (v.kind === "owner" || v.kind === "capture" || v.kind === "launch" || v.kind === "settlement")
19925
20463
  tasks.add(v.link.taskId);
19926
20464
  if (v.kind === "admission" && v.intent.identity.kind === "action") {
@@ -20016,10 +20554,10 @@ class HistoryWriter {
20016
20554
  try {
20017
20555
  const budget = HistoryReadBudget.authority();
20018
20556
  const intent = this.files.readCommand(commandId, budget);
20019
- 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));
20020
20558
  const wanted = intent ? decodeAdmissionIntent(json(intent, RECORD_BYTES)) : null;
20021
20559
  let found = null;
20022
- let run = null;
20560
+ let run2 = null;
20023
20561
  let operation = null;
20024
20562
  const scan = emptyScan();
20025
20563
  for (const batch of this.files.scan(scan, false, budget)) {
@@ -20029,19 +20567,19 @@ class HistoryWriter {
20029
20567
  return { status: "inconclusive" };
20030
20568
  found = row.value.record;
20031
20569
  if (row.value.intent.identity.kind === "action" && row.value.intent.runId)
20032
- run = new RunState(row.value.intent.runId);
20570
+ run2 = new RunState(row.value.intent.runId);
20033
20571
  else if (row.value.intent.identity.kind === "action")
20034
20572
  operation = new OperationState(row.value.intent.operationId);
20035
20573
  }
20036
20574
  for (const row of batch.rows) {
20037
- run?.apply(row, batch.marker.last);
20575
+ run2?.apply(row, batch.marker.last);
20038
20576
  operation?.apply(row, batch.marker.last);
20039
20577
  }
20040
20578
  }
20041
20579
  if (found)
20042
20580
  return {
20043
20581
  status: "found",
20044
- record: decodeStoredCommand(run?.receipt() ?? operation?.receipt() ?? found)
20582
+ record: decodeStoredCommand(run2?.receipt() ?? operation?.receipt() ?? found)
20045
20583
  };
20046
20584
  if (wanted || directoryExists || scan.tail)
20047
20585
  return { status: "inconclusive" };
@@ -20162,8 +20700,8 @@ class HistoryWriter {
20162
20700
  this.assertOrdinary();
20163
20701
  const bytes = encoded(intent);
20164
20702
  this.charge(Buffer.byteLength(bytes), intent.runId, true);
20165
- this.files.files.create(join22(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
20166
- 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"));
20167
20705
  await this.options.observeWrite?.("intent");
20168
20706
  const policy = this.resourcePolicy(intent.identity.kind === "action" ? intent.identity.expected.configRev : 1);
20169
20707
  return { kind: "admission", intent, record: record2, policy };
@@ -20297,11 +20835,11 @@ class HistoryWriter {
20297
20835
  continue;
20298
20836
  try {
20299
20837
  const checks = checkFold(this.files, taskId2, head.seq, HistoryReadBudget.authority()).state();
20300
- const run = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
20838
+ const run2 = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
20301
20839
  const plan = planFold(this.files, taskId2, head.seq, HistoryReadBudget.authority(), new HistoryNavigation(this.files), true).state();
20302
20840
  taskFoldMemory(this.files).remember(taskId2, head, {
20303
20841
  checks,
20304
- run,
20842
+ run: run2,
20305
20843
  plan
20306
20844
  });
20307
20845
  } catch {}
@@ -20361,10 +20899,10 @@ class HistoryWriter {
20361
20899
  }
20362
20900
  };
20363
20901
  assertContext();
20364
- const run = intent.runId ? this.retainedRun(intent.runId) : null;
20365
- if (run && !run.admission)
20902
+ const run2 = intent.runId ? this.retainedRun(intent.runId) : null;
20903
+ if (run2 && !run2.admission)
20366
20904
  throw new ContractError("conflict");
20367
- expected = run ? run.publicationExpected() : operation.state.publicationExpected();
20905
+ expected = run2 ? run2.publicationExpected() : operation.state.publicationExpected();
20368
20906
  link = {
20369
20907
  epoch: identity.expected.epoch,
20370
20908
  taskId: taskId2,
@@ -20374,7 +20912,7 @@ class HistoryWriter {
20374
20912
  const reader = HistoryReader.open(this.lease.coordination);
20375
20913
  if (!reader)
20376
20914
  throw new ContractError("unavailable");
20377
- 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);
20378
20916
  this.charge(2 * Buffer.byteLength(`${JSON.stringify(record2, null, 2)}
20379
20917
  `), intent.runId, true);
20380
20918
  return this.ownerValue({
@@ -20519,9 +21057,9 @@ class HistoryWriter {
20519
21057
  }
20520
21058
  childSlots() {
20521
21059
  let slots = 0;
20522
- for (const run of this.runs.values())
20523
- for (const auth of run.auth.values()) {
20524
- 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);
20525
21063
  if (child ? child.completion === null : auth.result === null || auth.result.outcome === "resolved" && !auth.result.admissionClosed)
20526
21064
  slots++;
20527
21065
  }
@@ -20897,10 +21435,10 @@ class HistoryWriter {
20897
21435
  const checks = decodeCheckObligations(review.checks);
20898
21436
  if (checks.taskId !== input.link.taskId || checks.revision !== fact.checksRevision || canonicalJson(review.observation) !== canonicalJson(changes.observation))
20899
21437
  throw new ContractError("conflict");
20900
- const run = this.retainedRun(fact.runId);
20901
- 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)
20902
21440
  throw new ContractError("conflict");
20903
- 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);
20904
21442
  if (issues.length && (fact.outcome !== "reviewed-with-issues" || !fact.acceptIssues))
20905
21443
  throw new ContractError("conflict");
20906
21444
  }
@@ -20958,11 +21496,11 @@ class HistoryWriter {
20958
21496
  throw new ContractError("conflict");
20959
21497
  }
20960
21498
  if (fact.kind === "gate" && fact.reservationId && fact.lane !== "check") {
20961
- const run = value.link.runId ? this.runs.get(value.link.runId) ?? this.retainedRun(value.link.runId) : null;
20962
- 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)
20963
21501
  throw new ContractError("conflict");
20964
- const selected2 = this.files.readAdmission(run.runId, run.admission);
20965
- 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);
20966
21504
  const assignment = selected2.graph?.assignments.find((a) => a.id === allocation?.assignmentId);
20967
21505
  if (!allocation || (assignment?.purpose === "edit" ? "writer" : "reader") !== fact.lane)
20968
21506
  throw new ContractError("conflict");
@@ -21066,7 +21604,7 @@ function digestHistory(files, exclude) {
21066
21604
  const walk = (path, depth) => {
21067
21605
  if (depth > 8 || !files.files.directory(path))
21068
21606
  throw new ContractError("corrupt-selected");
21069
- const directory = lstatSync13(path);
21607
+ const directory = lstatSync14(path);
21070
21608
  digest.update(`incarnation:${directory.dev}:${directory.ino}
21071
21609
  `);
21072
21610
  const dir = opendirSync8(path), names2 = [];
@@ -21080,11 +21618,11 @@ function digestHistory(files, exclude) {
21080
21618
  dir.closeSync();
21081
21619
  }
21082
21620
  for (const name of names2.sort()) {
21083
- const selected2 = join23(path, name);
21621
+ const selected2 = join25(path, name);
21084
21622
  if (selected2 === exclude)
21085
21623
  continue;
21086
21624
  const rel = relative7(files.directory, selected2);
21087
- if (lstatSync13(selected2).isDirectory()) {
21625
+ if (lstatSync14(selected2).isDirectory()) {
21088
21626
  digest.update(`directory:${Buffer.byteLength(rel)}:${rel}
21089
21627
  `);
21090
21628
  walk(selected2, depth + 1);
@@ -21141,7 +21679,7 @@ function damaged(error) {
21141
21679
  }
21142
21680
  async function healHistory(lease, log) {
21143
21681
  lease.assert();
21144
- const c = lease.coordination, directory = join23(c.directory, "history-v2");
21682
+ const c = lease.coordination, directory = join25(c.directory, "history-v2");
21145
21683
  let files;
21146
21684
  let broken = false;
21147
21685
  try {
@@ -21172,20 +21710,21 @@ async function healHistory(lease, log) {
21172
21710
  }
21173
21711
 
21174
21712
  // src/subagent-process.ts
21175
- import { spawn as spawn2 } from "node:child_process";
21176
- import { join as join24 } from "node:path";
21713
+ import { spawn as spawn3 } from "node:child_process";
21714
+ import { join as join26 } from "node:path";
21177
21715
  import { StringDecoder } from "node:string_decoder";
21178
- import { fileURLToPath as fileURLToPath4 } from "node:url";
21716
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
21179
21717
 
21180
21718
  // src/conversation-context.mjs
21181
21719
  var CONTEXT_BYTES = 2 * 1024 * 1024;
21182
- var clean = (s, secrets, max = CONTEXT_BYTES) => sanitizeText(text(s, max), secrets);
21720
+ var CONTEXT_RECORD_BYTES = LIMITS.detailBytes;
21721
+ var clean = (s, secrets, max = CONTEXT_RECORD_BYTES) => sanitizeText(text(s, max), secrets);
21183
21722
  function argumentsData(value, secrets) {
21184
21723
  const sanitizer = new DetailSanitizer("canonical-json", secrets);
21185
- const source = sanitizer.write(canonicalJson(value, 64 * 1024)) + sanitizer.end();
21724
+ const source = sanitizer.write(canonicalJson(value, CONTEXT_RECORD_BYTES)) + sanitizer.end();
21186
21725
  if (sanitizer.limited)
21187
21726
  throw new Error("Unsupported context arguments");
21188
- return parseWireJson(source, 64 * 1024);
21727
+ return parseWireJson(source, CONTEXT_RECORD_BYTES);
21189
21728
  }
21190
21729
  function own2(value, key2) {
21191
21730
  const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
@@ -21780,11 +22319,11 @@ class WorkerRecording {
21780
22319
  try {
21781
22320
  await Promise.race([
21782
22321
  ...this.pending,
21783
- new Promise((resolve8) => {
21784
- abort = resolve8;
22322
+ new Promise((resolve9) => {
22323
+ abort = resolve9;
21785
22324
  signal.addEventListener("abort", abort, { once: true });
21786
22325
  if (signal.aborted)
21787
- resolve8();
22326
+ resolve9();
21788
22327
  })
21789
22328
  ]);
21790
22329
  } finally {
@@ -21812,11 +22351,11 @@ class WorkerRecording {
21812
22351
  let timer;
21813
22352
  await Promise.race([
21814
22353
  Promise.all([...this.pending]),
21815
- new Promise((resolve8) => {
22354
+ new Promise((resolve9) => {
21816
22355
  timer = setTimeout(() => {
21817
22356
  this.failure = "uncertain";
21818
22357
  this.stop();
21819
- resolve8();
22358
+ resolve9();
21820
22359
  }, LIMITS.recordingStallMs);
21821
22360
  })
21822
22361
  ]);
@@ -21846,7 +22385,7 @@ class WorkerRecording {
21846
22385
  // src/subagent-process.ts
21847
22386
  function terminateWindowsTree(pid, fallback) {
21848
22387
  const root = process.env.SystemRoot;
21849
- 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 });
21850
22389
  taskkill.once("error", fallback);
21851
22390
  taskkill.once("close", (code2) => {
21852
22391
  if (code2 !== 0)
@@ -21884,8 +22423,8 @@ function runProcess(spec) {
21884
22423
  throw new Error("Invalid service check context");
21885
22424
  if (spec.input !== undefined && Buffer.byteLength(spec.input) > 128 * 1024)
21886
22425
  return Promise.resolve(early("failed", "Worker input exceeds bound"));
21887
- return new Promise((resolve8) => {
21888
- const child = spawn2(spec.command, spec.args, {
22426
+ return new Promise((resolve9) => {
22427
+ const child = spawn3(spec.command, spec.args, {
21889
22428
  cwd: spec.cwd,
21890
22429
  env: spec.env ?? safeChildEnv(),
21891
22430
  detached: process.platform !== "win32",
@@ -21974,7 +22513,7 @@ function runProcess(spec) {
21974
22513
  omissions: ["gap"]
21975
22514
  }
21976
22515
  }, capture);
21977
- resolve8({
22516
+ resolve9({
21978
22517
  outcome,
21979
22518
  closed: closed2,
21980
22519
  exitCode,
@@ -22165,12 +22704,26 @@ function runProcess(spec) {
22165
22704
  contextStream?.on("data", (chunk) => {
22166
22705
  if (settled || stopping)
22167
22706
  return;
22168
- contextBytes += chunk.length;
22169
- if (contextBytes > CONTEXT_BYTES) {
22707
+ try {
22708
+ let offset = 0;
22709
+ while (offset < chunk.length) {
22710
+ const end = chunk.indexOf(10, offset);
22711
+ const part = chunk.subarray(offset, end < 0 ? chunk.length : end);
22712
+ contextBytes += part.length;
22713
+ if (contextBytes > CONTEXT_RECORD_BYTES)
22714
+ throw new Error("Checkpoint record too large");
22715
+ contextChunks.push(part);
22716
+ if (end < 0)
22717
+ break;
22718
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(contextChunks, contextBytes));
22719
+ contextChunks.length = 0;
22720
+ contextBytes = 0;
22721
+ spec.onContext?.(source);
22722
+ offset = end + 1;
22723
+ }
22724
+ } catch {
22170
22725
  stop("failed");
22171
- return;
22172
22726
  }
22173
- contextChunks.push(chunk);
22174
22727
  });
22175
22728
  contextStream?.once("end", () => {
22176
22729
  contextEnded = true;
@@ -22230,9 +22783,9 @@ function runProcess(spec) {
22230
22783
  const close = () => {
22231
22784
  if (spec.onContext && !stopping && code2 === 0) {
22232
22785
  try {
22233
- if (!contextEnded)
22786
+ if (!contextEnded || contextBytes)
22234
22787
  throw new Error("Context EOF missing");
22235
- spec.onContext(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(contextChunks)));
22788
+ spec.onContextEnd?.();
22236
22789
  } catch {
22237
22790
  stopping = "failed";
22238
22791
  }
@@ -22308,7 +22861,7 @@ function launchEncoded(encoded2, signal, timeoutMs, extra = {}) {
22308
22861
  throw new Error("network");
22309
22862
  return runProcess({
22310
22863
  command: process.execPath,
22311
- args: [fileURLToPath4(new URL("./sdk-worker.mjs", import.meta.url))],
22864
+ args: [fileURLToPath5(new URL("./sdk-worker.mjs", import.meta.url))],
22312
22865
  cwd: encoded2.material.cwd,
22313
22866
  input: encoded2.input,
22314
22867
  env: encoded2.selected.env,
@@ -22335,22 +22888,33 @@ function launchConversation(prepared, conversation, signal, options) {
22335
22888
  if (!encoded2 || encoded2.input !== input)
22336
22889
  throw new Error("Invalid chat launch");
22337
22890
  const secrets = encoded2.secrets;
22891
+ let contextCount = 0, contextComplete = false;
22338
22892
  return launchEncoded(encoded2, signal, options.timeoutMs, {
22339
22893
  maySignal: options.maySignal,
22340
22894
  onNative: options.onNative,
22341
22895
  onCoordinator: options.onCoordinator,
22342
22896
  onFrame: (frame) => options.onFrame(frame, secrets),
22343
22897
  onContext: (source) => {
22344
- const value = closed(parseWireJson(source, CONTEXT_BYTES), [
22345
- "schema",
22346
- "messages"
22347
- ]);
22348
- if (value.schema !== "cadence-conversation-context/1")
22898
+ if (contextComplete)
22899
+ throw new Error("Checkpoint after end");
22900
+ const value = parseWireJson(source, CONTEXT_RECORD_BYTES);
22901
+ if (value.schema === "cadence-conversation-stream-end/1") {
22902
+ const record3 = closed(value, ["schema", "count"]);
22903
+ if (record3.count !== contextCount)
22904
+ throw new Error("Invalid checkpoint count");
22905
+ contextComplete = true;
22906
+ return;
22907
+ }
22908
+ const record2 = closed(value, ["schema", "message"]);
22909
+ if (record2.schema !== "cadence-conversation-stream/1")
22349
22910
  throw new Error("Invalid checkpoint");
22350
- options.onContext(conversationMessages(value.messages, [
22351
- ...options.ownerSecrets(),
22352
- ...secrets
22353
- ]));
22911
+ options.onContext(conversationMessages([record2.message], [...options.ownerSecrets(), ...secrets])[0]);
22912
+ contextCount++;
22913
+ },
22914
+ onContextEnd: () => {
22915
+ if (!contextComplete)
22916
+ throw new Error("Incomplete checkpoint");
22917
+ options.onContextEnd();
22354
22918
  }
22355
22919
  });
22356
22920
  });
@@ -22479,7 +23043,7 @@ class CheckoutGate {
22479
23043
  throw new ContractError("conflict");
22480
23044
  if (this.waiting.length >= CHECKOUT_WAITERS)
22481
23045
  throw new ContractError("capacity");
22482
- const result = new Promise((resolve8, reject) => {
23046
+ const result = new Promise((resolve9, reject) => {
22483
23047
  const abort = () => {
22484
23048
  const at = this.waiting.indexOf(waiter);
22485
23049
  if (at >= 0)
@@ -22489,7 +23053,7 @@ class CheckoutGate {
22489
23053
  id,
22490
23054
  resolve: (permit) => {
22491
23055
  signal.removeEventListener("abort", abort);
22492
- resolve8(permit);
23056
+ resolve9(permit);
22493
23057
  },
22494
23058
  reject: (error) => {
22495
23059
  signal.removeEventListener("abort", abort);
@@ -22621,8 +23185,8 @@ class OwnerModelChoice {
22621
23185
  }
22622
23186
 
22623
23187
  // src/service/model-config.ts
22624
- import { lstatSync as lstatSync14, realpathSync as realpathSync7 } from "node:fs";
22625
- 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";
22626
23190
  var CONFIG_BYTES2 = 1024 * 1024;
22627
23191
  var ENTRY_LIMIT = 256;
22628
23192
  function refuse2() {
@@ -22687,16 +23251,16 @@ function captureEnvironment(value) {
22687
23251
  return Object.freeze(out);
22688
23252
  }
22689
23253
  function piSource(agentDir, home, cwd, env) {
22690
- if (!isAbsolute8(home) || !isAbsolute8(cwd))
23254
+ if (!isAbsolute9(home) || !isAbsolute9(cwd))
22691
23255
  refuse2();
22692
- 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");
22693
23257
  if (!selected2 || selected2.includes("\x00"))
22694
23258
  refuse2();
22695
23259
  if (selected2 === "~" || selected2.startsWith("~/"))
22696
23260
  selected2 = home + selected2.slice(1);
22697
- selected2 = resolve8(cwd, selected2);
22698
- const directory = join25(realpathSync7(dirname15(selected2)), selected2.slice(dirname15(selected2).length + 1));
22699
- 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())
22700
23264
  refuse2();
22701
23265
  const files = new PrivateFiles(directory, false);
22702
23266
  if (!files.directory(directory))
@@ -22704,8 +23268,8 @@ function piSource(agentDir, home, cwd, env) {
22704
23268
  return {
22705
23269
  directory,
22706
23270
  files,
22707
- authPath: join25(directory, "auth.json"),
22708
- modelsPath: join25(directory, "models.json")
23271
+ authPath: join27(directory, "auth.json"),
23272
+ modelsPath: join27(directory, "models.json")
22709
23273
  };
22710
23274
  }
22711
23275
  function templateNames(value) {
@@ -23653,10 +24217,10 @@ class OwnerModelContext {
23653
24217
  closed2 = true;
23654
24218
  };
23655
24219
  let reportClosed;
23656
- const closedWait = new Promise((resolve9) => {
24220
+ const closedWait = new Promise((resolve10) => {
23657
24221
  reportClosed = () => {
23658
24222
  close();
23659
- resolve9(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
24223
+ resolve10(refusal2(new ContractError("auth-unavailable"), effectStarted ? "uncertain" : "none"));
23660
24224
  };
23661
24225
  });
23662
24226
  input.signal.addEventListener("abort", reportClosed, { once: true });
@@ -24090,8 +24654,8 @@ class ServiceOwner {
24090
24654
  if (!this.attempt) {
24091
24655
  this.reportingExpired = false;
24092
24656
  let complete;
24093
- this.attempt = new Promise((resolve9) => {
24094
- complete = resolve9;
24657
+ this.attempt = new Promise((resolve10) => {
24658
+ complete = resolve10;
24095
24659
  });
24096
24660
  const finish = () => {
24097
24661
  this.attempt = undefined;
@@ -24109,11 +24673,11 @@ class ServiceOwner {
24109
24673
  try {
24110
24674
  await Promise.race([
24111
24675
  this.attempt,
24112
- new Promise((resolve9) => {
24676
+ new Promise((resolve10) => {
24113
24677
  timer = setTimeout(() => {
24114
24678
  this.reportingExpired = true;
24115
24679
  this.persistPhase("quarantined");
24116
- resolve9();
24680
+ resolve10();
24117
24681
  }, waitMs);
24118
24682
  })
24119
24683
  ]);
@@ -24143,13 +24707,13 @@ class ServiceOwner {
24143
24707
  }
24144
24708
 
24145
24709
  // src/service/workbench.ts
24146
- import { opendirSync as opendirSync13 } from "node:fs";
24147
- import { join as join31 } from "node:path";
24710
+ import { opendirSync as opendirSync14 } from "node:fs";
24711
+ import { join as join33 } from "node:path";
24148
24712
 
24149
24713
  // src/service/conversation-workflow.ts
24150
- import { randomUUID as randomUUID20 } from "node:crypto";
24151
- import { opendirSync as opendirSync10 } from "node:fs";
24152
- import { dirname as dirname17, join as join27 } from "node:path";
24714
+ import { randomUUID as randomUUID21 } from "node:crypto";
24715
+ import { opendirSync as opendirSync11 } from "node:fs";
24716
+ import { dirname as dirname20, join as join29 } from "node:path";
24153
24717
 
24154
24718
  // src/cadence-instructions.ts
24155
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.
@@ -24160,12 +24724,246 @@ Present the returned complete plan and invite a single clear execution approval
24160
24724
  During accepted work answer questions, report actual retained progress, and let the service execute. cadence_cancel is explicit cancellation, not navigation/exit. Never claim a worker's prose is a passing check or automatic review is human review. Failed/unknown/blocked outcomes are not success. A completed goal leaves Cadence ON and ready for the next goal; do not require /cadence again. Unrelated discussion is still ordinary conversation within this mode, not implicit permission to start another implementation. Tools operate on the host; this is not a sandbox.`;
24161
24725
 
24162
24726
  // src/service/conversations.ts
24727
+ import { randomUUID as randomUUID20 } from "node:crypto";
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";
24730
+
24731
+ // src/service/conversation-history.ts
24163
24732
  import { randomUUID as randomUUID19 } from "node:crypto";
24164
- import { lstatSync as lstatSync15, opendirSync as opendirSync9, realpathSync as realpathSync8, statfsSync as statfsSync2 } from "node:fs";
24165
- import { dirname as dirname16, join as join26 } from "node:path";
24733
+ import { lstatSync as lstatSync16, opendirSync as opendirSync9 } from "node:fs";
24734
+ var CONVERSATION_PAGE = 50;
24735
+ var SCAN_ENTRIES = 8;
24736
+ var SCANS = 16;
24737
+ var IDLE_MS = 120000;
24738
+ var compareChats = (a, b) => b.updatedAt - a.updatedAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
24739
+
24740
+ class ConversationHistory {
24741
+ path;
24742
+ directory;
24743
+ summary;
24744
+ scans = new Map;
24745
+ closed = false;
24746
+ constructor(path, directory, summary2) {
24747
+ this.path = path;
24748
+ this.directory = directory;
24749
+ this.summary = summary2;
24750
+ }
24751
+ incarnation() {
24752
+ const st = lstatSync16(this.path, { bigint: true });
24753
+ if (!st.isDirectory() || st.isSymbolicLink())
24754
+ throw new ContractError("corrupt-selected");
24755
+ return `${st.dev}:${st.ino}`;
24756
+ }
24757
+ read(after, cursor) {
24758
+ if (this.closed)
24759
+ throw new ContractError("unavailable");
24760
+ let state;
24761
+ if (cursor) {
24762
+ const selected2 = this.scans.get(cursor);
24763
+ if (!selected2 || selected2.after?.id !== after?.id || selected2.after?.updatedAt !== after?.updatedAt)
24764
+ throw new ContractError("stale");
24765
+ this.scans.delete(cursor);
24766
+ clearTimeout(selected2.timer);
24767
+ state = selected2;
24768
+ } else {
24769
+ if (!this.directory())
24770
+ return { kind: "conversations", entries: [], next: null };
24771
+ if (this.scans.size >= SCANS)
24772
+ throw new ContractError("capacity");
24773
+ const incarnation3 = this.incarnation();
24774
+ state = {
24775
+ dir: opendirSync9(this.path),
24776
+ incarnation: incarnation3,
24777
+ after,
24778
+ entries: []
24779
+ };
24780
+ }
24781
+ let suspended = false;
24782
+ try {
24783
+ if (!this.directory() || this.incarnation() !== state.incarnation)
24784
+ throw new ContractError("stale");
24785
+ const started = performance.now();
24786
+ for (let n = 0;n < SCAN_ENTRIES; n++) {
24787
+ if (n && performance.now() - started >= LIMITS.searchMs)
24788
+ break;
24789
+ const e = state.dir.readSync();
24790
+ if (!e) {
24791
+ const entries2 = state.entries.slice(0, CONVERSATION_PAGE);
24792
+ const last = entries2.at(-1);
24793
+ return {
24794
+ kind: "conversations",
24795
+ entries: entries2,
24796
+ next: state.entries.length > entries2.length && last ? { id: last.id, updatedAt: last.updatedAt } : null
24797
+ };
24798
+ }
24799
+ if (!e.isFile() || !e.name.endsWith(".json"))
24800
+ throw new ContractError("corrupt-selected");
24801
+ const summary2 = this.summary(decodeId(e.name.slice(0, -5)));
24802
+ if (after && compareChats(summary2, after) <= 0)
24803
+ continue;
24804
+ if (state.entries.some((row) => row.id === summary2.id))
24805
+ continue;
24806
+ state.entries.push(summary2);
24807
+ state.entries.sort(compareChats);
24808
+ if (state.entries.length > CONVERSATION_PAGE + 1)
24809
+ state.entries.pop();
24810
+ }
24811
+ const scan = randomUUID19();
24812
+ state.timer = setTimeout(() => {
24813
+ this.scans.delete(scan);
24814
+ try {
24815
+ state.dir.closeSync();
24816
+ } catch {
24817
+ this.closed = true;
24818
+ }
24819
+ }, IDLE_MS);
24820
+ state.timer.unref();
24821
+ this.scans.set(scan, state);
24822
+ suspended = true;
24823
+ return { kind: "conversations-progress", after, scan };
24824
+ } finally {
24825
+ if (!suspended)
24826
+ state.dir.closeSync();
24827
+ }
24828
+ }
24829
+ close() {
24830
+ this.closed = true;
24831
+ let failed = false;
24832
+ for (const state of this.scans.values()) {
24833
+ clearTimeout(state.timer);
24834
+ try {
24835
+ state.dir.closeSync();
24836
+ } catch {
24837
+ failed = true;
24838
+ }
24839
+ }
24840
+ this.scans.clear();
24841
+ if (failed)
24842
+ throw new ContractError("unavailable");
24843
+ }
24844
+ }
24845
+
24846
+ // src/service/conversation-transcript.ts
24847
+ var TRANSCRIPT_PAGE_BYTES = 384 * 1024;
24848
+ var PREVIEW_BYTES = 300 * 1024;
24849
+ var FIELD_CHARS = 16 * 1024;
24850
+ var PREVIEW_MARK = `
24851
+ [Preview only; open the full transcript.]`;
24852
+ function part(value, offset, chars = FIELD_CHARS) {
24853
+ let end = Math.min(value.length, offset + chars);
24854
+ if (end < value.length && /[\uD800-\uDBFF]/u.test(value[end - 1]))
24855
+ end--;
24856
+ return value.slice(offset, end);
24857
+ }
24858
+
24859
+ class ConversationTranscript {
24860
+ turn;
24861
+ write;
24862
+ state = { pages: 0 };
24863
+ workingSizes = new Map;
24864
+ workingBytes = 0;
24865
+ sizes = new Map;
24866
+ bytes = 4096;
24867
+ pending = new Map;
24868
+ constructor(turn, write2) {
24869
+ this.turn = turn;
24870
+ this.write = write2;
24871
+ turn.transcript = this.state;
24872
+ for (const item of [...turn.items]) {
24873
+ this.archive(item);
24874
+ this.preview(item);
24875
+ }
24876
+ }
24877
+ item(id, role2) {
24878
+ let item = this.pending.get(id);
24879
+ if (!item) {
24880
+ if (this.pending.size >= 256)
24881
+ throw new ContractError("capacity");
24882
+ item = { id, role: role2, text: "", name: "", args: "", error: false };
24883
+ this.pending.set(id, item);
24884
+ this.preview(item);
24885
+ }
24886
+ return item;
24887
+ }
24888
+ find(id) {
24889
+ return this.pending.get(id);
24890
+ }
24891
+ preview(item) {
24892
+ if (this.pending.has(item.id)) {
24893
+ const size3 = Buffer.byteLength(item.text) + Buffer.byteLength(item.args) + Buffer.byteLength(item.name);
24894
+ this.workingBytes += size3 - (this.workingSizes.get(item.id) ?? 0);
24895
+ this.workingSizes.set(item.id, size3);
24896
+ if (this.workingBytes > 2 * LIMITS.detailBytes)
24897
+ throw new ContractError("capacity");
24898
+ }
24899
+ const clip = (value) => {
24900
+ const prefix = part(value, 0);
24901
+ return prefix.length < value.length ? prefix + PREVIEW_MARK : value;
24902
+ };
24903
+ const preview = { ...item, text: clip(item.text), args: clip(item.args) };
24904
+ const size2 = Buffer.byteLength(canonicalJson(preview, PREVIEW_BYTES));
24905
+ this.bytes += size2 - (this.sizes.get(item.id) ?? 0);
24906
+ this.sizes.set(item.id, size2);
24907
+ const at = this.turn.items.findIndex((i) => i.id === item.id);
24908
+ if (at < 0)
24909
+ this.turn.items.push(preview);
24910
+ else
24911
+ this.turn.items[at] = preview;
24912
+ while (this.bytes > PREVIEW_BYTES || this.turn.items.length > 128) {
24913
+ if (this.turn.items.length <= 2)
24914
+ throw new ContractError("oversize");
24915
+ const [removed] = this.turn.items.splice(this.turn.items[0].role === "user" ? 1 : 0, 1);
24916
+ this.bytes -= this.sizes.get(removed.id) ?? 0;
24917
+ this.sizes.delete(removed.id);
24918
+ }
24919
+ }
24920
+ complete(id) {
24921
+ const item = this.pending.get(id);
24922
+ if (!item)
24923
+ return;
24924
+ this.preview(item);
24925
+ this.archive(item);
24926
+ this.pending.delete(id);
24927
+ this.workingBytes -= this.workingSizes.get(id) ?? 0;
24928
+ this.workingSizes.delete(id);
24929
+ }
24930
+ finish() {
24931
+ for (const id of this.pending.keys())
24932
+ this.complete(id);
24933
+ }
24934
+ archive(item) {
24935
+ let text2 = 0, args = 0;
24936
+ do {
24937
+ let chars = 128 * 1024;
24938
+ const fragment = { ...item, text: "", args: part(item.args, args) };
24939
+ for (;; ) {
24940
+ fragment.text = part(item.text, text2, chars);
24941
+ try {
24942
+ if (Buffer.byteLength(fragment.text) > 256 * 1024)
24943
+ throw new ContractError("oversize");
24944
+ canonicalJson(fragment, TRANSCRIPT_PAGE_BYTES - 4096);
24945
+ break;
24946
+ } catch (error) {
24947
+ if (!(error instanceof ContractError) || error.code !== "oversize" || chars <= FIELD_CHARS)
24948
+ throw error;
24949
+ chars /= 2;
24950
+ }
24951
+ }
24952
+ const page = this.state.pages;
24953
+ if (!Number.isSafeInteger(page + 1))
24954
+ throw new ContractError("capacity");
24955
+ this.write({ turnId: this.turn.id, page, items: [fragment] });
24956
+ this.state.pages = page + 1;
24957
+ text2 += fragment.text.length;
24958
+ args += fragment.args.length;
24959
+ } while (text2 < item.text.length || args < item.args.length);
24960
+ }
24961
+ }
24962
+
24963
+ // src/service/conversations.ts
24166
24964
  var TURN_BYTES = 384 * 1024;
24167
24965
  var META_BYTES = 64 * 1024;
24168
- var SESSION_LIMIT = 200;
24966
+ var SUMMARY_CACHE = 256;
24169
24967
  var OMITTED_FLAG = {
24170
24968
  "hidden-thinking": "thinking",
24171
24969
  binary: "media",
@@ -24173,7 +24971,7 @@ var OMITTED_FLAG = {
24173
24971
  };
24174
24972
  function observedFile(path) {
24175
24973
  try {
24176
- const s = lstatSync15(path);
24974
+ const s = lstatSync17(path);
24177
24975
  return [s.dev, s.ino, s.size, s.mode, s.nlink, s.ctimeMs, s.mtimeMs].join(":");
24178
24976
  } catch (error) {
24179
24977
  if (error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
@@ -24186,14 +24984,18 @@ class ConversationCapture {
24186
24984
  turn;
24187
24985
  save;
24188
24986
  secrets;
24987
+ transcript;
24189
24988
  details = new Map;
24190
24989
  messageText = new Map;
24191
- constructor(turn, save, secrets) {
24990
+ constructor(turn, save, secrets, transcript) {
24192
24991
  this.turn = turn;
24193
24992
  this.save = save;
24194
24993
  this.secrets = secrets;
24994
+ this.transcript = transcript;
24195
24995
  }
24196
24996
  item(id, role2) {
24997
+ if (this.transcript)
24998
+ return this.transcript.item(id, role2);
24197
24999
  let item = this.turn.items.find((i) => i.id === id);
24198
25000
  if (!item) {
24199
25001
  if (this.turn.items.length >= 256)
@@ -24211,6 +25013,13 @@ class ConversationCapture {
24211
25013
  return item;
24212
25014
  }
24213
25015
  update(item, field, value, maximum) {
25016
+ if (this.transcript) {
25017
+ if (Buffer.byteLength(value) > LIMITS.detailBytes)
25018
+ throw new ContractError("capacity");
25019
+ item[field] = value;
25020
+ this.transcript.preview(item);
25021
+ return;
25022
+ }
24214
25023
  const before = item[field];
24215
25024
  try {
24216
25025
  if (Buffer.byteLength(value) > maximum)
@@ -24240,11 +25049,11 @@ class ConversationCapture {
24240
25049
  if (!d)
24241
25050
  return;
24242
25051
  d.text += e.kind === "detail-chunk" ? d.sanitizer.write(e.text) : d.sanitizer.end();
24243
- if (Buffer.byteLength(d.text) > 256 * 1024)
25052
+ if (Buffer.byteLength(d.text) > (this.transcript ? LIMITS.detailBytes : 256 * 1024))
24244
25053
  throw new ContractError("capacity");
24245
25054
  const o = d.descriptor.owner;
24246
25055
  if (o.kind === "message") {
24247
- const role2 = this.turn.items.find((i) => i.id === o.messageId)?.role;
25056
+ const role2 = (this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId))?.role;
24248
25057
  if (role2 === "assistant" && o.stage === "stream") {
24249
25058
  this.messageText.set(o.blockId, {
24250
25059
  messageId: o.messageId,
@@ -24253,7 +25062,7 @@ class ConversationCapture {
24253
25062
  this.update(this.item(o.messageId, "assistant"), "text", [...this.messageText.values()].filter((block) => block.messageId === o.messageId).map((block) => block.text).join(""), 256 * 1024);
24254
25063
  }
24255
25064
  } else if (o.kind === "message-final") {
24256
- const item = this.turn.items.find((i) => i.id === o.messageId);
25065
+ const item = this.transcript?.find(o.messageId) ?? this.turn.items.find((i) => i.id === o.messageId);
24257
25066
  if (item?.role === "assistant")
24258
25067
  this.update(item, "text", d.text, 256 * 1024);
24259
25068
  } else if (o.kind === "tool") {
@@ -24276,29 +25085,38 @@ class ConversationCapture {
24276
25085
  this.turn.notice = `worker-failure: ${e.code}`;
24277
25086
  else if (e.kind === "omitted-block" && e.block.owner.kind !== "context" && e.block.owner.kind !== "handoff")
24278
25087
  this.turn.omitted[OMITTED_FLAG[e.block.reason]] = true;
24279
- if ([...this.details.values()].reduce((size2, detail) => size2 + Buffer.byteLength(detail.text) + detail.sanitizer.retainedBytes, 0) > TURN_BYTES)
25088
+ if ([...this.details.values()].reduce((size2, detail) => size2 + Buffer.byteLength(detail.text) + detail.sanitizer.retainedBytes, 0) > (this.transcript ? 2 * LIMITS.detailBytes : TURN_BYTES))
24280
25089
  throw new ContractError("capacity");
24281
- canonicalJson(this.turn, TURN_BYTES);
25090
+ if (!this.transcript)
25091
+ canonicalJson(this.turn, TURN_BYTES);
24282
25092
  if (e.kind === "message-end") {
24283
25093
  for (const [id, block] of this.messageText)
24284
25094
  if (block.messageId === e.messageId)
24285
25095
  this.messageText.delete(id);
24286
25096
  }
24287
- if (e.kind === "message-end" || e.kind === "tool-end")
25097
+ if (e.kind === "message-end" || e.kind === "tool-end") {
25098
+ this.transcript?.complete(e.kind === "message-end" ? e.messageId : e.callId);
24288
25099
  this.save();
25100
+ }
24289
25101
  }
24290
25102
  }
24291
25103
 
24292
25104
  class Conversations {
24293
25105
  o;
24294
25106
  root;
25107
+ history;
24295
25108
  cwd;
24296
25109
  active = new Map;
24297
25110
  summaries = new Map;
24298
25111
  constructor(o) {
24299
25112
  this.o = o;
24300
- this.root = join26(o.coordination.directory, "conversations-v1");
24301
- this.cwd = realpathSync8(o.cwd);
25113
+ this.root = join28(o.coordination.directory, "conversations-v1");
25114
+ this.cwd = realpathSync10(o.cwd);
25115
+ const sessions = join28(this.root, "sessions");
25116
+ this.history = new ConversationHistory(sessions, () => {
25117
+ this.o.owner.lease.assert();
25118
+ return this.files.directory(sessions);
25119
+ }, (id) => this.retainedSummary(id));
24302
25120
  }
24303
25121
  currentDirectory() {
24304
25122
  const current2 = resolveWorkspace(this.o.cwd);
@@ -24308,13 +25126,13 @@ class Conversations {
24308
25126
  return this.o.coordination.files;
24309
25127
  }
24310
25128
  path(id, name) {
24311
- return join26(this.root, "turns", decodeId(id), name);
25129
+ return join28(this.root, "turns", decodeId(id), name);
24312
25130
  }
24313
25131
  identityPath(id) {
24314
- return join26(this.root, "identities", `${decodeId(id)}.json`);
25132
+ return join28(this.root, "identities", `${decodeId(id)}.json`);
24315
25133
  }
24316
25134
  metadataPath(id) {
24317
- return join26(this.root, "sessions", `${decodeId(id)}.json`);
25135
+ return join28(this.root, "sessions", `${decodeId(id)}.json`);
24318
25136
  }
24319
25137
  read(path, max) {
24320
25138
  const value = this.files.read(path, max);
@@ -24341,16 +25159,65 @@ class Conversations {
24341
25159
  ]);
24342
25160
  if (identity.schema !== "cadence-conversation/1" || identity.id !== id || identity.cwd !== this.cwd)
24343
25161
  throw new ContractError("corrupt-selected");
24344
- const m = closed(value, ["id", "title", "turns", "checkpoint"]);
25162
+ const indexed = value !== null && typeof value === "object" && Object.hasOwn(value, "count");
25163
+ const m = closed(value, [
25164
+ "id",
25165
+ "title",
25166
+ "turns",
25167
+ "checkpoint",
25168
+ ...indexed ? ["head", "count"] : []
25169
+ ]);
24345
25170
  const turns = list(m.turns, 1000, decodeId);
24346
- if (!turns.length || new Set(turns).size !== turns.length || m.id !== id || m.checkpoint !== null && !turns.includes(decodeId(m.checkpoint)))
25171
+ const count2 = indexed ? integer(m.count, Math.max(1, turns.length)) : turns.length;
25172
+ const head = indexed ? decodeId(m.head) : turns.at(-1);
25173
+ if (!head || !count2 || new Set(turns).size !== turns.length || m.id !== id)
24347
25174
  throw new ContractError("corrupt-selected");
24348
- return {
25175
+ const meta = {
24349
25176
  id,
24350
25177
  title: text(m.title, 512, true),
24351
25178
  turns,
25179
+ head,
25180
+ count: count2,
24352
25181
  checkpoint: m.checkpoint === null ? null : decodeId(m.checkpoint)
24353
25182
  };
25183
+ if (this.turnAt(meta, count2 - 1) !== head || indexed && this.position(meta, head) !== count2 - 1 || meta.checkpoint && !this.contains(meta, meta.checkpoint))
25184
+ throw new ContractError("corrupt-selected");
25185
+ return meta;
25186
+ }
25187
+ slotPath(id, ordinal) {
25188
+ return join28(this.root, "indices", decodeId(id), `${integer(ordinal, 0)}.json`);
25189
+ }
25190
+ turnAt(meta, ordinal) {
25191
+ if (ordinal < 0 || ordinal >= meta.count)
25192
+ throw new ContractError("stale");
25193
+ if (ordinal < meta.turns.length)
25194
+ return meta.turns[ordinal];
25195
+ const row = closed(this.read(this.slotPath(meta.id, ordinal), META_BYTES), [
25196
+ "conversationId",
25197
+ "ordinal",
25198
+ "turnId"
25199
+ ]);
25200
+ if (row.conversationId !== meta.id || row.ordinal !== ordinal)
25201
+ throw new ContractError("corrupt-selected");
25202
+ return decodeId(row.turnId);
25203
+ }
25204
+ position(meta, turnId) {
25205
+ const legacy = meta.turns.indexOf(turnId);
25206
+ if (legacy >= 0)
25207
+ return legacy;
25208
+ const value = this.read(this.path(turnId, "position.json"), META_BYTES);
25209
+ if (value === undefined)
25210
+ return -1;
25211
+ const row = closed(value, ["conversationId", "ordinal", "turnId"]);
25212
+ if (row.turnId !== turnId)
25213
+ throw new ContractError("corrupt-selected");
25214
+ const ordinal = integer(row.ordinal, 0);
25215
+ if (row.conversationId !== meta.id || ordinal >= meta.count)
25216
+ return -1;
25217
+ return this.turnAt(meta, ordinal) === turnId ? ordinal : -1;
25218
+ }
25219
+ contains(meta, turnId) {
25220
+ return this.position(meta, turnId) >= 0;
24354
25221
  }
24355
25222
  turn(id) {
24356
25223
  const live2 = this.active.get(id);
@@ -24364,7 +25231,7 @@ class Conversations {
24364
25231
  } : turn;
24365
25232
  }
24366
25233
  controlBound(id) {
24367
- const path = join26(this.root, "control-links", `${decodeId(id)}.json`);
25234
+ const path = join28(this.root, "control-links", `${decodeId(id)}.json`);
24368
25235
  const value = this.read(path, META_BYTES);
24369
25236
  if (value === undefined)
24370
25237
  return false;
@@ -24374,17 +25241,18 @@ class Conversations {
24374
25241
  return true;
24375
25242
  }
24376
25243
  controlKey(id) {
24377
- return observedFile(join26(this.root, "control-links", `${decodeId(id)}.json`));
25244
+ return observedFile(join28(this.root, "control-links", `${decodeId(id)}.json`));
24378
25245
  }
24379
25246
  bindControl(id) {
24380
25247
  if (!this.controlBound(id))
24381
- 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);
24382
25249
  }
24383
25250
  hasTurn(id, turnId) {
24384
- return this.metadata(id)?.turns.includes(turnId) ?? false;
25251
+ const meta = this.metadata(id);
25252
+ return !!meta && this.contains(meta, turnId);
24385
25253
  }
24386
25254
  summary(meta) {
24387
- const head = meta.turns.at(-1), turn = this.turn(head);
25255
+ const head = meta.head, turn = this.turn(head);
24388
25256
  const accepted2 = closed(this.read(this.path(head, "accepted.json"), META_BYTES), ["command", "at"]);
24389
25257
  const command = decodeWorkbenchCommand(accepted2.command);
24390
25258
  if (command.kind !== "send" || command.commandId !== head || command.conversationId !== meta.id || command.model.epoch !== turn.epoch)
@@ -24397,25 +25265,34 @@ class Conversations {
24397
25265
  updatedAt: integer(accepted2.at, 0)
24398
25266
  };
24399
25267
  }
24400
- headKey(head) {
24401
- return [this.path(head, "turn.json"), this.path(head, "accepted.json")].map(observedFile).join("|");
25268
+ headKey(head, id, count2) {
25269
+ return [
25270
+ this.path(head, "turn.json"),
25271
+ this.path(head, "accepted.json"),
25272
+ this.path(head, "position.json"),
25273
+ this.slotPath(id, count2 - 1)
25274
+ ].map(observedFile).join("|");
24402
25275
  }
24403
25276
  retainedSummary(id) {
24404
25277
  const base = [this.metadataPath(id), this.identityPath(id)].map(observedFile).join("|");
24405
25278
  const hit = this.summaries.get(id);
24406
- if (hit && !this.active.has(hit.summary.head) && hit.key === `${base}|${this.headKey(hit.summary.head)}`)
25279
+ if (hit && !this.active.has(hit.summary.head) && hit.key === `${base}|${this.headKey(hit.summary.head, id, hit.count)}`)
24407
25280
  return { ...hit.summary };
24408
25281
  const meta = this.metadata(id);
24409
25282
  if (!meta)
24410
25283
  throw new ContractError("corrupt-selected");
24411
- const head = meta.turns.at(-1);
24412
- const key2 = `${base}|${this.headKey(head)}`;
25284
+ const head = meta.head;
25285
+ const key2 = `${base}|${this.headKey(head, id, meta.count)}`;
24413
25286
  const summary2 = this.summary(meta);
24414
25287
  this.summaries.delete(id);
24415
25288
  if (!this.active.has(head) && !["queued", "running"].includes(summary2.status)) {
24416
- if (this.summaries.size >= SESSION_LIMIT)
24417
- this.summaries.clear();
24418
- this.summaries.set(id, { key: key2, summary: { ...summary2 } });
25289
+ if (this.summaries.size >= SUMMARY_CACHE)
25290
+ this.summaries.delete(this.summaries.keys().next().value);
25291
+ this.summaries.set(id, {
25292
+ key: key2,
25293
+ summary: { ...summary2 },
25294
+ count: meta.count
25295
+ });
24419
25296
  }
24420
25297
  return summary2;
24421
25298
  }
@@ -24428,35 +25305,36 @@ class Conversations {
24428
25305
  updatedAt: live2.acceptedAt
24429
25306
  };
24430
25307
  }
24431
- list() {
25308
+ list(after = null, scan) {
24432
25309
  this.o.owner.lease.assert();
24433
- const dir = join26(this.root, "sessions");
24434
- if (!this.files.directory(dir))
24435
- return {
24436
- kind: "conversations",
24437
- entries: [...this.active.values()].map((live2) => this.liveSummary(live2))
24438
- };
24439
- const entries2 = [], opened = opendirSync9(dir);
25310
+ return this.history.read(after, scan);
25311
+ }
25312
+ activeConversations() {
25313
+ this.o.owner.lease.assert();
25314
+ return {
25315
+ kind: "conversation-active",
25316
+ entries: [...this.active.values()].map((live2) => this.liveSummary(live2))
25317
+ };
25318
+ }
25319
+ closeReads() {
25320
+ this.history.close();
25321
+ }
25322
+ assertSettled() {
25323
+ this.o.owner.lease.assert();
25324
+ const path = join28(this.root, "sessions");
25325
+ if (!this.files.directory(path))
25326
+ return;
25327
+ const dir = opendirSync10(path);
24440
25328
  try {
24441
- for (let e = opened.readSync();e; e = opened.readSync()) {
24442
- if (!e.isFile() || !e.name.endsWith(".json") || entries2.length >= SESSION_LIMIT)
24443
- throw new ContractError("capacity");
24444
- entries2.push(this.retainedSummary(decodeId(e.name.slice(0, -5))));
25329
+ for (let e = dir.readSync();e; e = dir.readSync()) {
25330
+ if (!e.isFile() || !e.name.endsWith(".json"))
25331
+ throw new ContractError("corrupt-selected");
25332
+ if (this.retainedSummary(decodeId(e.name.slice(0, -5))).status === "unknown")
25333
+ throw new ContractError("quarantine");
24445
25334
  }
24446
25335
  } finally {
24447
- opened.closeSync();
24448
- }
24449
- for (const live2 of this.active.values()) {
24450
- const at = entries2.findIndex((entry) => entry.id === live2.conversationId);
24451
- if (at < 0)
24452
- entries2.push(this.liveSummary(live2));
24453
- else
24454
- entries2[at] = this.liveSummary(live2);
25336
+ dir.closeSync();
24455
25337
  }
24456
- return {
24457
- kind: "conversations",
24458
- entries: entries2.sort((a, b) => b.updatedAt - a.updatedAt)
24459
- };
24460
25338
  }
24461
25339
  view(id, before) {
24462
25340
  this.o.owner.lease.assert();
@@ -24479,13 +25357,13 @@ class Conversations {
24479
25357
  before: null
24480
25358
  };
24481
25359
  }
24482
- let end = before === null ? meta.turns.length : meta.turns.indexOf(before);
25360
+ let end = before === null ? meta.count : this.position(meta, before);
24483
25361
  if (end < 0)
24484
25362
  throw new ContractError("stale");
24485
25363
  const turns = [];
24486
25364
  let bytes = 0;
24487
25365
  while (end > 0 && turns.length < 20) {
24488
- const turn = this.turn(meta.turns[end - 1]), size2 = Buffer.byteLength(canonicalJson(turn, TURN_BYTES));
25366
+ const turn = this.turn(this.turnAt(meta, end - 1)), size2 = Buffer.byteLength(canonicalJson(turn, TURN_BYTES));
24489
25367
  if (bytes + size2 > 400 * 1024)
24490
25368
  break;
24491
25369
  bytes += size2;
@@ -24499,36 +25377,27 @@ class Conversations {
24499
25377
  before: end > 0 ? turns[0].id : null
24500
25378
  };
24501
25379
  }
24502
- capacity() {
24503
- let bytes = 0, count2 = 0;
24504
- const visit = (directory, depth) => {
24505
- if (depth > 4 || !this.files.directory(directory))
24506
- return;
24507
- const dir = opendirSync9(directory);
24508
- try {
24509
- for (let entry = dir.readSync();entry; entry = dir.readSync()) {
24510
- if (++count2 > 1e4)
24511
- throw new ContractError("capacity");
24512
- const path = join26(directory, entry.name);
24513
- if (entry.isDirectory())
24514
- visit(path, depth + 1);
24515
- else if (entry.isFile())
24516
- bytes += lstatSync15(path).size;
24517
- else
24518
- throw new ContractError("corrupt-selected");
24519
- if (bytes + (this.active.size + 1) * (CONTEXT_BYTES + TURN_BYTES + 128 * 1024) > 512 * 1024 * 1024)
24520
- throw new ContractError("capacity");
24521
- }
24522
- } finally {
24523
- dir.closeSync();
24524
- }
25380
+ transcript(id, turnId, page) {
25381
+ this.o.owner.lease.assert();
25382
+ if (!this.hasTurn(id, turnId))
25383
+ throw new ContractError("invalid");
25384
+ const turn = this.turn(turnId);
25385
+ if (!turn.transcript || page >= turn.transcript.pages)
25386
+ throw new ContractError("stale");
25387
+ const record2 = closed(this.read(this.path(turnId, `transcript/${page}.json`), TRANSCRIPT_PAGE_BYTES), ["turnId", "page", "items"]);
25388
+ if (record2.turnId !== turnId || record2.page !== page)
25389
+ throw new ContractError("corrupt-selected");
25390
+ return {
25391
+ kind: "conversation-transcript",
25392
+ conversationId: id,
25393
+ page,
25394
+ turn: decodeChatTurn({ ...turn, items: record2.items })
24525
25395
  };
24526
- visit(this.root, 0);
24527
25396
  }
24528
25397
  attempted(conversationId, commandId) {
24529
25398
  this.o.owner.lease.assert();
24530
25399
  const meta = this.metadata(conversationId);
24531
- return this.active.has(commandId) || this.files.directory(dirname16(this.path(commandId, "accepted.json"))) || !!meta?.turns.includes(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);
24532
25401
  }
24533
25402
  command(input, reply) {
24534
25403
  return {
@@ -24552,7 +25421,7 @@ class Conversations {
24552
25421
  const receipt = this.receipt(input, !!control?.reply);
24553
25422
  if (receipt)
24554
25423
  return receipt;
24555
- if (this.files.directory(dirname16(this.path(input.commandId, "accepted.json"))))
25424
+ if (this.files.directory(dirname19(this.path(input.commandId, "accepted.json"))))
24556
25425
  throw new ContractError("corrupt-selected");
24557
25426
  if (this.o.owner.state !== "idle")
24558
25427
  throw new ContractError("quarantine");
@@ -24568,17 +25437,14 @@ class Conversations {
24568
25437
  this.files.assert(this.metadataPath(input.conversationId), beforeMeta, META_BYTES);
24569
25438
  if (!meta && this.files.read(this.identityPath(input.conversationId), META_BYTES))
24570
25439
  throw new ContractError("corrupt-selected");
24571
- if ((meta?.turns.at(-1) ?? null) !== input.head)
25440
+ if ((meta?.head ?? null) !== input.head)
24572
25441
  throw new ContractError("stale");
24573
25442
  if (meta && this.turn(input.head).status !== "completed" && (!control || ["queued", "running", "unknown"].includes(this.turn(input.head).status)))
24574
25443
  throw new ContractError("conflict");
24575
- if (this.active.size >= 8 || (meta?.turns.length ?? 0) >= 1000 || !meta && this.list().entries.length >= SESSION_LIMIT)
25444
+ if (this.active.size >= 8 || meta && !Number.isSafeInteger(meta.count + 1))
24576
25445
  throw new ContractError("capacity");
24577
25446
  if (!input.text.trim())
24578
25447
  throw new ContractError("invalid");
24579
- if (this.list().entries.some((entry) => entry.status === "unknown"))
24580
- throw new ContractError("quarantine");
24581
- this.capacity();
24582
25448
  const space = statfsSync2(this.o.coordination.directory);
24583
25449
  if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
24584
25450
  throw new ContractError("capacity");
@@ -24603,6 +25469,8 @@ class Conversations {
24603
25469
  id: input.conversationId,
24604
25470
  title: [...command.text.trim()].slice(0, 100).join("") || "Conversation",
24605
25471
  turns: [],
25472
+ head: turn.id,
25473
+ count: 0,
24606
25474
  checkpoint: null
24607
25475
  };
24608
25476
  const previous = next.checkpoint ? this.path(next.checkpoint, "context.json") : null;
@@ -24611,8 +25479,8 @@ class Conversations {
24611
25479
  throw new ContractError("corrupt-selected");
24612
25480
  const abort = new AbortController;
24613
25481
  let begin;
24614
- const ready2 = new Promise((resolve9) => {
24615
- begin = resolve9;
25482
+ const ready2 = new Promise((resolve10) => {
25483
+ begin = resolve10;
24616
25484
  });
24617
25485
  const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort, control));
24618
25486
  const live2 = {
@@ -24633,7 +25501,15 @@ class Conversations {
24633
25501
  this.write(this.identityPath(next.id), { schema: "cadence-conversation/1", id: next.id, cwd: this.cwd }, META_BYTES);
24634
25502
  this.write(this.path(turn.id, "accepted.json"), { command, at: live2.acceptedAt }, META_BYTES);
24635
25503
  live2.turnFile = this.write(this.path(turn.id, "turn.json"), turn, TURN_BYTES);
24636
- next.turns.push(turn.id);
25504
+ const position2 = {
25505
+ conversationId: next.id,
25506
+ ordinal: next.count,
25507
+ turnId: turn.id
25508
+ };
25509
+ this.write(this.slotPath(next.id, next.count), position2, META_BYTES);
25510
+ this.write(this.path(turn.id, "position.json"), position2, META_BYTES);
25511
+ next.head = turn.id;
25512
+ next.count++;
24637
25513
  live2.metaFile = this.write(this.metadataPath(next.id), next, META_BYTES, beforeMeta);
24638
25514
  control?.accept();
24639
25515
  } catch (error) {
@@ -24646,7 +25522,7 @@ class Conversations {
24646
25522
  }
24647
25523
  origin(taskId2) {
24648
25524
  this.o.owner.lease.assert();
24649
- 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);
24650
25526
  if (value === undefined)
24651
25527
  return { kind: "task-origin", taskId: taskId2, conversationId: null };
24652
25528
  const row = closed(value, ["conversationId"]);
@@ -24666,13 +25542,14 @@ class Conversations {
24666
25542
  return;
24667
25543
  }
24668
25544
  const meta = this.metadata(id);
24669
- if (!meta?.turns.includes(turnId))
25545
+ if (!meta || !this.contains(meta, turnId))
24670
25546
  throw new ContractError("invalid");
24671
25547
  if (this.turn(turnId).epoch !== epoch)
24672
25548
  throw new ContractError("stale");
24673
25549
  this.active.get(turnId)?.abort.abort();
24674
25550
  }
24675
25551
  async run(command, turn, previous, previousFile, meta, abort, control) {
25552
+ let transcript;
24676
25553
  let barrier;
24677
25554
  let authSettled;
24678
25555
  let uncertain = false;
@@ -24727,7 +25604,7 @@ class Conversations {
24727
25604
  taskId: meta.id,
24728
25605
  taskKind: control ? "research" : "code",
24729
25606
  runId: turn.id,
24730
- childRunId: randomUUID19(),
25607
+ childRunId: randomUUID20(),
24731
25608
  assignmentId: "conversation",
24732
25609
  purpose: control ? "research" : "edit",
24733
25610
  model: selected2,
@@ -24742,7 +25619,7 @@ class Conversations {
24742
25619
  });
24743
25620
  const auth = this.o.models.prepareTracked({
24744
25621
  request: request3,
24745
- operationId: randomUUID19(),
25622
+ operationId: randomUUID20(),
24746
25623
  epoch: turn.epoch,
24747
25624
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
24748
25625
  signal: abort.signal,
@@ -24760,11 +25637,15 @@ class Conversations {
24760
25637
  save();
24761
25638
  this.write(this.path(turn.id, "launch.json"), { epoch: turn.epoch, childRunId: request3.childRunId }, META_BYTES);
24762
25639
  let credentials = [];
24763
- let checkpoint;
24764
- const capture = new ConversationCapture(turn, save, () => [
24765
- ...this.o.secrets(),
24766
- ...credentials
24767
- ]);
25640
+ let checkpoint = false, contextCount = 0;
25641
+ let contextHead = null;
25642
+ transcript = new ConversationTranscript(turn, (page) => {
25643
+ const space = statfsSync2(this.o.coordination.directory);
25644
+ if (space.bavail * space.bsize - TRANSCRIPT_PAGE_BYTES < LIMITS.freeSpaceFloorBytes)
25645
+ throw new ContractError("capacity");
25646
+ this.write(this.path(turn.id, `transcript/${page.page}.json`), page, TRANSCRIPT_PAGE_BYTES);
25647
+ });
25648
+ const capture = new ConversationCapture(turn, save, () => [...this.o.secrets(), ...credentials], transcript);
24768
25649
  const running = Promise.resolve().then(() => launchConversation(prepared.prepared, {
24769
25650
  previous,
24770
25651
  agentDir: this.o.agentDir,
@@ -24773,8 +25654,21 @@ class Conversations {
24773
25654
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
24774
25655
  ownerSecrets: this.o.secrets,
24775
25656
  onCoordinator: control?.onTool,
24776
- onContext: (messages) => {
24777
- checkpoint = messages;
25657
+ onContext: (message) => {
25658
+ const space = statfsSync2(this.o.coordination.directory);
25659
+ if (space.bavail * space.bsize - CONTEXT_RECORD_BYTES < LIMITS.freeSpaceFloorBytes)
25660
+ throw new ContractError("capacity");
25661
+ const file = this.write(this.path(turn.id, `context-${contextCount}.json`), {
25662
+ schema: "cadence-conversation-message/1",
25663
+ index: contextCount,
25664
+ previous: contextHead,
25665
+ message
25666
+ }, CONTEXT_RECORD_BYTES);
25667
+ contextHead = file.identity;
25668
+ contextCount++;
25669
+ },
25670
+ onContextEnd: () => {
25671
+ checkpoint = true;
24778
25672
  },
24779
25673
  maySignal: () => {
24780
25674
  try {
@@ -24800,7 +25694,11 @@ class Conversations {
24800
25694
  if (result.outcome === "completed") {
24801
25695
  if (!checkpoint)
24802
25696
  throw new ContractError("corrupt-selected");
24803
- this.write(this.path(turn.id, "context.json"), { schema: "cadence-conversation-context/1", messages: checkpoint }, CONTEXT_BYTES);
25697
+ this.write(this.path(turn.id, "context.json"), {
25698
+ schema: "cadence-conversation-context/2",
25699
+ messages: contextCount,
25700
+ head: contextHead
25701
+ }, CONTEXT_BYTES);
24804
25702
  meta.checkpoint = turn.id;
24805
25703
  if (!live2?.metaFile)
24806
25704
  throw new ContractError("corrupt-selected");
@@ -24818,6 +25716,7 @@ class Conversations {
24818
25716
  turn.status = "unknown";
24819
25717
  try {
24820
25718
  this.write(this.path(turn.id, "native.json"), native, META_BYTES);
25719
+ transcript?.finish();
24821
25720
  if (turn.status !== "completed")
24822
25721
  turn.notice = [
24823
25722
  turn.notice,
@@ -24843,8 +25742,7 @@ var BYTES = 384 * 1024;
24843
25742
  var EVIDENCE_BYTES = 16384;
24844
25743
  var SCHEMA = "cadence-conversation-workflow/1";
24845
25744
  var COORDINATORS = 8;
24846
- var RECORDS = 200;
24847
- var RUNS = 200;
25745
+ var RECENT_RUNS = 200;
24848
25746
  var SCAN = 256;
24849
25747
  var INCOMPLETE = "Cadence control state for this conversation is missing, incomplete or unreadable. No mode, plan or run is inferred and nothing was repaired. Start a new conversation; preserve this state for local diagnosis.";
24850
25748
  var UNRECORDED = "The last Cadence message of this conversation was not durably recorded. Its plan is not approvable and nothing was replayed or repaired. Start a new conversation; preserve this state for local diagnosis.";
@@ -24853,14 +25751,14 @@ var PLAN_REFUSALS = {
24853
25751
  stale: "The project, model selection or owner changed while publishing. No plan card was published; ask the user before trying again.",
24854
25752
  conflict: "The current project state conflicts with this plan (for example uncommitted changes in a declared target or its project context). No plan card was published; explain this to the user.",
24855
25753
  forbidden: "The plan contains a protected value or an unsafe path and cannot be shown for approval. No plan card was published.",
24856
- capacity: "Retained workflow capacity is exhausted. No plan card was published.",
25754
+ capacity: "Workflow storage is unavailable. No plan card was published.",
24857
25755
  invalid: "The plan cannot use this delivery policy here (for example local-merge outside an existing Git branch). No plan card was published.",
24858
25756
  oversize: "The plan exceeds its size bounds. No plan card was published.",
24859
25757
  unavailable: "Git or the project state could not be observed. No plan card was published."
24860
25758
  };
24861
25759
  var RESEARCH_REFUSALS = {
24862
25760
  stale: "The project, model selection or owner changed. No investigation started.",
24863
- capacity: "The owner is at its workflow capacity (active or retained runs). No investigation started.",
25761
+ capacity: "The owner has no available workflow slot or storage. No investigation started.",
24864
25762
  forbidden: "The request contains a protected value. No investigation started."
24865
25763
  };
24866
25764
  var refusal3 = (refused2, notice) => ({ refused: refused2, notice });
@@ -24892,10 +25790,10 @@ class ConversationWorkflow {
24892
25790
  grants = new Map;
24893
25791
  constructor(o) {
24894
25792
  this.o = o;
24895
- this.root = join27(o.coordination.directory, "conversation-workflows-v1");
25793
+ this.root = join29(o.coordination.directory, "conversation-workflows-v1");
24896
25794
  }
24897
25795
  path(id) {
24898
- return join27(this.root, decodeId(id), "state.json");
25796
+ return join29(this.root, decodeId(id), "state.json");
24899
25797
  }
24900
25798
  read(id) {
24901
25799
  this.o.owner.lease.assert();
@@ -24904,7 +25802,7 @@ class ConversationWorkflow {
24904
25802
  const bound = this.o.conversations.controlBound(id);
24905
25803
  const file = this.o.coordination.files.read(path, BYTES);
24906
25804
  if (!file)
24907
- 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) };
24908
25806
  const record2 = closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
24909
25807
  "schema",
24910
25808
  "state"
@@ -24941,9 +25839,28 @@ class ConversationWorkflow {
24941
25839
  this.o.owner.lease.assert();
24942
25840
  if (!Number.isSafeInteger(state.revision))
24943
25841
  throw new ContractError("capacity");
24944
- const { notice: _projectionOnly, ...persisted } = state;
25842
+ const { notice: _projectionOnly, ...persisted } = {
25843
+ ...state,
25844
+ runs: state.runs.slice(-RECENT_RUNS)
25845
+ };
24945
25846
  const body = canonicalJson({ schema: SCHEMA, state: decodeCadenceConversation(persisted) }, BYTES);
24946
25847
  try {
25848
+ const prior = file ? decodeCadenceConversation(closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
25849
+ "schema",
25850
+ "state"
25851
+ ]).state).runs : [];
25852
+ for (const [index, runId] of state.runs.entries()) {
25853
+ if (index >= state.runs.length - RECENT_RUNS && prior.includes(runId))
25854
+ continue;
25855
+ const path = this.runLink(runId);
25856
+ const old = this.o.coordination.files.read(path);
25857
+ const value = canonicalJson({ runId, conversationId: state.id });
25858
+ if (old) {
25859
+ if (old.bytes.toString("utf8") !== value)
25860
+ throw new ContractError("conflict");
25861
+ } else
25862
+ this.o.coordination.files.create(path, value);
25863
+ }
24947
25864
  if (file)
24948
25865
  this.o.coordination.files.replace(this.path(state.id), file, body, BYTES);
24949
25866
  else
@@ -24953,23 +25870,6 @@ class ConversationWorkflow {
24953
25870
  throw e;
24954
25871
  }
24955
25872
  }
24956
- records() {
24957
- if (!this.o.coordination.files.directory(this.root))
24958
- return 0;
24959
- const dir = opendirSync10(this.root);
24960
- let entries2 = 0, records = 0;
24961
- try {
24962
- for (let e = dir.readSync();e; e = dir.readSync()) {
24963
- if (++entries2 > SCAN)
24964
- return RECORDS;
24965
- if (e.isDirectory())
24966
- ++records;
24967
- }
24968
- } finally {
24969
- dir.closeSync();
24970
- }
24971
- return records;
24972
- }
24973
25873
  state(id) {
24974
25874
  const loaded = this.read(id);
24975
25875
  if (loaded.transient)
@@ -24997,15 +25897,38 @@ class ConversationWorkflow {
24997
25897
  this.cache.set(id, { key: key2, state: loaded.state });
24998
25898
  return loaded.state;
24999
25899
  }
25900
+ runLink(runId) {
25901
+ return join29(this.o.coordination.directory, "conversations-v1", "workflow-links", `${decodeId(runId)}.json`);
25902
+ }
25000
25903
  links(runIds) {
25001
25904
  this.o.owner.lease.assert();
25002
25905
  const wanted = new Set(runIds), links = [];
25906
+ for (const runId of runIds) {
25907
+ try {
25908
+ const file = this.o.coordination.files.read(this.runLink(runId));
25909
+ if (!file)
25910
+ continue;
25911
+ const row = closed(parseWireJson(file.bytes.toString("utf8")), [
25912
+ "runId",
25913
+ "conversationId"
25914
+ ]);
25915
+ if (row.runId !== runId)
25916
+ continue;
25917
+ const conversationId = decodeId(row.conversationId);
25918
+ if (this.observe(conversationId).notice)
25919
+ continue;
25920
+ links.push({ runId, conversationId });
25921
+ wanted.delete(runId);
25922
+ } catch {
25923
+ this.o.owner.lease.assert();
25924
+ }
25925
+ }
25003
25926
  if (!wanted.size)
25004
25927
  return links;
25005
25928
  try {
25006
25929
  if (!this.o.coordination.files.directory(this.root))
25007
25930
  return links;
25008
- const dir = opendirSync10(this.root);
25931
+ const dir = opendirSync11(this.root);
25009
25932
  try {
25010
25933
  let seen = 0;
25011
25934
  for (let e = dir.readSync();e && seen < SCAN && wanted.size; e = dir.readSync()) {
@@ -25057,14 +25980,14 @@ class ConversationWorkflow {
25057
25980
  }, current2.file);
25058
25981
  } catch {}
25059
25982
  }
25060
- preview(run, bytes, steps) {
25983
+ preview(run2, bytes, steps) {
25061
25984
  const clip = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
25062
25985
  return {
25063
- ...run,
25064
- goal: clip(run.goal, 320),
25065
- notice: clip(run.notice, 512),
25066
- stepsOmitted: Math.max(0, run.steps.length - steps),
25067
- 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) => {
25068
25991
  const text2 = clip(s.text, bytes);
25069
25992
  return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
25070
25993
  })
@@ -25090,8 +26013,6 @@ class ConversationWorkflow {
25090
26013
  throw new ContractError("conflict");
25091
26014
  if (enabled && this.active.size >= COORDINATORS)
25092
26015
  throw new ContractError("capacity");
25093
- if (!file && this.records() >= RECORDS)
25094
- throw new ContractError("capacity");
25095
26016
  const next = {
25096
26017
  id: state.id,
25097
26018
  revision: state.revision + 1,
@@ -25176,7 +26097,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25176
26097
  }
25177
26098
  let published;
25178
26099
  try {
25179
- published = this.o.workflows.command(randomUUID20(), epoch, {
26100
+ published = this.o.workflows.command(randomUUID21(), epoch, {
25180
26101
  action: "propose",
25181
26102
  plan,
25182
26103
  model
@@ -25217,12 +26138,10 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25217
26138
  } catch {
25218
26139
  return refusal3("invalid", "An investigation needs a goal and one or two non-empty questions. Nothing was started.");
25219
26140
  }
25220
- if (current2.state.runs.length >= RUNS)
25221
- return refusal3("capacity", "This conversation reached its retained workflow limit. Nothing was started; continue in a new conversation.");
25222
26141
  const busy = this.o.workflows.activeRuns().runs.filter((r) => r.phase !== "research").map((r) => r.id);
25223
26142
  if (busy.length)
25224
26143
  return refusal3("checkout-busy", `An approved workflow (${busy.join(", ")}) is using this checkout. New investigations start only after it settles; meanwhile discuss recorded evidence or use cadence_status. Nothing was started.`);
25225
- const id = randomUUID20(), conversationId = current2.state.id;
26144
+ const id = randomUUID21(), conversationId = current2.state.id;
25226
26145
  try {
25227
26146
  this.o.workflows.command(id, epoch, {
25228
26147
  action: "research",
@@ -25246,7 +26165,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25246
26165
  }, current2.file);
25247
26166
  const cancel = () => {
25248
26167
  try {
25249
- this.o.workflows.command(randomUUID20(), epoch, {
26168
+ this.o.workflows.command(randomUUID21(), epoch, {
25250
26169
  action: "cancel",
25251
26170
  runId: id
25252
26171
  });
@@ -25265,7 +26184,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25265
26184
  approval(c, caller) {
25266
26185
  if (!caller)
25267
26186
  throw new ContractError("forbidden");
25268
- 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`);
25269
26188
  let effects = true;
25270
26189
  try {
25271
26190
  effects = this.o.owner.state !== "idle";
@@ -25324,7 +26243,7 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25324
26243
  });
25325
26244
  if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
25326
26245
  throw new ContractError("unavailable");
25327
- const g = prepared.response, grant2 = randomUUID20();
26246
+ const g = prepared.response, grant2 = randomUUID21();
25328
26247
  this.grants.set(grant2, {
25329
26248
  caller: canonicalJson(caller),
25330
26249
  revision: c.revision,
@@ -25343,8 +26262,6 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25343
26262
  proposal: g.proposal
25344
26263
  };
25345
26264
  }
25346
- if (state.runs.length >= RUNS)
25347
- throw new ContractError("capacity");
25348
26265
  const grant = this.grants.get(c.grant);
25349
26266
  if (grant && grant.expiresAt < Date.now())
25350
26267
  this.grants.delete(c.grant);
@@ -25391,23 +26308,23 @@ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_st
25391
26308
  }
25392
26309
 
25393
26310
  // src/service/workflows.ts
25394
- import { randomUUID as randomUUID22 } from "node:crypto";
26311
+ import { randomUUID as randomUUID23 } from "node:crypto";
25395
26312
  import {
25396
- lstatSync as lstatSync19,
25397
- opendirSync as opendirSync12,
25398
- realpathSync as realpathSync10,
26313
+ lstatSync as lstatSync21,
26314
+ opendirSync as opendirSync13,
26315
+ realpathSync as realpathSync12,
25399
26316
  rmdirSync,
25400
26317
  statfsSync as statfsSync3,
25401
- writeFileSync as writeFileSync4
26318
+ writeFileSync as writeFileSync5
25402
26319
  } from "node:fs";
25403
- import { basename as basename3, dirname as dirname19, join as join30, resolve as resolve10 } from "node:path";
25404
- 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";
25405
26322
 
25406
26323
  // src/task-diff.ts
25407
- import { spawnSync as spawnSync3 } from "node:child_process";
26324
+ import { spawnSync as spawnSync5 } from "node:child_process";
25408
26325
  import { createHash as createHash24 } from "node:crypto";
25409
- import { lstatSync as lstatSync16, readdirSync as readdirSync3, readlinkSync } from "node:fs";
25410
- 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";
25411
26328
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
25412
26329
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
25413
26330
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -25426,7 +26343,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25426
26343
  if (Date.now() >= deadline)
25427
26344
  outcome = "time budget exhausted";
25428
26345
  else {
25429
- const result = spawnSync3("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
26346
+ const result = spawnSync5("git", gitArguments(["-c", "core.quotepath=true", ...args]), {
25430
26347
  cwd: root,
25431
26348
  encoding: "buffer",
25432
26349
  timeout: Math.max(1, deadline - Date.now()),
@@ -25450,8 +26367,8 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25450
26367
  return;
25451
26368
  }
25452
26369
  try {
25453
- const path = join28(root, name);
25454
- const st = lstatSync16(path);
26370
+ const path = join30(root, name);
26371
+ const st = lstatSync18(path);
25455
26372
  add(name, `${st.mode}:${st.size}`);
25456
26373
  if (st.isSymbolicLink()) {
25457
26374
  add(name, readlinkSync(path));
@@ -25476,7 +26393,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
25476
26393
  limits.push(`Unreadable/changing: ${name}`);
25477
26394
  }
25478
26395
  };
25479
- const probe2 = spawnSync3("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
26396
+ const probe2 = spawnSync5("git", gitArguments(["rev-parse", "--is-inside-work-tree"]), {
25480
26397
  cwd: root,
25481
26398
  env: gitEnvironment(),
25482
26399
  timeout: 3000,
@@ -25591,7 +26508,7 @@ ${data2.toString("utf8")}`);
25591
26508
  return;
25592
26509
  }
25593
26510
  for (const name of names2) {
25594
- const path = join28(dir, name);
26511
+ const path = join30(dir, name);
25595
26512
  const rel = relative8(root, path).split("\\").join("/");
25596
26513
  if (rel === ".git" || admin(rel))
25597
26514
  continue;
@@ -25600,7 +26517,7 @@ ${data2.toString("utf8")}`);
25600
26517
  break;
25601
26518
  }
25602
26519
  try {
25603
- const st = lstatSync16(path);
26520
+ const st = lstatSync18(path);
25604
26521
  if (st.isDirectory())
25605
26522
  walk(path, depth + 1);
25606
26523
  else
@@ -25626,21 +26543,21 @@ ${data2.toString("utf8")}`);
25626
26543
  }
25627
26544
 
25628
26545
  // src/service/workflow-git.ts
25629
- import { spawn as spawn3, spawnSync as spawnSync4 } from "node:child_process";
26546
+ import { spawn as spawn4, spawnSync as spawnSync6 } from "node:child_process";
25630
26547
  import { createHash as createHash25 } from "node:crypto";
25631
26548
  import {
25632
26549
  closeSync as closeSync9,
25633
- constants as constants7,
26550
+ constants as constants8,
25634
26551
  fstatSync as fstatSync6,
25635
- lstatSync as lstatSync17,
26552
+ lstatSync as lstatSync19,
25636
26553
  openSync as openSync9,
25637
26554
  readdirSync as readdirSync4,
25638
26555
  readlinkSync as readlinkSync2,
25639
26556
  readSync as readSync5,
25640
- realpathSync as realpathSync9
26557
+ realpathSync as realpathSync11
25641
26558
  } from "node:fs";
25642
26559
  import { lstat, open as open2, readdir, readlink } from "node:fs/promises";
25643
- 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";
25644
26561
  var NAMES_BYTES = 64 * 1024 * 1024;
25645
26562
  var SYNC_MS = 30000;
25646
26563
  var READ_MS = 120000;
@@ -25656,7 +26573,7 @@ class WorkflowRefusal extends ContractError {
25656
26573
  }
25657
26574
  }
25658
26575
  function gitRead(cwd, args) {
25659
- const r = spawnSync4("git", gitArguments(args), {
26576
+ const r = spawnSync6("git", gitArguments(args), {
25660
26577
  cwd,
25661
26578
  env: gitEnvironment(),
25662
26579
  encoding: "utf8",
@@ -25669,7 +26586,7 @@ function gitRead(cwd, args) {
25669
26586
  return r.stdout;
25670
26587
  }
25671
26588
  function gitAnswer(cwd, args) {
25672
- const r = spawnSync4("git", gitArguments(args), {
26589
+ const r = spawnSync6("git", gitArguments(args), {
25673
26590
  cwd,
25674
26591
  env: gitEnvironment(),
25675
26592
  encoding: "utf8",
@@ -25683,7 +26600,7 @@ function gitAnswer(cwd, args) {
25683
26600
  }
25684
26601
  function gitRun(cwd, args, timeoutMs = READ_MS) {
25685
26602
  return new Promise((done, fail2) => {
25686
- const child = spawn3("git", gitArguments(args), {
26603
+ const child = spawn4("git", gitArguments(args), {
25687
26604
  cwd,
25688
26605
  env: gitEnvironment(),
25689
26606
  stdio: ["ignore", "pipe", "ignore"],
@@ -25726,19 +26643,19 @@ async function gitHead(cwd) {
25726
26643
  }
25727
26644
  function contains2(root, path) {
25728
26645
  const within = relative9(root, path);
25729
- return !within || !within.startsWith(`..${sep6}`) && within !== ".." && !isAbsolute9(within);
26646
+ return !within || !within.startsWith(`..${sep7}`) && within !== ".." && !isAbsolute10(within);
25730
26647
  }
25731
26648
  function nested(a, b) {
25732
26649
  return contains2(a, b) || contains2(b, a);
25733
26650
  }
25734
26651
  function safeWorkflowFile(cwd, name) {
25735
26652
  workflowPath(name);
25736
- const p = resolve9(cwd, name);
26653
+ const p = resolve10(cwd, name);
25737
26654
  if (relative9(cwd, p).startsWith(".."))
25738
26655
  throw new ContractError("forbidden");
25739
- safeDirectory(dirname18(p));
26656
+ safeDirectory(dirname21(p));
25740
26657
  try {
25741
- const st = lstatSync17(p);
26658
+ const st = lstatSync19(p);
25742
26659
  if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
25743
26660
  throw new ContractError("forbidden");
25744
26661
  } catch (e) {
@@ -25749,12 +26666,12 @@ function safeWorkflowFile(cwd, name) {
25749
26666
  }
25750
26667
  function declaredTarget(cwd, name) {
25751
26668
  workflowPath(name);
25752
- const p = resolve9(cwd, name);
26669
+ const p = resolve10(cwd, name);
25753
26670
  if (relative9(cwd, p).startsWith(".."))
25754
26671
  throw new ContractError("forbidden");
25755
- safeDirectory(dirname18(p));
26672
+ safeDirectory(dirname21(p));
25756
26673
  try {
25757
- const st = lstatSync17(p);
26674
+ const st = lstatSync19(p);
25758
26675
  if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory() || st.isFile() && st.nlink !== 1)
25759
26676
  throw new ContractError("forbidden");
25760
26677
  } catch (e) {
@@ -25780,7 +26697,7 @@ function fileIdentity(p, st, hashBytes) {
25780
26697
  return quick;
25781
26698
  let fd;
25782
26699
  try {
25783
- fd = openSync9(p, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
26700
+ fd = openSync9(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
25784
26701
  } catch (e) {
25785
26702
  if (absent2(e))
25786
26703
  return null;
@@ -25805,7 +26722,7 @@ async function fileIdentityAsync(p, st, hashBytes) {
25805
26722
  return quick;
25806
26723
  let handle;
25807
26724
  try {
25808
- handle = await open2(p, constants7.O_RDONLY | (constants7.O_NOFOLLOW ?? 0));
26725
+ handle = await open2(p, constants8.O_RDONLY | (constants8.O_NOFOLLOW ?? 0));
25809
26726
  } catch (e) {
25810
26727
  if (absent2(e))
25811
26728
  return null;
@@ -25834,8 +26751,8 @@ function directoryIdentity(root, name) {
25834
26751
  continue;
25835
26752
  if (++count2 > DIRECTORY_ENTRIES)
25836
26753
  throw tooLarge(name);
25837
- const full = join29(directory, entry), relative10 = `${prefix}${entry}`;
25838
- const st = lstatSync17(full);
26754
+ const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
26755
+ const st = lstatSync19(full);
25839
26756
  if (st.isDirectory()) {
25840
26757
  rows.push(`${relative10}/`);
25841
26758
  visit(full, `${relative10}/`);
@@ -25856,7 +26773,7 @@ async function directoryIdentityAsync(root, name) {
25856
26773
  continue;
25857
26774
  if (++count2 > DIRECTORY_ENTRIES)
25858
26775
  throw tooLarge(name);
25859
- const full = join29(directory, entry), relative10 = `${prefix}${entry}`;
26776
+ const full = join31(directory, entry), relative10 = `${prefix}${entry}`;
25860
26777
  const st = await lstat(full);
25861
26778
  if (st.isDirectory()) {
25862
26779
  rows.push(`${relative10}/`);
@@ -25870,12 +26787,12 @@ async function directoryIdentityAsync(root, name) {
25870
26787
  `))}`;
25871
26788
  }
25872
26789
  function pathIdentity(cwd, name, walk = true) {
25873
- const p = resolve9(cwd, name);
26790
+ const p = resolve10(cwd, name);
25874
26791
  if (relative9(cwd, p).startsWith(".."))
25875
26792
  throw new ContractError("forbidden");
25876
26793
  let st;
25877
26794
  try {
25878
- st = lstatSync17(p);
26795
+ st = lstatSync19(p);
25879
26796
  } catch (e) {
25880
26797
  if (absent2(e))
25881
26798
  return null;
@@ -25886,7 +26803,7 @@ function pathIdentity(cwd, name, walk = true) {
25886
26803
  return fileIdentity(p, st, HASH_BYTES);
25887
26804
  }
25888
26805
  async function pathIdentityAsync(cwd, name) {
25889
- const p = resolve9(cwd, name);
26806
+ const p = resolve10(cwd, name);
25890
26807
  if (relative9(cwd, p).startsWith(".."))
25891
26808
  throw new ContractError("forbidden");
25892
26809
  let st;
@@ -26090,20 +27007,20 @@ ${block}
26090
27007
  async function assertWorktree(root, cwd) {
26091
27008
  if (!safeDirectory(cwd))
26092
27009
  throw new ContractError("stale");
26093
- const real = (p) => realpathSync9(resolve9(p));
27010
+ const real = (p) => realpathSync11(resolve10(p));
26094
27011
  if (real((await gitText(cwd, ["rev-parse", "--show-toplevel"])).trim()) !== real(cwd))
26095
27012
  throw new ContractError("stale");
26096
- 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()));
26097
27014
  if (await common(root) !== await common(cwd))
26098
27015
  throw new ContractError("stale");
26099
- const marker2 = resolve9(cwd, ".git");
26100
- if (!lstatSync17(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: "))
26101
27018
  throw new ContractError("stale");
26102
27019
  }
26103
27020
 
26104
27021
  // src/service/workflow-history.ts
26105
- import { randomUUID as randomUUID21 } from "node:crypto";
26106
- import { lstatSync as lstatSync18, opendirSync as opendirSync11 } from "node:fs";
27022
+ import { randomUUID as randomUUID22 } from "node:crypto";
27023
+ import { lstatSync as lstatSync20, opendirSync as opendirSync12 } from "node:fs";
26107
27024
  class WorkflowHistoryScanner {
26108
27025
  path;
26109
27026
  directory;
@@ -26114,7 +27031,7 @@ class WorkflowHistoryScanner {
26114
27031
  this.directory = directory;
26115
27032
  }
26116
27033
  incarnation() {
26117
- const st = lstatSync18(this.path, { bigint: true });
27034
+ const st = lstatSync20(this.path, { bigint: true });
26118
27035
  if (!st.isDirectory() || st.isSymbolicLink())
26119
27036
  throw new ContractError("corrupt-selected");
26120
27037
  return `${st.dev}:${st.ino}`;
@@ -26140,7 +27057,7 @@ class WorkflowHistoryScanner {
26140
27057
  if (this.scans.size >= WORKFLOW_LIMITS.historyScans)
26141
27058
  throw new ContractError("capacity");
26142
27059
  const incarnation3 = this.incarnation();
26143
- state = { dir: opendirSync11(this.path), incarnation: incarnation3, after, ids: [] };
27060
+ state = { dir: opendirSync12(this.path), incarnation: incarnation3, after, ids: [] };
26144
27061
  }
26145
27062
  let suspended = false;
26146
27063
  try {
@@ -26166,7 +27083,7 @@ class WorkflowHistoryScanner {
26166
27083
  if (state.ids.length > WORKFLOW_LIMITS.historyPage + 1)
26167
27084
  state.ids.pop();
26168
27085
  }
26169
- const scan = randomUUID21();
27086
+ const scan = randomUUID22();
26170
27087
  state.timer = setTimeout(() => {
26171
27088
  this.scans.delete(scan);
26172
27089
  try {
@@ -26203,9 +27120,9 @@ class WorkflowHistoryScanner {
26203
27120
 
26204
27121
  // src/service/workflows.ts
26205
27122
  var OWNER_RUNTIME = Object.freeze({
26206
- version: "2.0.27",
26207
- build: "8ef1833b9806c52b446f2864252a2cd50eb71fef901da32dcd35aee988c4775c",
26208
- entry: fileURLToPath5(import.meta.url),
27123
+ version: "2.0.29",
27124
+ build: "159ebb3ba7182c899b19bd0e5349d74397c5f1bbb6ae29dc9f03848edd457b24",
27125
+ entry: fileURLToPath6(import.meta.url),
26209
27126
  pid: process.pid,
26210
27127
  node: process.versions.node,
26211
27128
  platform: process.platform,
@@ -26391,12 +27308,12 @@ class Workflows {
26391
27308
  grants = new Map;
26392
27309
  constructor(o) {
26393
27310
  this.o = o;
26394
- this.root = join30(o.coordination.directory, "workflows-v1");
26395
- this.cwd = realpathSync10(o.coordination.store.root);
26396
- this.worktreeRoot = join30(o.coordination.stateHome, "cadence-worktrees-v1", basename3(o.coordination.store.privateRoot));
26397
- 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"), () => {
26398
27315
  this.o.owner.lease.assert();
26399
- return this.files.directory(join30(this.root, "runs"));
27316
+ return this.files.directory(join32(this.root, "runs"));
26400
27317
  });
26401
27318
  this.recover();
26402
27319
  }
@@ -26404,7 +27321,7 @@ class Workflows {
26404
27321
  return this.o.coordination.files;
26405
27322
  }
26406
27323
  path(id, name) {
26407
- return join30(this.root, "runs", decodeId(id), name);
27324
+ return join32(this.root, "runs", decodeId(id), name);
26408
27325
  }
26409
27326
  write(path, value, expected, max = RECORD_BYTES2) {
26410
27327
  this.o.owner.lease.assert();
@@ -26421,11 +27338,11 @@ class Workflows {
26421
27338
  `), 2048, this.o.secrets());
26422
27339
  }
26423
27340
  recover() {
26424
- const runs = join30(this.root, "runs");
27341
+ const runs = join32(this.root, "runs");
26425
27342
  if (!this.files.directory(runs))
26426
27343
  return;
26427
27344
  const ids = [];
26428
- const dir = opendirSync12(runs);
27345
+ const dir = opendirSync13(runs);
26429
27346
  try {
26430
27347
  for (let e = dir.readSync();e; e = dir.readSync()) {
26431
27348
  if (!e.isDirectory())
@@ -26456,7 +27373,7 @@ class Workflows {
26456
27373
  const accepted2 = this.retained(this.path(id, "accepted.json"));
26457
27374
  if (!accepted2)
26458
27375
  return;
26459
- let run2;
27376
+ let run3;
26460
27377
  try {
26461
27378
  const o = closed(parseWireJson(accepted2.bytes.toString("utf8"), RECORD_BYTES2), ["epoch", "request"]);
26462
27379
  const request3 = decodeWorkflowRequest(o.request);
@@ -26465,7 +27382,7 @@ class Workflows {
26465
27382
  try {
26466
27383
  goal = this.proposal(request3.proposalId).plan.goal;
26467
27384
  } catch {}
26468
- run2 = {
27385
+ run3 = {
26469
27386
  id,
26470
27387
  epoch: decodeId(o.epoch),
26471
27388
  goal,
@@ -26479,30 +27396,30 @@ class Workflows {
26479
27396
  } catch {
26480
27397
  return;
26481
27398
  }
26482
- this.write(path, run2);
27399
+ this.write(path, run3);
26483
27400
  return;
26484
27401
  }
26485
- let run;
27402
+ let run2;
26486
27403
  try {
26487
- run = decodeWorkflowRun(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
27404
+ run2 = decodeWorkflowRun(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
26488
27405
  } catch {
26489
27406
  return;
26490
27407
  }
26491
- 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")
26492
27409
  return;
26493
- const integrating = run.phase === "integrating";
26494
- run.status = "unknown";
26495
- run.phase = "finished";
26496
- 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)
26497
27414
  if (step.status === "running")
26498
27415
  step.status = "unknown";
26499
- run.notice = diagnosticText([
26500
- run.notice,
27416
+ run2.notice = diagnosticText([
27417
+ run2.notice,
26501
27418
  RESTARTED,
26502
27419
  integrating ? "Integration had started: inspect the target branch; a fast-forward may have completed." : ""
26503
27420
  ].filter(Boolean).join(`
26504
27421
  `), 2048);
26505
- this.write(path, run, file);
27422
+ this.write(path, run2, file);
26506
27423
  }
26507
27424
  current() {
26508
27425
  this.o.owner.lease.assert();
@@ -26532,7 +27449,7 @@ class Workflows {
26532
27449
  };
26533
27450
  }
26534
27451
  proposal(id) {
26535
- 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);
26536
27453
  if (!file)
26537
27454
  throw new ContractError("unavailable");
26538
27455
  return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
@@ -26554,9 +27471,9 @@ class Workflows {
26554
27471
  this.o.owner.lease.assert();
26555
27472
  return {
26556
27473
  kind: "workflow-active",
26557
- runs: [...this.active.values()].map(({ run }) => ({
26558
- ...structuredClone(run),
26559
- goal: clipUnits(run.goal, 320),
27474
+ runs: [...this.active.values()].map(({ run: run2 }) => ({
27475
+ ...structuredClone(run2),
27476
+ goal: clipUnits(run2.goal, 320),
26560
27477
  steps: []
26561
27478
  }))
26562
27479
  };
@@ -26571,13 +27488,13 @@ class Workflows {
26571
27488
  const view = this.view(id);
26572
27489
  if (view.kind !== "workflow" || view.response.type !== "run")
26573
27490
  throw new ContractError("invalid");
26574
- const run = view.response.run;
27491
+ const run2 = view.response.run;
26575
27492
  return {
26576
27493
  id,
26577
27494
  run: {
26578
- ...run,
26579
- goal: clipUnits(sanitizeText(run.goal, this.o.secrets()), 320),
26580
- notice: this.notice(run.notice),
27495
+ ...run2,
27496
+ goal: clipUnits(sanitizeText(run2.goal, this.o.secrets()), 320),
27497
+ notice: this.notice(run2.notice),
26581
27498
  steps: []
26582
27499
  }
26583
27500
  };
@@ -26603,27 +27520,27 @@ class Workflows {
26603
27520
  const file = live2 ? undefined : this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
26604
27521
  if (!live2 && !file)
26605
27522
  throw new ContractError("unavailable");
26606
- const run = decodeWorkflowRun(live2 ? live2.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
26607
- 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)
26608
27525
  throw new ContractError("corrupt-selected");
26609
- if (!live2 && ["running", "queued"].includes(run.status))
26610
- run.status = "unknown";
27526
+ if (!live2 && ["running", "queued"].includes(run2.status))
27527
+ run2.status = "unknown";
26611
27528
  return {
26612
27529
  kind: "workflow",
26613
27530
  commandId: null,
26614
- response: { type: "run", run }
27531
+ response: { type: "run", run: run2 }
26615
27532
  };
26616
27533
  }
26617
27534
  transcript(id, stepId) {
26618
27535
  const view = this.view(id);
26619
27536
  if (view.kind !== "workflow" || view.response.type !== "run")
26620
27537
  throw new ContractError("unavailable");
26621
- 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);
26622
27539
  if (!step?.childRunId)
26623
27540
  throw new ContractError("unavailable");
26624
27541
  const file = this.files.read(this.path(id, `transcripts/${step.childRunId}.json`), RECORD_BYTES2);
26625
27542
  const turn = file ? decodeChatTurn(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2)) : null;
26626
- if (turn && (turn.id !== step.childRunId || turn.epoch !== run.epoch))
27543
+ if (turn && (turn.id !== step.childRunId || turn.epoch !== run2.epoch))
26627
27544
  throw new ContractError("corrupt-selected");
26628
27545
  if (turn) {
26629
27546
  const secrets = this.o.secrets();
@@ -26686,8 +27603,8 @@ class Workflows {
26686
27603
  if (action === "prepare")
26687
27604
  return [...this.grants.values()].some((g) => g.commandId === id && g.expiresAt >= Date.now());
26688
27605
  if (action === "propose")
26689
- return !!this.files.read(join30(this.root, "proposals", `${id}.json`), RECORD_BYTES2);
26690
- 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));
26691
27608
  }
26692
27609
  admit(commandId, epoch, r, effect) {
26693
27610
  this.current();
@@ -26716,7 +27633,7 @@ class Workflows {
26716
27633
  };
26717
27634
  if (sanitizeData(p, secrets) !== canonicalJson(p))
26718
27635
  throw new ContractError("forbidden");
26719
- const target3 = join30(this.root, "proposals", `${commandId}.json`);
27636
+ const target3 = join32(this.root, "proposals", `${commandId}.json`);
26720
27637
  const previous = this.files.read(target3, RECORD_BYTES2);
26721
27638
  if (previous) {
26722
27639
  if (previous.bytes.toString("utf8") !== canonicalJson(p))
@@ -26739,7 +27656,7 @@ class Workflows {
26739
27656
  this.grants.delete(key2);
26740
27657
  if (this.grants.size >= 16)
26741
27658
  throw new ContractError("capacity");
26742
- const grant = randomUUID22(), expiresAt = Date.now() + 120000;
27659
+ const grant = randomUUID23(), expiresAt = Date.now() + 120000;
26743
27660
  effect();
26744
27661
  this.grants.set(grant, {
26745
27662
  commandId,
@@ -26767,7 +27684,7 @@ class Workflows {
26767
27684
  throw new ContractError("conflict");
26768
27685
  return { ...this.view(commandId), commandId };
26769
27686
  }
26770
- if (this.files.directory(dirname19(acceptedPath)))
27687
+ if (this.files.directory(dirname22(acceptedPath)))
26771
27688
  throw new ContractError("quarantine");
26772
27689
  let proposal;
26773
27690
  let target2;
@@ -26795,7 +27712,7 @@ class Workflows {
26795
27712
  this.capacity();
26796
27713
  } else
26797
27714
  throw new ContractError("invalid");
26798
- const run = {
27715
+ const run2 = {
26799
27716
  id: commandId,
26800
27717
  epoch,
26801
27718
  goal: proposal?.plan.goal ?? (request3.action === "research" ? request3.goal : ""),
@@ -26817,11 +27734,11 @@ class Workflows {
26817
27734
  };
26818
27735
  const abort = new AbortController;
26819
27736
  let begin;
26820
- const ready2 = new Promise((resolve11) => {
26821
- begin = resolve11;
27737
+ const ready2 = new Promise((resolve12) => {
27738
+ begin = resolve12;
26822
27739
  });
26823
27740
  const live2 = {
26824
- run,
27741
+ run: run2,
26825
27742
  abort,
26826
27743
  original: ready2.then(() => this.execute(live2, request3)),
26827
27744
  proposal,
@@ -26835,7 +27752,7 @@ class Workflows {
26835
27752
  this.o.owner.trackConversation(live2.original, () => abort.abort());
26836
27753
  try {
26837
27754
  this.write(acceptedPath, { epoch, request: request3 });
26838
- live2.file = this.write(this.path(commandId, "state.json"), run);
27755
+ live2.file = this.write(this.path(commandId, "state.json"), run2);
26839
27756
  } catch (e) {
26840
27757
  abort.abort();
26841
27758
  begin();
@@ -26845,7 +27762,7 @@ class Workflows {
26845
27762
  return {
26846
27763
  kind: "workflow",
26847
27764
  commandId,
26848
- response: { type: "run", run: structuredClone(run) }
27765
+ response: { type: "run", run: structuredClone(run2) }
26849
27766
  };
26850
27767
  }
26851
27768
  capacity() {
@@ -26881,7 +27798,7 @@ class Workflows {
26881
27798
  if (live2.run.steps.length >= MAX_STEPS)
26882
27799
  throw new ContractError("capacity");
26883
27800
  const s = {
26884
- id: `${clipUnits(id, STEP_UNITS)}-${randomUUID22()}`,
27801
+ id: `${clipUnits(id, STEP_UNITS)}-${randomUUID23()}`,
26885
27802
  ...childRunId ? { childRunId } : {},
26886
27803
  kind,
26887
27804
  ...childRunId ? {
@@ -26950,7 +27867,7 @@ class Workflows {
26950
27867
  throw new ContractError("unavailable");
26951
27868
  if (cwd !== this.cwd)
26952
27869
  await assertWorktree(this.cwd, cwd);
26953
- const childRunId = randomUUID22(), op = randomUUID22();
27870
+ const childRunId = randomUUID23(), op = randomUUID23();
26954
27871
  const plan = live2.proposal?.plan;
26955
27872
  const request3 = decodeWorkerPublicRequest({
26956
27873
  protocol: 2,
@@ -27027,7 +27944,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27027
27944
  const running = Promise.resolve().then(() => launchWorkflowWorker(prepared.prepared, cwd, live2.abort.signal, {
27028
27945
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
27029
27946
  ownerSecrets: this.o.secrets(),
27030
- roots: roots?.length ? roots.map((p) => resolve10(cwd, p)) : [cwd],
27947
+ roots: roots?.length ? roots.map((p) => resolve11(cwd, p)) : [cwd],
27031
27948
  onLifecycle: (event) => {
27032
27949
  if (!step.timing)
27033
27950
  return;
@@ -27108,7 +28025,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27108
28025
  const shell = "check" in operation;
27109
28026
  if (cwd !== this.cwd && shell)
27110
28027
  await assertWorktree(this.cwd, cwd);
27111
- const id = randomUUID22();
28028
+ const id = randomUUID23();
27112
28029
  this.write(this.path(live2.run.id, `operations/${id}-intent.json`), {
27113
28030
  cwd,
27114
28031
  args: shell ? operation.check : operation.git
@@ -27122,7 +28039,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27122
28039
  command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
27123
28040
  args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${operation.check.command}"`] : ["-c", operation.check.command] : gitArguments([
27124
28041
  "-c",
27125
- `core.hooksPath=${join30(this.root, "empty-hooks")}`,
28042
+ `core.hooksPath=${join32(this.root, "empty-hooks")}`,
27126
28043
  "-c",
27127
28044
  "commit.gpgsign=false",
27128
28045
  "-c",
@@ -27264,7 +28181,7 @@ Read applicable AGENTS.md, existing project conventions and relevant tests befor
27264
28181
  async review(live2, cwd, p) {
27265
28182
  live2.run.phase = "reviewing";
27266
28183
  this.save(live2);
27267
- const { result, step } = await this.worker(live2, cwd, `review-${randomUUID22()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
28184
+ const { result, step } = await this.worker(live2, cwd, `review-${randomUUID23()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
27268
28185
  Files: ${p.plan.tasks.flatMap((t) => t.writes).join(", ")}`, true, p.model);
27269
28186
  this.success(result);
27270
28187
  const verdict = reviewVerdict(result.text);
@@ -27359,9 +28276,9 @@ ${changed.map((p) => `- ${p}`).join(`
27359
28276
  publish(live2, cwd, plan, names3, changed) {
27360
28277
  for (const name of names3) {
27361
28278
  const file = safeWorkflowFile(cwd, name);
27362
- if (!safeDirectory(dirname19(file), true))
28279
+ if (!safeDirectory(dirname22(file), true))
27363
28280
  throw new ContractError("forbidden");
27364
- writeFileSync4(file, this.documentBody(live2, cwd, plan, name, changed), {
28281
+ writeFileSync5(file, this.documentBody(live2, cwd, plan, name, changed), {
27365
28282
  flag: name === ".cadence/project.md" ? "w" : "wx"
27366
28283
  });
27367
28284
  }
@@ -27369,17 +28286,17 @@ ${changed.map((p) => `- ${p}`).join(`
27369
28286
  worktreeHome(id) {
27370
28287
  if (nested(this.cwd, this.worktreeRoot))
27371
28288
  throw new ContractError("unsupported-context");
27372
- for (const directory of [dirname19(this.worktreeRoot), this.worktreeRoot]) {
28289
+ for (const directory of [dirname22(this.worktreeRoot), this.worktreeRoot]) {
27373
28290
  if (!safeDirectory(directory, true))
27374
28291
  throw new ContractError("forbidden");
27375
- const st = lstatSync19(directory);
28292
+ const st = lstatSync21(directory);
27376
28293
  if (process.platform !== "win32" && ((st.mode & 63) !== 0 || process.getuid && st.uid !== process.getuid()))
27377
28294
  throw new ContractError("forbidden");
27378
28295
  }
27379
- const home = join30(this.worktreeRoot, decodeId(id));
28296
+ const home = join32(this.worktreeRoot, decodeId(id));
27380
28297
  if (safeDirectory(home))
27381
28298
  throw new ContractError("conflict");
27382
- safeDirectory(join30(home, "tasks"), true);
28299
+ safeDirectory(join32(home, "tasks"), true);
27383
28300
  return home;
27384
28301
  }
27385
28302
  async merge(live2, candidate) {
@@ -27447,7 +28364,7 @@ ${result.output}`}`);
27447
28364
  } finally {
27448
28365
  this.closeStep(live2, step);
27449
28366
  }
27450
- for (const directory of [join30(home, "tasks"), home])
28367
+ for (const directory of [join32(home, "tasks"), home])
27451
28368
  try {
27452
28369
  rmdirSync(directory);
27453
28370
  } catch {}
@@ -27479,8 +28396,8 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
27479
28396
  throw new ContractError("invalid");
27480
28397
  const base = target2.head;
27481
28398
  const home = this.worktreeHome(live2.run.id);
27482
- const taskHome = join30(home, "tasks");
27483
- const integration = join30(home, "integration");
28399
+ const taskHome = join32(home, "tasks");
28400
+ const integration = join32(home, "integration");
27484
28401
  await this.gitStep(live2, this.cwd, "worktree-integration", (git) => git(["worktree", "add", "--detach", integration, base]));
27485
28402
  await assertWorktree(this.cwd, integration);
27486
28403
  await this.setup(live2, integration, plan);
@@ -27497,7 +28414,7 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
27497
28414
  live2.run.phase = "implementing";
27498
28415
  this.save(live2);
27499
28416
  const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
27500
- const cwd = join30(taskHome, task.id);
28417
+ const cwd = join32(taskHome, task.id);
27501
28418
  await this.gitStep(live2, this.cwd, `worktree-${task.id}`, (git) => git(["worktree", "add", "--detach", cwd, base]));
27502
28419
  const picks2 = workflowAncestors(plan.tasks, task.id).map((dep) => commits.get(dep.id)).filter((c) => !!c);
27503
28420
  if (picks2.length)
@@ -27562,9 +28479,9 @@ Write only these exact files: ${task.writes.join(", ")} (a declared directory in
27562
28479
  const file = safeWorkflowFile(this.cwd, name), before = documentBefore.get(name) ?? null;
27563
28480
  if (before !== pathIdentity(this.cwd, name))
27564
28481
  throw new WorkflowRefusal("conflict", `${name} changed during the run; the generated note was not written.`);
27565
- if (!safeDirectory(dirname19(file), true))
28482
+ if (!safeDirectory(dirname22(file), true))
27566
28483
  throw new ContractError("unavailable");
27567
- 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" });
27568
28485
  }
27569
28486
  if (!await this.checks(live2, this.cwd, plan))
27570
28487
  throw new Error("Local merge completed, but post-merge checks failed. No reset or rollback was attempted.");
@@ -27675,13 +28592,16 @@ class Workbench {
27675
28592
  conversations: this.conversations,
27676
28593
  workflows: this.workflows
27677
28594
  });
27678
- if (this.conversations.list().entries.some((entry) => entry.status === "unknown"))
27679
- throw new ContractError("quarantine");
28595
+ this.conversations.assertSettled();
27680
28596
  this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
27681
- this.projectRoot = join31(o.coordination.files.namespace, "workbench-projects-v1");
28597
+ this.projectRoot = join33(o.coordination.files.namespace, "workbench-projects-v1");
27682
28598
  }
27683
28599
  closeReads() {
27684
- this.workflows.closeHistory();
28600
+ try {
28601
+ this.workflows.closeHistory();
28602
+ } finally {
28603
+ this.conversations.closeReads();
28604
+ }
27685
28605
  }
27686
28606
  read(value) {
27687
28607
  const request3 = decodeWorkbenchRead(value);
@@ -27693,7 +28613,7 @@ class Workbench {
27693
28613
  const active2 = this.workflows.activeRuns();
27694
28614
  return {
27695
28615
  ...active2,
27696
- links: this.cadence.links(active2.runs.map((run) => run.id))
28616
+ links: this.cadence.links(active2.runs.map((run2) => run2.id))
27697
28617
  };
27698
28618
  }
27699
28619
  case "workflow-history":
@@ -27706,8 +28626,11 @@ class Workbench {
27706
28626
  return this.workflows.view(request3.id);
27707
28627
  case "task-origin":
27708
28628
  return this.conversations.origin(request3.taskId);
28629
+ case "conversation-active":
27709
28630
  case "conversations": {
27710
- const value2 = this.conversations.list();
28631
+ const value2 = request3.kind === "conversation-active" ? this.conversations.activeConversations() : this.conversations.list(request3.after ?? null, request3.scan);
28632
+ if (value2.kind !== "conversations" && value2.kind !== "conversation-active")
28633
+ return value2;
27711
28634
  return {
27712
28635
  ...value2,
27713
28636
  entries: value2.entries.map((entry) => ({
@@ -27716,6 +28639,8 @@ class Workbench {
27716
28639
  }))
27717
28640
  };
27718
28641
  }
28642
+ case "conversation-transcript":
28643
+ return this.conversations.transcript(request3.id, request3.turnId, request3.page);
27719
28644
  case "conversation":
27720
28645
  return this.conversations.view(request3.id, request3.before);
27721
28646
  case "files":
@@ -27768,12 +28693,12 @@ class Workbench {
27768
28693
  const entries2 = [{ path: this.o.cwd, current: true }], files = this.o.coordination.files;
27769
28694
  if (!files.directory(this.projectRoot))
27770
28695
  return { kind: "projects", entries: entries2 };
27771
- const directory = opendirSync13(this.projectRoot);
28696
+ const directory = opendirSync14(this.projectRoot);
27772
28697
  try {
27773
28698
  for (let e = directory.readSync();e; e = directory.readSync()) {
27774
28699
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries2.length > 128)
27775
28700
  throw new ContractError("corrupt-selected");
27776
- const saved = files.read(join31(this.projectRoot, e.name));
28701
+ const saved = files.read(join33(this.projectRoot, e.name));
27777
28702
  if (!saved)
27778
28703
  throw new ContractError("corrupt-selected");
27779
28704
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -27842,7 +28767,7 @@ class Workbench {
27842
28767
  if (this.opening.size >= 64)
27843
28768
  throw new ContractError("capacity");
27844
28769
  const path = this.files.directory(request3.path);
27845
- 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`);
27846
28771
  const files = this.o.coordination.files;
27847
28772
  if (files.read(marker2))
27848
28773
  throw new ContractError("receipt-inconclusive");
@@ -27860,7 +28785,7 @@ class Workbench {
27860
28785
  }
27861
28786
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
27862
28787
  for (const root of [this.o.cwd, opened.path]) {
27863
- const entry = join31(this.projectRoot, `${hash2(root)}.json`);
28788
+ const entry = join33(this.projectRoot, `${hash2(root)}.json`);
27864
28789
  const saved = files.read(entry);
27865
28790
  if (!saved)
27866
28791
  files.create(entry, canonicalJson({ path: root }));
@@ -27890,7 +28815,7 @@ async function predecessorExited() {
27890
28815
  } catch {
27891
28816
  return;
27892
28817
  }
27893
- await new Promise((resolve11) => setTimeout(resolve11, 100));
28818
+ await new Promise((resolve12) => setTimeout(resolve12, 100));
27894
28819
  }
27895
28820
  }
27896
28821
  async function healBeforeStart(c) {
@@ -27919,7 +28844,7 @@ function legacy(store, budget, reader) {
27919
28844
  throw new ContractError("capacity");
27920
28845
  }
27921
28846
  }
27922
- const dir = opendirSync14(store.tasks), records = [];
28847
+ const dir = opendirSync15(store.tasks), records = [];
27923
28848
  let entries2 = 0;
27924
28849
  try {
27925
28850
  for (let entry = dir.readSync();entry; entry = dir.readSync()) {
@@ -27928,8 +28853,8 @@ function legacy(store, budget, reader) {
27928
28853
  decodeId(entry.name);
27929
28854
  if (created.has(entry.name))
27930
28855
  continue;
27931
- const path = join32(store.tasks, entry.name, "task.json");
27932
- const size2 = lstatSync20(path).size;
28856
+ const path = join34(store.tasks, entry.name, "task.json");
28857
+ const size2 = lstatSync22(path).size;
27933
28858
  if (size2 > 128 * 1024)
27934
28859
  throw new ContractError("corrupt-selected");
27935
28860
  budget.reserve(size2);
@@ -27961,9 +28886,9 @@ var processLifetime = {
27961
28886
  const restarts = process.uptime() > 600 ? 0 : previous;
27962
28887
  if (!Number.isSafeInteger(restarts) || restarts >= SELF_RESTARTS)
27963
28888
  return;
27964
- const child = spawn4(process.execPath, [
28889
+ const child = spawn5(process.execPath, [
27965
28890
  ...process.execArgv,
27966
- fileURLToPath6(new URL("./service-host.mjs", import.meta.url))
28891
+ fileURLToPath7(new URL("./service-host.mjs", import.meta.url))
27967
28892
  ], {
27968
28893
  detached: true,
27969
28894
  stdio: ["pipe", "ignore", "ignore"],
@@ -27982,7 +28907,7 @@ var processLifetime = {
27982
28907
  }
27983
28908
  };
27984
28909
  async function createServiceHost(value, sourceBuild, lifetime) {
27985
- const embedded = "b6935a8daa09f70de094136c18d8e3588fdd34fc24b9a8fe95e465de11ddae8d";
28910
+ const embedded = "70b7d387e5677a43ff0a80f82aad39684362496916c796150a4e326cd7756b65";
27986
28911
  if (embedded && sourceBuild)
27987
28912
  throw new ContractError("unsupported-context");
27988
28913
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -28066,8 +28991,8 @@ async function createServiceHost(value, sourceBuild, lifetime) {
28066
28991
  let timer;
28067
28992
  await Promise.race([
28068
28993
  owner?.idle(),
28069
- new Promise((resolve11) => {
28070
- timer = setTimeout(resolve11, FAULT_SETTLE_MS);
28994
+ new Promise((resolve12) => {
28995
+ timer = setTimeout(resolve12, FAULT_SETTLE_MS);
28071
28996
  })
28072
28997
  ]);
28073
28998
  clearTimeout(timer);
@@ -28258,6 +29183,7 @@ async function createServiceHost(value, sourceBuild, lifetime) {
28258
29183
  return {
28259
29184
  status: heldOwner.state === "idle" ? ready2 ? "alive" : "unavailable" : heldOwner.state,
28260
29185
  epoch: native.epoch,
29186
+ work: heldOwner.acceptedPending,
28261
29187
  actions: heldOwner.state === "idle" && !!workbench && ready2 && !!choice.snapshot().selected,
28262
29188
  ...operation === "diagnose" ? {
28263
29189
  recording: heldWriter.quarantined ? "quarantined" : "available",