@mrciphersmith/keryx 0.4.26 → 0.4.27

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.
@@ -70,6 +70,31 @@ function readConfigFile(file) {
70
70
  function readTranscriptFile(file) {
71
71
  return readBoundedFile(file, MAX_TRANSCRIPT_FILE_BYTES);
72
72
  }
73
+ function ensureKeryxSubdir(segments, dir) {
74
+ const root = ensureKeryxConfigDir(dir);
75
+ let current = root;
76
+ for (const segment of segments) {
77
+ current = path.join(current, segment);
78
+ mkdirSync(current, { recursive: true, mode: 448 });
79
+ if (process.platform === "win32") {
80
+ continue;
81
+ }
82
+ try {
83
+ chmodSync(current, 448);
84
+ } catch {}
85
+ }
86
+ return current;
87
+ }
88
+ function appendOwnerOnlyLine(file, line) {
89
+ appendFileSync(file, `${line}
90
+ `, { mode: 384 });
91
+ if (process.platform === "win32") {
92
+ return;
93
+ }
94
+ try {
95
+ chmodSync(file, 384);
96
+ } catch {}
97
+ }
73
98
  function writeOwnerOnlyFileAtomic(file, body) {
74
99
  const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
75
100
  try {
@@ -20582,7 +20607,7 @@ var init_repomap = __esm(() => {
20582
20607
  // src/session/preservation.ts
20583
20608
  import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
20584
20609
  import { closeSync as closeSync4, fsyncSync, mkdirSync as mkdirSync4, openSync as openSync4, readdirSync as readdirSync5, readFileSync as readFileSync15, renameSync as renameSync4, unlinkSync as unlinkSync2, writeFileSync as writeFileSync5 } from "fs";
20585
- import path68 from "path";
20610
+ import path69 from "path";
20586
20611
  function syncDir(dir) {
20587
20612
  if (process.platform === "win32")
20588
20613
  return;
@@ -20594,7 +20619,7 @@ function syncDir(dir) {
20594
20619
  }
20595
20620
  }
20596
20621
  function writePreservationFile(file, body) {
20597
- const dir = path68.dirname(file);
20622
+ const dir = path69.dirname(file);
20598
20623
  mkdirSync4(dir, { recursive: true, mode: 448 });
20599
20624
  const tmp = `${file}.${randomUUID5()}.tmp`;
20600
20625
  const fd = openSync4(tmp, "wx", 384);
@@ -20630,21 +20655,21 @@ function commitPreservation(dir, files, beforeSelect) {
20630
20655
  throw new Error("preservation snapshot exceeds readable size limit");
20631
20656
  }
20632
20657
  const id = hash(body);
20633
- const base = path68.join(dir, "preservation");
20634
- mkdirSync4(path68.join(base, "generations"), { recursive: true, mode: 448 });
20658
+ const base = path69.join(dir, "preservation");
20659
+ mkdirSync4(path69.join(base, "generations"), { recursive: true, mode: 448 });
20635
20660
  syncDir(dir);
20636
20661
  syncDir(base);
20637
- writePreservationFile(path68.join(base, "generations", `${id}.json`), body);
20662
+ writePreservationFile(path69.join(base, "generations", `${id}.json`), body);
20638
20663
  beforeSelect?.();
20639
- writePreservationFile(path68.join(base, "CURRENT"), id);
20664
+ writePreservationFile(path69.join(base, "CURRENT"), id);
20640
20665
  return id;
20641
20666
  }
20642
20667
  function readPreservation(dir, snapshotId) {
20643
- const base = path68.join(dir, "preservation");
20668
+ const base = path69.join(dir, "preservation");
20644
20669
  let id = snapshotId;
20645
20670
  if (id === undefined) {
20646
20671
  try {
20647
- id = readFileSync15(path68.join(base, "CURRENT"), "utf8");
20672
+ id = readFileSync15(path69.join(base, "CURRENT"), "utf8");
20648
20673
  } catch (e) {
20649
20674
  if (e.code === "ENOENT")
20650
20675
  return;
@@ -20653,7 +20678,7 @@ function readPreservation(dir, snapshotId) {
20653
20678
  }
20654
20679
  if (!/^[a-f0-9]{64}$/.test(id))
20655
20680
  throw new Error("invalid preservation identity");
20656
- const read = readTranscriptFile(path68.join(base, "generations", `${id}.json`));
20681
+ const read = readTranscriptFile(path69.join(base, "generations", `${id}.json`));
20657
20682
  if (!read.ok)
20658
20683
  throw new Error(`snapshot unreadable: ${read.reason}`);
20659
20684
  if (hash(read.text) !== id)
@@ -20683,7 +20708,7 @@ function collectPreservationFiles(dir, rawSlate) {
20683
20708
  for (const name of allowed) {
20684
20709
  if (name === "slate.json")
20685
20710
  continue;
20686
- const read = readTranscriptFile(path68.join(dir, name));
20711
+ const read = readTranscriptFile(path69.join(dir, name));
20687
20712
  if (read.ok)
20688
20713
  files[name] = read.text;
20689
20714
  else if (read.reason !== "absent")
@@ -20708,17 +20733,17 @@ function queuePreservedWrapUp(dir, rawSlate) {
20708
20733
  ...files["archive.jsonl"]?.trim() ? ["Transcript retained for evidence review"] : []
20709
20734
  ]
20710
20735
  };
20711
- const outbox = path68.join(dir, "preservation", "outbox");
20712
- const target = path68.join(outbox, `${snapshot}.json`);
20736
+ const outbox = path69.join(dir, "preservation", "outbox");
20737
+ const target = path69.join(outbox, `${snapshot}.json`);
20713
20738
  mkdirSync4(outbox, { recursive: true, mode: 448 });
20714
- syncDir(path68.dirname(outbox));
20739
+ syncDir(path69.dirname(outbox));
20715
20740
  writePreservationFile(target, JSON.stringify(receipt));
20716
20741
  return receipt;
20717
20742
  }
20718
20743
  function readPendingHistory(dir) {
20719
- let read = readConfigFile(path68.join(dir, "preservation", "HISTORY"));
20744
+ let read = readConfigFile(path69.join(dir, "preservation", "HISTORY"));
20720
20745
  if (!read.ok && read.reason === "absent") {
20721
- read = readConfigFile(path68.join(dir, "preservation", "MIRRORING"));
20746
+ read = readConfigFile(path69.join(dir, "preservation", "MIRRORING"));
20722
20747
  }
20723
20748
  if (!read.ok) {
20724
20749
  if (read.reason === "absent")
@@ -20742,7 +20767,7 @@ var init_preservation = __esm(() => {
20742
20767
 
20743
20768
  // src/session/slate.ts
20744
20769
  import { mkdir as mkdir13, readFile as readFile32, readdir as readdir18, stat as stat12 } from "fs/promises";
20745
- import path69 from "path";
20770
+ import path70 from "path";
20746
20771
  import { unlinkSync as unlinkSync3 } from "fs";
20747
20772
  function isReservedNoteKey(key) {
20748
20773
  return key.toLowerCase().startsWith(ASK_ANSWER_NOTE_PREFIX);
@@ -20753,7 +20778,7 @@ function modelNotesOf(notes) {
20753
20778
  return Object.fromEntries(Object.entries(notes).filter(([key]) => !isReservedNoteKey(key)));
20754
20779
  }
20755
20780
  function slatePath(dir) {
20756
- return path69.join(dir, "slate.json");
20781
+ return path70.join(dir, "slate.json");
20757
20782
  }
20758
20783
  function slateLockPath(dir) {
20759
20784
  return `${slatePath(dir)}.lock`;
@@ -20777,14 +20802,14 @@ function workingMemoryOf(slate) {
20777
20802
  };
20778
20803
  }
20779
20804
  async function readArchivedWorkingMemory(dir) {
20780
- const archiveDir = path69.join(dir, "slate-archive");
20805
+ const archiveDir = path70.join(dir, "slate-archive");
20781
20806
  try {
20782
20807
  const names = (await readdir18(archiveDir)).filter((n) => n.endsWith(".json"));
20783
- const dated = await Promise.all(names.map(async (n) => ({ n, at: (await stat12(path69.join(archiveDir, n))).mtimeMs })));
20808
+ const dated = await Promise.all(names.map(async (n) => ({ n, at: (await stat12(path70.join(archiveDir, n))).mtimeMs })));
20784
20809
  dated.sort((a, b) => b.at - a.at || (a.n < b.n ? 1 : -1));
20785
20810
  for (const { n } of dated) {
20786
20811
  try {
20787
- const slate = JSON.parse(await readFile32(path69.join(archiveDir, n), "utf8"));
20812
+ const slate = JSON.parse(await readFile32(path70.join(archiveDir, n), "utf8"));
20788
20813
  const carry = workingMemoryOf(slate);
20789
20814
  if (carry.trail !== undefined || carry.notes !== undefined || carry.answers !== undefined)
20790
20815
  return carry;
@@ -20819,11 +20844,11 @@ async function archiveIfExistsLocked(dir, attemptId, signal) {
20819
20844
  return;
20820
20845
  throw error;
20821
20846
  }
20822
- const archiveDir = path69.join(dir, "slate-archive");
20847
+ const archiveDir = path70.join(dir, "slate-archive");
20823
20848
  await mkdir13(archiveDir, { recursive: true });
20824
20849
  signal?.throwIfAborted();
20825
20850
  queuePreservedWrapUp(dir, raw);
20826
- writePreservationFile(path69.join(archiveDir, `${attemptId}.json`), raw);
20851
+ writePreservationFile(path70.join(archiveDir, `${attemptId}.json`), raw);
20827
20852
  unlinkSync3(slatePath(dir));
20828
20853
  }
20829
20854
  async function openSlateAtomic(dir, mintAttemptId, build, signal) {
@@ -20839,7 +20864,7 @@ async function openSlateAtomic(dir, mintAttemptId, build, signal) {
20839
20864
  writePreservationFile(slatePath(dir), `${JSON.stringify(next, null, 2)}
20840
20865
  `);
20841
20866
  try {
20842
- unlinkSync3(path69.join(dir, "terminal-state.json"));
20867
+ unlinkSync3(path70.join(dir, "terminal-state.json"));
20843
20868
  } catch (error) {
20844
20869
  if (!isNotFound(error))
20845
20870
  throw error;
@@ -21241,9 +21266,9 @@ var init_validation = __esm(() => {
21241
21266
  });
21242
21267
 
21243
21268
  // src/memory/config.ts
21244
- import path79 from "path";
21269
+ import path80 from "path";
21245
21270
  function memoryConfigPath(cwd) {
21246
- return path79.join(cwd, ".metaproject", "memory.config.json");
21271
+ return path80.join(cwd, ".metaproject", "memory.config.json");
21247
21272
  }
21248
21273
  async function loadMemoryConfig(cwd) {
21249
21274
  const file = memoryConfigPath(cwd);
@@ -21321,12 +21346,12 @@ var init_config4 = __esm(() => {
21321
21346
 
21322
21347
  // src/memory/write.ts
21323
21348
  import { mkdir as mkdir18, open as open6, readFile as readFile39, rename as rename4, rm as rm7, writeFile as writeFile9 } from "fs/promises";
21324
- import path82 from "path";
21349
+ import path83 from "path";
21325
21350
  async function resolveCanonicalEntryPath(cwd, relativePath) {
21326
- const root = path82.resolve(memoryRoot(cwd));
21327
- const absolutePath = path82.resolve(root, relativePath);
21328
- const normalized = toPosix2(path82.relative(root, absolutePath));
21329
- if (!normalized || normalized.startsWith("../") || path82.isAbsolute(normalized) || !normalized.endsWith(".md")) {
21351
+ const root = path83.resolve(memoryRoot(cwd));
21352
+ const absolutePath = path83.resolve(root, relativePath);
21353
+ const normalized = toPosix2(path83.relative(root, absolutePath));
21354
+ if (!normalized || normalized.startsWith("../") || path83.isAbsolute(normalized) || !normalized.endsWith(".md")) {
21330
21355
  return null;
21331
21356
  }
21332
21357
  return { absolutePath, relativePath: normalized };
@@ -21379,9 +21404,9 @@ function validateNextEntry(relativePath, content) {
21379
21404
  return null;
21380
21405
  }
21381
21406
  async function replaceAtomically(target, content) {
21382
- const dir = path82.dirname(target);
21407
+ const dir = path83.dirname(target);
21383
21408
  await mkdir18(dir, { recursive: true });
21384
- const tmp = path82.join(dir, `.${path82.basename(target)}.keryx-tmp-${process.pid}-${Math.random().toString(16).slice(2)}`);
21409
+ const tmp = path83.join(dir, `.${path83.basename(target)}.keryx-tmp-${process.pid}-${Math.random().toString(16).slice(2)}`);
21385
21410
  try {
21386
21411
  await writeFile9(tmp, content, "utf8");
21387
21412
  const file = await open6(tmp, "r");
@@ -21410,7 +21435,7 @@ function header(content, name) {
21410
21435
  return content.match(new RegExp(`^${name}:\\s*(.+)$`, "mi"))?.[1]?.trim() ?? null;
21411
21436
  }
21412
21437
  function toPosix2(value) {
21413
- return value.split(path82.sep).join("/");
21438
+ return value.split(path83.sep).join("/");
21414
21439
  }
21415
21440
  function message(cause) {
21416
21441
  return cause instanceof Error ? cause.message : String(cause);
@@ -21522,9 +21547,9 @@ var init_evidence = __esm(() => {
21522
21547
  });
21523
21548
 
21524
21549
  // src/wiki/config.ts
21525
- import path83 from "path";
21550
+ import path84 from "path";
21526
21551
  function wikiConfigPath(cwd) {
21527
- return path83.join(cwd, ".metaproject", "wiki.config.json");
21552
+ return path84.join(cwd, ".metaproject", "wiki.config.json");
21528
21553
  }
21529
21554
  function mergeWikiConfig(parsed) {
21530
21555
  const base = DEFAULT_WIKI_CONFIG;
@@ -21602,12 +21627,12 @@ var init_config5 = __esm(() => {
21602
21627
  // src/wiki/history.ts
21603
21628
  import { createHash as createHash20, randomBytes as randomBytes4 } from "crypto";
21604
21629
  import { appendFile as appendFile3, mkdir as mkdir19, open as open7, readFile as readFile41, rm as rm8, stat as stat13, writeFile as writeFile10 } from "fs/promises";
21605
- import path84 from "path";
21630
+ import path85 from "path";
21606
21631
  function wikiRootPath(cwd) {
21607
- return path84.join(cwd, ".metaproject", "wiki");
21632
+ return path85.join(cwd, ".metaproject", "wiki");
21608
21633
  }
21609
21634
  function wikiHistoryRoot(cwd) {
21610
- return path84.join(cwd, ".metaproject", "data", "gdwiki", "history");
21635
+ return path85.join(cwd, ".metaproject", "data", "gdwiki", "history");
21611
21636
  }
21612
21637
  function newWikiRunId(now = new Date) {
21613
21638
  const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
@@ -21628,26 +21653,26 @@ async function openWikiWriteContext(cwd, command) {
21628
21653
  return createWikiWriteContext(cwd, command, { keep: (await loadWikiConfig(cwd)).history.keep });
21629
21654
  }
21630
21655
  function wikiPageKey(cwd, absolutePath) {
21631
- const relative = path84.relative(wikiRootPath(cwd), path84.resolve(absolutePath));
21632
- if (relative === "" || relative.startsWith("..") || path84.isAbsolute(relative)) {
21656
+ const relative = path85.relative(wikiRootPath(cwd), path85.resolve(absolutePath));
21657
+ if (relative === "" || relative.startsWith("..") || path85.isAbsolute(relative)) {
21633
21658
  throw new Error(`not a wiki page: ${absolutePath}`);
21634
21659
  }
21635
21660
  return toPosix(relative);
21636
21661
  }
21637
21662
  function assertPageKey(page) {
21638
21663
  const segments = page.split("/");
21639
- if (page.length === 0 || page.includes("\\") || path84.isAbsolute(page) || segments.some((segment) => segment === "" || segment === "." || segment === "..")) {
21664
+ if (page.length === 0 || page.includes("\\") || path85.isAbsolute(page) || segments.some((segment) => segment === "" || segment === "." || segment === "..")) {
21640
21665
  throw new Error(`not a wiki page path: ${page}`);
21641
21666
  }
21642
21667
  return page;
21643
21668
  }
21644
21669
  function pageHistoryDir(cwd, page) {
21645
- return path84.join(wikiHistoryRoot(cwd), ...assertPageKey(page).replace(/\.md$/i, "").split("/"));
21670
+ return path85.join(wikiHistoryRoot(cwd), ...assertPageKey(page).replace(/\.md$/i, "").split("/"));
21646
21671
  }
21647
21672
  function versionFilePath(cwd, page, file) {
21648
21673
  const dir = pageHistoryDir(cwd, page);
21649
- const target = path84.join(dir, file);
21650
- if (!VERSION_FILE.test(file) || path84.dirname(target) !== dir) {
21674
+ const target = path85.join(dir, file);
21675
+ if (!VERSION_FILE.test(file) || path85.dirname(target) !== dir) {
21651
21676
  throw new Error(`history index names an invalid version file for ${page}: ${file}`);
21652
21677
  }
21653
21678
  return target;
@@ -21714,7 +21739,7 @@ function parsePageHistoryIndex(markdown, page) {
21714
21739
  return { page, rows };
21715
21740
  }
21716
21741
  async function readPageHistory(cwd, page) {
21717
- const indexPath = path84.join(pageHistoryDir(cwd, page), INDEX_FILE);
21742
+ const indexPath = path85.join(pageHistoryDir(cwd, page), INDEX_FILE);
21718
21743
  const raw = await readBufferOrNull(indexPath);
21719
21744
  if (raw === null)
21720
21745
  return null;
@@ -21726,8 +21751,8 @@ async function readPageHistory(cwd, page) {
21726
21751
  }
21727
21752
  async function storeVersion(cwd, page, version, at, content) {
21728
21753
  const fileName = `${versionLabel(version)}-${at.replace(/[:.]/g, "-")}.md`;
21729
- const target = path84.join(pageHistoryDir(cwd, page), fileName);
21730
- await mkdir19(path84.dirname(target), { recursive: true });
21754
+ const target = path85.join(pageHistoryDir(cwd, page), fileName);
21755
+ await mkdir19(path85.dirname(target), { recursive: true });
21731
21756
  await writeFile10(target, content);
21732
21757
  if (sha2562(await readFile41(target)) !== sha2562(content)) {
21733
21758
  throw new Error(`history: stored version does not match the page bytes: ${target}`);
@@ -21765,7 +21790,7 @@ function planPrune2(history, keep, maxRows = MAX_INDEX_ROWS) {
21765
21790
  }
21766
21791
  async function ensureHistoryRoot(cwd) {
21767
21792
  const root = wikiHistoryRoot(cwd);
21768
- const ignore = path84.join(root, ".gitignore");
21793
+ const ignore = path85.join(root, ".gitignore");
21769
21794
  if (await readBufferOrNull(ignore))
21770
21795
  return;
21771
21796
  await mkdir19(root, { recursive: true });
@@ -21795,14 +21820,14 @@ async function endsWithoutNewline(file) {
21795
21820
  }
21796
21821
  async function appendRun(cwd, entry) {
21797
21822
  const root = wikiHistoryRoot(cwd);
21798
- const file = path84.join(root, RUNS_FILE);
21823
+ const file = path85.join(root, RUNS_FILE);
21799
21824
  const lead = await endsWithoutNewline(file) ? `
21800
21825
  ` : "";
21801
21826
  await appendFile3(file, `${lead}${JSON.stringify(entry)}
21802
21827
  `, "utf8");
21803
21828
  if ((await stat13(file)).size <= MAX_RUNS_BYTES)
21804
21829
  return;
21805
- await withFileLock2(path84.join(root, ".runs.lock"), async () => {
21830
+ await withFileLock2(path85.join(root, ".runs.lock"), async () => {
21806
21831
  if ((await stat13(file)).size <= MAX_RUNS_BYTES)
21807
21832
  return;
21808
21833
  const lines = (await readFile41(file, "utf8")).split(`
@@ -21816,7 +21841,7 @@ async function mutatePage(ctx, absolutePath, next) {
21816
21841
  const page = wikiPageKey(ctx.cwd, absolutePath);
21817
21842
  const dir = pageHistoryDir(ctx.cwd, page);
21818
21843
  await ensureHistoryRoot(ctx.cwd);
21819
- return withFileLock2(path84.join(path84.dirname(dir), `.${path84.basename(dir)}.lock`), async () => {
21844
+ return withFileLock2(path85.join(path85.dirname(dir), `.${path85.basename(dir)}.lock`), async () => {
21820
21845
  const live = await readBufferOrNull(absolutePath);
21821
21846
  if (next === null ? live === null : live !== null && live.equals(next)) {
21822
21847
  return { changed: false };
@@ -21840,7 +21865,7 @@ async function mutatePage(ctx, absolutePath, next) {
21840
21865
  if (next === null) {
21841
21866
  await rm8(absolutePath, { force: true });
21842
21867
  } else {
21843
- await mkdir19(path84.dirname(absolutePath), { recursive: true });
21868
+ await mkdir19(path85.dirname(absolutePath), { recursive: true });
21844
21869
  await writeFile10(absolutePath, next);
21845
21870
  }
21846
21871
  } catch (error) {
@@ -21848,7 +21873,7 @@ async function mutatePage(ctx, absolutePath, next) {
21848
21873
  await rm8(versionFilePath(ctx.cwd, page, row.file), { force: true });
21849
21874
  throw error;
21850
21875
  }
21851
- await writeFileAtomic(path84.join(dir, INDEX_FILE), renderPageHistoryIndex(history));
21876
+ await writeFileAtomic(path85.join(dir, INDEX_FILE), renderPageHistoryIndex(history));
21852
21877
  for (const file of pruned)
21853
21878
  await rm8(versionFilePath(ctx.cwd, page, file), { force: true });
21854
21879
  return { changed: true, action };
@@ -28896,8 +28921,228 @@ init_validator();
28896
28921
 
28897
28922
  // src/lib/phase-trace.ts
28898
28923
  import { appendFileSync as appendFileSync2 } from "fs";
28924
+
28925
+ // src/lib/call-diagnostics.ts
28926
+ init_config_dir();
28927
+ import { statSync as statSync5 } from "fs";
28928
+ import path65 from "path";
28929
+ var DEFAULT_WATCH_INTERVAL_MS = 30000;
28930
+ var DEFAULT_STALL_MS = 10 * 60000;
28931
+ var DEFAULT_REPEAT_MS = 15 * 60000;
28932
+ var DEFAULT_MAX_FILE_BYTES = 1e6;
28933
+ var SNAPSHOT_RECENT = 120;
28934
+ var HUMAN_STAGE_FACTOR = 3;
28935
+ var HUMAN_STAGES = new Set(["approval"]);
28936
+ function errText(e) {
28937
+ return e instanceof Error ? e.message : String(e);
28938
+ }
28939
+ function emptyMetrics() {
28940
+ return { callsStarted: 0, callsSettled: 0, callsByOutcome: {}, stages: {}, events: {}, dumps: 0, maxLoopLagMs: 0 };
28941
+ }
28942
+ function createCallDiagnostics(options = {}) {
28943
+ const now = options.now ?? (() => Date.now());
28944
+ const ringSize = options.ringSize ?? 300;
28945
+ let sink = options.sink;
28946
+ const bornAt = now();
28947
+ const calls = new Map;
28948
+ const probes = new Map;
28949
+ let ring = [];
28950
+ const metrics = emptyMetrics();
28951
+ let sessionId;
28952
+ let file;
28953
+ let lastLagMs = 0;
28954
+ let lastTickAt;
28955
+ let intervalMs = DEFAULT_WATCH_INTERVAL_MS;
28956
+ let stallMs = DEFAULT_STALL_MS;
28957
+ let repeatMs = DEFAULT_REPEAT_MS;
28958
+ let lastDumpAt;
28959
+ let lastDumpIds = new Set;
28960
+ const record = (label) => {
28961
+ ring.push(`${new Date(now()).toISOString()} ${label}`);
28962
+ if (ring.length > ringSize)
28963
+ ring = ring.slice(ring.length - ringSize);
28964
+ };
28965
+ const leaveStage = (call, at) => {
28966
+ const ms = Math.max(0, at - call.stageSince);
28967
+ const stat = metrics.stages[call.stage] ??= { count: 0, totalMs: 0, maxMs: 0 };
28968
+ stat.count += 1;
28969
+ stat.totalMs += ms;
28970
+ if (ms > stat.maxMs)
28971
+ stat.maxMs = ms;
28972
+ };
28973
+ const snapshot = (reason) => {
28974
+ const at = now();
28975
+ const probed = {};
28976
+ for (const [name, fn] of probes) {
28977
+ try {
28978
+ probed[name] = fn();
28979
+ } catch (e) {
28980
+ probed[name] = { probeError: errText(e) };
28981
+ }
28982
+ }
28983
+ let rssBytes;
28984
+ try {
28985
+ rssBytes = process.memoryUsage().rss;
28986
+ } catch {
28987
+ rssBytes = undefined;
28988
+ }
28989
+ let activeResources;
28990
+ try {
28991
+ const list = process.getActiveResourcesInfo?.();
28992
+ if (list !== undefined) {
28993
+ activeResources = {};
28994
+ for (const kind of list)
28995
+ activeResources[kind] = (activeResources[kind] ?? 0) + 1;
28996
+ }
28997
+ } catch {
28998
+ activeResources = undefined;
28999
+ }
29000
+ return {
29001
+ ts: new Date(at).toISOString(),
29002
+ reason,
29003
+ pid: process.pid,
29004
+ sessionId,
29005
+ uptimeMs: at - bornAt,
29006
+ calls: [...calls.values()].map((c) => ({
29007
+ id: c.id,
29008
+ name: c.name,
29009
+ ageMs: at - c.startedAt,
29010
+ stage: c.stage,
29011
+ stageAgeMs: at - c.stageSince,
29012
+ stageChanges: c.stageChanges
29013
+ })),
29014
+ metrics: structuredClone(metrics),
29015
+ probes: probed,
29016
+ loop: { lastLagMs, maxLagMs: metrics.maxLoopLagMs },
29017
+ process: { rssBytes, activeResources },
29018
+ recent: ring.slice(-SNAPSHOT_RECENT)
29019
+ };
29020
+ };
29021
+ const dump = (reason) => {
29022
+ let snap;
29023
+ try {
29024
+ snap = snapshot(reason);
29025
+ } catch {
29026
+ return;
29027
+ }
29028
+ if (sink === undefined)
29029
+ return snap;
29030
+ try {
29031
+ sink(JSON.stringify({ ...snap, metrics: { ...snap.metrics, dumps: metrics.dumps + 1 } }));
29032
+ } catch {
29033
+ return;
29034
+ }
29035
+ metrics.dumps += 1;
29036
+ return snap;
29037
+ };
29038
+ const tick = () => {
29039
+ const at = now();
29040
+ if (lastTickAt !== undefined) {
29041
+ const lag = Math.max(0, at - lastTickAt - intervalMs);
29042
+ lastLagMs = lag;
29043
+ if (lag > metrics.maxLoopLagMs)
29044
+ metrics.maxLoopLagMs = lag;
29045
+ }
29046
+ lastTickAt = at;
29047
+ const suspects = [...calls.values()].filter((c) => c.watched && at - c.stageSince >= (HUMAN_STAGES.has(c.stage) ? stallMs * HUMAN_STAGE_FACTOR : stallMs));
29048
+ if (suspects.length === 0) {
29049
+ lastDumpIds = new Set;
29050
+ return;
29051
+ }
29052
+ const ids = new Set(suspects.map((c) => c.id));
29053
+ const fresh = [...ids].some((id) => !lastDumpIds.has(id));
29054
+ const due = lastDumpAt === undefined || at - lastDumpAt >= repeatMs;
29055
+ if (!fresh && !due)
29056
+ return;
29057
+ lastDumpAt = at;
29058
+ lastDumpIds = ids;
29059
+ record(`diag stall suspected: ${suspects.map((c) => `${c.name}#${c.id}@${c.stage}`).join(", ")}`);
29060
+ dump("stall");
29061
+ };
29062
+ return {
29063
+ begin(id, name, opts) {
29064
+ const at = now();
29065
+ let key = id;
29066
+ for (let n = 2;calls.has(key); n += 1)
29067
+ key = `${id}~${n}`;
29068
+ calls.set(key, { id: key, name, startedAt: at, watched: opts?.watched !== false, stage: "start", stageSince: at, stageChanges: 0 });
29069
+ metrics.callsStarted += 1;
29070
+ return key;
29071
+ },
29072
+ stage(id, next) {
29073
+ const call = calls.get(id);
29074
+ if (call === undefined)
29075
+ return;
29076
+ const at = now();
29077
+ leaveStage(call, at);
29078
+ call.stage = next;
29079
+ call.stageSince = at;
29080
+ call.stageChanges += 1;
29081
+ },
29082
+ end(id, outcome) {
29083
+ const call = calls.get(id);
29084
+ if (call === undefined)
29085
+ return;
29086
+ leaveStage(call, now());
29087
+ calls.delete(id);
29088
+ metrics.callsSettled += 1;
29089
+ metrics.callsByOutcome[outcome] = (metrics.callsByOutcome[outcome] ?? 0) + 1;
29090
+ },
29091
+ event(kind, detail) {
29092
+ metrics.events[kind] = (metrics.events[kind] ?? 0) + 1;
29093
+ record(detail === undefined ? `event ${kind}` : `event ${kind} ${detail}`);
29094
+ },
29095
+ record,
29096
+ probe(name, fn) {
29097
+ probes.set(name, fn);
29098
+ return () => {
29099
+ if (probes.get(name) === fn)
29100
+ probes.delete(name);
29101
+ };
29102
+ },
29103
+ snapshot,
29104
+ dump,
29105
+ inFlight: () => [...calls.values()],
29106
+ dumpPath: () => file,
29107
+ tick,
29108
+ start(opts) {
29109
+ sessionId = opts.sessionId;
29110
+ intervalMs = opts.intervalMs ?? DEFAULT_WATCH_INTERVAL_MS;
29111
+ stallMs = opts.stallMs ?? DEFAULT_STALL_MS;
29112
+ repeatMs = opts.repeatMs ?? DEFAULT_REPEAT_MS;
29113
+ const cap = opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
29114
+ if (sink === undefined) {
29115
+ sink = (line) => {
29116
+ if (file === undefined) {
29117
+ const dir = ensureKeryxSubdir(["diagnostics"], opts.configDir);
29118
+ file = path65.join(dir, `${opts.sessionId.replace(/[^A-Za-z0-9._-]/g, "_")}.ndjson`);
29119
+ }
29120
+ let size = 0;
29121
+ try {
29122
+ size = statSync5(file).size;
29123
+ } catch {}
29124
+ if (size >= cap)
29125
+ throw new Error("diagnostics file is at its size cap");
29126
+ appendOwnerOnlyLine(file, line);
29127
+ };
29128
+ }
29129
+ lastTickAt = now();
29130
+ const timer = setInterval(() => {
29131
+ try {
29132
+ tick();
29133
+ } catch {}
29134
+ }, intervalMs);
29135
+ timer.unref?.();
29136
+ return () => clearInterval(timer);
29137
+ }
29138
+ };
29139
+ }
29140
+ var callDiagnostics = createCallDiagnostics();
29141
+
29142
+ // src/lib/phase-trace.ts
28899
29143
  var ENV_PHASE_TRACE = "KERYX_PHASE_TRACE";
28900
29144
  function tracePhase(label, env = process.env) {
29145
+ callDiagnostics.record(label);
28901
29146
  const target = env[ENV_PHASE_TRACE];
28902
29147
  if (target === undefined || target === "")
28903
29148
  return;
@@ -28911,7 +29156,7 @@ function tracePhase(label, env = process.env) {
28911
29156
  init_json();
28912
29157
  init_shell_syntax();
28913
29158
  import { readdir as readdir17, stat as stat11 } from "fs/promises";
28914
- import path65 from "path";
29159
+ import path66 from "path";
28915
29160
  var PR_REF = /(?:github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+))|^#?(\d+)$/;
28916
29161
  var REVIEW_ENDPOINT = /(?:^|\/)repos\/([^/]+\/[^/]+)\/pulls\/(\d+)\/reviews(?:\/\d+\/events)?\/?$/;
28917
29162
  var PR_REVIEW_VALUE_FLAGS = new Set(["-R", "--repo", "-b", "--body", "-F", "--body-file"]);
@@ -28990,12 +29235,12 @@ async function boundPackages(cwd) {
28990
29235
  }
28991
29236
  const found = [];
28992
29237
  for (const name of names) {
28993
- const dir = path65.join(reviewsRoot(cwd), name);
28994
- const manifest = await readJsonFileOr(path65.join(dir, "manifest.json"), undefined);
29238
+ const dir = path66.join(reviewsRoot(cwd), name);
29239
+ const manifest = await readJsonFileOr(path66.join(dir, "manifest.json"), undefined);
28995
29240
  if (manifest === undefined || !isPrBound(manifest.target))
28996
29241
  continue;
28997
29242
  const ref = parseRef(manifest.target.ref);
28998
- const info = await stat11(path65.join(dir, "manifest.json")).catch(() => {
29243
+ const info = await stat11(path66.join(dir, "manifest.json")).catch(() => {
28999
29244
  return;
29000
29245
  });
29001
29246
  found.push({ dir, id: manifest.reviewId, status: manifest.status, number: ref.number, repo: ref.repo, mtime: info?.mtimeMs ?? 0 });
@@ -29168,7 +29413,7 @@ init_command_risk();
29168
29413
  init_contained_path();
29169
29414
  import { createHash as createHash9 } from "crypto";
29170
29415
  import { closeSync as closeSync3, constants as constants6, fstatSync as fstatSync3, openSync as openSync3, readSync } from "fs";
29171
- import path66 from "path";
29416
+ import path67 from "path";
29172
29417
 
29173
29418
  // src/lib/review-path-flags.ts
29174
29419
  init_args();
@@ -29326,7 +29571,7 @@ function carriesPreload(text) {
29326
29571
  }
29327
29572
  var MAX_BUNFIG_BYTES = 256 * 1024;
29328
29573
  function readBunfig(root) {
29329
- const file = path66.join(root, "bunfig.toml");
29574
+ const file = path67.join(root, "bunfig.toml");
29330
29575
  let fd;
29331
29576
  try {
29332
29577
  fd = openSync3(file, constants6.O_RDONLY | constants6.O_NONBLOCK);
@@ -29407,10 +29652,10 @@ function movedTo(cwd, target) {
29407
29652
  if (cwd === undefined || target === "" || target.startsWith("-") || isExpandable(target))
29408
29653
  return;
29409
29654
  const cdpath = process.env.CDPATH;
29410
- if (cdpath !== undefined && cdpath !== "" && !path66.isAbsolute(target) && !target.startsWith("./") && !target.startsWith("../")) {
29655
+ if (cdpath !== undefined && cdpath !== "" && !path67.isAbsolute(target) && !target.startsWith("./") && !target.startsWith("../")) {
29411
29656
  return;
29412
29657
  }
29413
- const lexical = path66.resolve(cwd, target);
29658
+ const lexical = path67.resolve(cwd, target);
29414
29659
  return realOrResolved(lexical) === lexical ? lexical : undefined;
29415
29660
  }
29416
29661
  function areReviewPathFlagsInside(sub, args, walk) {
@@ -29445,11 +29690,11 @@ function isOutsideReadFlag(word) {
29445
29690
  return name.length >= 3 && name.startsWith("--") && GIT_OUTSIDE_READ_FLAGS.some((flag) => flag.startsWith(name));
29446
29691
  }
29447
29692
  function isOutsideRoot(projectRoot, target) {
29448
- const relative = path66.relative(projectRoot, target);
29449
- return relative === ".." || relative.startsWith(`..${path66.sep}`) || path66.isAbsolute(relative);
29693
+ const relative = path67.relative(projectRoot, target);
29694
+ return relative === ".." || relative.startsWith(`..${path67.sep}`) || path67.isAbsolute(relative);
29450
29695
  }
29451
29696
  function isEscapingOperand(word, cwd, projectRoot) {
29452
- return isOutsideRoot(projectRoot, realOrResolved(path66.resolve(cwd, word)));
29697
+ return isOutsideRoot(projectRoot, realOrResolved(path67.resolve(cwd, word)));
29453
29698
  }
29454
29699
  function isGitReadConfined(words, walk) {
29455
29700
  const cwd = walk.cwd;
@@ -29490,7 +29735,7 @@ function isTrustRoutineCommand(command, context = {}) {
29490
29735
  const segments = splitSegments(command);
29491
29736
  if (segments.length === 0 || segments.length > MAX_CHAIN_SEGMENTS)
29492
29737
  return false;
29493
- const cwd = realOrResolved(path66.resolve(context.cwd ?? process.cwd()));
29738
+ const cwd = realOrResolved(path67.resolve(context.cwd ?? process.cwd()));
29494
29739
  const walk = { projectRoot: realOrResolved(resolveProjectRoot(cwd)), cwd, untrusted: context.untrustedContent === true };
29495
29740
  return segments.every((seg) => (seg.precededBy === undefined || seg.precededBy === "&&") && !hasUnquotedMetacharacter(seg.raw) && !(isJudgedByWords(seg.words) && hasUnquotedExpansion(seg.raw)) && isRoutineSegment(seg.words, walk));
29496
29741
  }
@@ -29527,7 +29772,7 @@ function resolveQuestionAnswerer(mode) {
29527
29772
  // src/commands/automatic-review.ts
29528
29773
  import { existsSync as existsSync17, lstatSync as lstatSync4, realpathSync as realpathSync4 } from "fs";
29529
29774
  import { mkdir as mkdir12, writeFile as writeFile7 } from "fs/promises";
29530
- import path67 from "path";
29775
+ import path68 from "path";
29531
29776
 
29532
29777
  // src/harness/tool/builtin/ask-user-tool.ts
29533
29778
  var ASK_USER_DESCRIPTION = "Ask the user an interactive multiple-choice question (Claude-style interview). " + "Use when requirements are unclear, for interview steps, or to confirm a plan. " + "Provide 2\u20136 options with short descriptions; mark at most ONE option recommended when sensible (more than one is rejected). " + "Whenever you mark an option recommended, ALWAYS set recommendationReason: one sentence on why it is the better choice. " + "Input: { question: string, options: [{ id, label, description, recommended? }], recommendationReason?: string, allow_freeform?: boolean, action?: string, irreversible?: boolean, emergency?: string }. " + "Returns the chosen option id (or freeform text if allow_freeform). " + "irreversible: true means the question decides something that cannot be undone (release, publish, deploy, delete, push, merge to a shared branch, drop, force, reset, tag a version). " + 'action names that irreversible action (e.g. action: "release"). ' + "policy: { kind, facts } optionally tags a review question with its kind (scope, budget, option_choice, partial_coverage, smaller_slice, slice_order) " + "and numeric or boolean facts about the recommended option; only the automatic answerer reads it, as numbers and flags, never as text. " + `emergency: "gate-waiver" (a gate refusal needs the operator's quote) or "reduced-reviewer-set"; the only two cases an automatic review may put to the operator.`;
@@ -29749,20 +29994,20 @@ function realTarget(target) {
29749
29994
  let existing = target;
29750
29995
  const rest = [];
29751
29996
  while (!entryExists(existing)) {
29752
- const parent = path67.dirname(existing);
29997
+ const parent = path68.dirname(existing);
29753
29998
  if (parent === existing)
29754
29999
  return target;
29755
- rest.unshift(path67.basename(existing));
30000
+ rest.unshift(path68.basename(existing));
29756
30001
  existing = parent;
29757
30002
  }
29758
30003
  try {
29759
- return path67.join(realpathSync4(existing), ...rest);
30004
+ return path68.join(realpathSync4(existing), ...rest);
29760
30005
  } catch {
29761
30006
  return "";
29762
30007
  }
29763
30008
  }
29764
30009
  function segmentsBelow(base, target) {
29765
- return path67.relative(base, target).split(/[\\/]/);
30010
+ return path68.relative(base, target).split(/[\\/]/);
29766
30011
  }
29767
30012
  function hasOnlyPlainSegments(base, target) {
29768
30013
  return segmentsBelow(base, target).every((segment) => PLAIN_SEGMENT.test(segment));
@@ -29771,7 +30016,7 @@ function touchesOperatorOnlyName(base, target) {
29771
30016
  return segmentsBelow(base, target).some((segment) => OPERATOR_ONLY_NAMES.has(foldFileName(segment)));
29772
30017
  }
29773
30018
  function escapesPackage(realDir, real) {
29774
- return !real.startsWith(`${realDir}${path67.sep}`);
30019
+ return !real.startsWith(`${realDir}${path68.sep}`);
29775
30020
  }
29776
30021
 
29777
30022
  class AutomaticReviewRun {
@@ -29809,11 +30054,11 @@ class AutomaticReviewRun {
29809
30054
  return false;
29810
30055
  }
29811
30056
  const realDir = realTarget(dir);
29812
- const isData = (file) => PACKAGE_DATA_EXTENSIONS.has(path67.extname(file).toLowerCase());
30057
+ const isData = (file) => PACKAGE_DATA_EXTENSIONS.has(path68.extname(file).toLowerCase());
29813
30058
  return targets.every((target) => {
29814
- const resolved = path67.resolve(this.cwd, target);
30059
+ const resolved = path68.resolve(this.cwd, target);
29815
30060
  const real = realTarget(resolved);
29816
- return resolved.startsWith(`${dir}${path67.sep}`) && !escapesPackage(realDir, real) && hasOnlyPlainSegments(dir, resolved) && hasOnlyPlainSegments(realDir, real) && isData(resolved) && isData(real) && !touchesOperatorOnlyName(dir, resolved) && !touchesOperatorOnlyName(realDir, real);
30061
+ return resolved.startsWith(`${dir}${path68.sep}`) && !escapesPackage(realDir, real) && hasOnlyPlainSegments(dir, resolved) && hasOnlyPlainSegments(realDir, real) && isData(resolved) && isData(real) && !touchesOperatorOnlyName(dir, resolved) && !touchesOperatorOnlyName(realDir, real);
29817
30062
  });
29818
30063
  }
29819
30064
  observe(command, result) {
@@ -29832,8 +30077,8 @@ class AutomaticReviewRun {
29832
30077
  if (id === undefined || printed === undefined) {
29833
30078
  return;
29834
30079
  }
29835
- const dir = path67.resolve(this.cwd, printed);
29836
- const metaproject = path67.join(path67.resolve(this.cwd), ".metaproject") + path67.sep;
30080
+ const dir = path68.resolve(this.cwd, printed);
30081
+ const metaproject = path68.join(path68.resolve(this.cwd), ".metaproject") + path68.sep;
29837
30082
  if (dir.startsWith(metaproject)) {
29838
30083
  this.binding = { id, dir };
29839
30084
  }
@@ -29878,13 +30123,13 @@ class AutomaticReviewRun {
29878
30123
  }
29879
30124
  summaryLine() {
29880
30125
  const { manual, automatic } = this.disclosure();
29881
- return `[automatic review] inputs: ${manual} manual, ${automatic} automatic${this.binding === undefined ? "" : ` (${path67.relative(this.cwd, path67.join(this.binding.dir, AUTOMATIC_REVIEW_DISCLOSURE_FILE))})`}`;
30126
+ return `[automatic review] inputs: ${manual} manual, ${automatic} automatic${this.binding === undefined ? "" : ` (${path68.relative(this.cwd, path68.join(this.binding.dir, AUTOMATIC_REVIEW_DISCLOSURE_FILE))})`}`;
29882
30127
  }
29883
30128
  async writeDisclosure() {
29884
30129
  if (this.binding === undefined) {
29885
30130
  return;
29886
30131
  }
29887
- const file = path67.join(this.binding.dir, AUTOMATIC_REVIEW_DISCLOSURE_FILE);
30132
+ const file = path68.join(this.binding.dir, AUTOMATIC_REVIEW_DISCLOSURE_FILE);
29888
30133
  await mkdir12(this.binding.dir, { recursive: true });
29889
30134
  await writeFile7(file, `${JSON.stringify(this.disclosure(), null, 2)}
29890
30135
  `, "utf8");
@@ -29945,27 +30190,27 @@ class AutomaticReviewRun {
29945
30190
  if (this.binding !== undefined) {
29946
30191
  return this.insidePackage(value);
29947
30192
  }
29948
- const resolved = path67.resolve(this.cwd, value);
29949
- return resolved.startsWith(reviewsRoot(path67.resolve(this.cwd)) + path67.sep);
30193
+ const resolved = path68.resolve(this.cwd, value);
30194
+ return resolved.startsWith(reviewsRoot(path68.resolve(this.cwd)) + path68.sep);
29950
30195
  }
29951
30196
  insidePackage(value) {
29952
30197
  const dir = this.binding?.dir;
29953
30198
  if (dir === undefined) {
29954
30199
  return false;
29955
30200
  }
29956
- const resolved = path67.resolve(this.cwd, value);
29957
- return resolved === dir || resolved.startsWith(`${dir}${path67.sep}`);
30201
+ const resolved = path68.resolve(this.cwd, value);
30202
+ return resolved === dir || resolved.startsWith(`${dir}${path68.sep}`);
29958
30203
  }
29959
30204
  insideCwd(value) {
29960
- const resolved = path67.resolve(this.cwd, value);
29961
- const root = path67.resolve(this.cwd);
29962
- return resolved === root || resolved.startsWith(`${root}${path67.sep}`);
30205
+ const resolved = path68.resolve(this.cwd, value);
30206
+ const root = path68.resolve(this.cwd);
30207
+ return resolved === root || resolved.startsWith(`${root}${path68.sep}`);
29963
30208
  }
29964
30209
  namesReviewPackage(value) {
29965
30210
  if (value === "" || value.startsWith("-"))
29966
30211
  return false;
29967
- const asPath = path67.resolve(this.cwd, value);
29968
- if (!/[\\/]/.test(value) && value !== "." && value !== ".." && !existsSync17(path67.join(asPath, "manifest.json")))
30212
+ const asPath = path68.resolve(this.cwd, value);
30213
+ if (!/[\\/]/.test(value) && value !== "." && value !== ".." && !existsSync17(path68.join(asPath, "manifest.json")))
29969
30214
  return true;
29970
30215
  return this.insideCwd(value) && isReviewPackageDir(asPath, this.cwd);
29971
30216
  }
@@ -29973,7 +30218,7 @@ class AutomaticReviewRun {
29973
30218
  if (this.binding === undefined) {
29974
30219
  return false;
29975
30220
  }
29976
- return ref === this.binding.id || path67.resolve(this.cwd, ref) === this.binding.dir;
30221
+ return ref === this.binding.id || path68.resolve(this.cwd, ref) === this.binding.dir;
29977
30222
  }
29978
30223
  }
29979
30224
 
@@ -30014,7 +30259,7 @@ function composeAbortSignals(external, internal) {
30014
30259
  var ENV_CALL_WATCHDOG_MS = "KERYX_SPAWN_CALL_WATCHDOG_MS";
30015
30260
  var DEFAULT_CALL_WATCHDOG_MS = 12 * 60000;
30016
30261
  var ABORT_GRACE_MS = 1e4;
30017
- var HUMAN_STAGES = new Set(["approval"]);
30262
+ var HUMAN_STAGES2 = new Set(["approval"]);
30018
30263
  function resolveCallWatchdogMs(env = process.env) {
30019
30264
  const raw = env[ENV_CALL_WATCHDOG_MS];
30020
30265
  if (raw === undefined || raw.trim() === "")
@@ -30024,33 +30269,53 @@ function resolveCallWatchdogMs(env = process.env) {
30024
30269
  }
30025
30270
  async function runWithCallWatchdog(name, run, options = {}) {
30026
30271
  const capMs = options.capMs ?? resolveCallWatchdogMs();
30272
+ const callId = options.callId;
30273
+ const tag = callId === undefined ? name : `${name}#${callId}`;
30027
30274
  let currentStage = "start";
30275
+ let diagKey;
30028
30276
  const stage = {
30029
30277
  get current() {
30030
30278
  return currentStage;
30031
30279
  },
30032
30280
  set current(next) {
30033
30281
  currentStage = next;
30034
- tracePhase(`${name} stage ${next}`);
30282
+ tracePhase(`${tag} stage ${next}`);
30283
+ if (diagKey !== undefined)
30284
+ callDiagnostics.stage(diagKey, next);
30035
30285
  }
30036
30286
  };
30037
- tracePhase(`${name} call start (watchdog ${capMs}ms)`);
30038
- if (capMs <= 0)
30039
- return run(options.signal, stage);
30287
+ tracePhase(`${tag} call start (watchdog ${capMs}ms)`);
30288
+ if (callId !== undefined)
30289
+ diagKey = callDiagnostics.begin(callId, name);
30290
+ if (capMs <= 0) {
30291
+ let kind = "error";
30292
+ try {
30293
+ const result = await run(options.signal, stage);
30294
+ kind = result.isError ? "error" : "ok";
30295
+ return result;
30296
+ } finally {
30297
+ if (diagKey !== undefined)
30298
+ callDiagnostics.end(diagKey, kind);
30299
+ }
30300
+ }
30040
30301
  const graceMs = options.abortGraceMs ?? ABORT_GRACE_MS;
30041
30302
  const inner = new AbortController;
30042
30303
  const composed = composeAbortSignals(options.signal, inner.signal);
30043
30304
  let timer;
30044
30305
  let graceTimer;
30045
30306
  let onAbort;
30307
+ let firedKind = undefined;
30046
30308
  const stalled = new Promise((resolve) => {
30047
30309
  const arm = () => {
30048
30310
  timer = setTimeout(() => {
30049
- if (HUMAN_STAGES.has(stage.current)) {
30311
+ if (HUMAN_STAGES2.has(stage.current)) {
30312
+ callDiagnostics.event("approval.rearm", tag);
30050
30313
  arm();
30051
30314
  return;
30052
30315
  }
30053
- tracePhase(`${name} watchdog fired at stage ${stage.current}`);
30316
+ tracePhase(`${tag} watchdog fired at stage ${stage.current}`);
30317
+ callDiagnostics.event("watchdog.fired", `${tag} stage=${stage.current}`);
30318
+ firedKind = "watchdog";
30054
30319
  resolve({
30055
30320
  output: `${name} did not finish within ${capMs}ms and was abandoned by the harness watchdog ` + `(stuck at stage "${stage.current}"; tune with ${ENV_CALL_WATCHDOG_MS}). Retry on a smaller slice instead of waiting.`,
30056
30321
  isError: true
@@ -30063,10 +30328,14 @@ async function runWithCallWatchdog(name, run, options = {}) {
30063
30328
  arm();
30064
30329
  if (options.signal !== undefined) {
30065
30330
  onAbort = () => {
30066
- graceTimer = setTimeout(() => resolve({
30067
- output: `${name} was cancelled by the operator and did not stop on its own (stage "${stage.current}"); the call was abandoned.`,
30068
- isError: true
30069
- }), graceMs);
30331
+ graceTimer = setTimeout(() => {
30332
+ firedKind = "aborted";
30333
+ callDiagnostics.event("abort.abandoned", `${tag} stage=${stage.current}`);
30334
+ resolve({
30335
+ output: `${name} was cancelled by the operator and did not stop on its own (stage "${stage.current}"); the call was abandoned.`,
30336
+ isError: true
30337
+ });
30338
+ }, graceMs);
30070
30339
  };
30071
30340
  if (options.signal.aborted)
30072
30341
  onAbort();
@@ -30075,11 +30344,15 @@ async function runWithCallWatchdog(name, run, options = {}) {
30075
30344
  }
30076
30345
  });
30077
30346
  const running = run(composed.signal, stage);
30347
+ let kind = "error";
30078
30348
  try {
30079
30349
  const outcome = await Promise.race([running, stalled]);
30080
- tracePhase(`${name} call settled`);
30350
+ kind = firedKind ?? (outcome.isError ? "error" : "ok");
30351
+ tracePhase(`${tag} call settled`);
30081
30352
  return outcome;
30082
30353
  } finally {
30354
+ if (diagKey !== undefined)
30355
+ callDiagnostics.end(diagKey, kind);
30083
30356
  if (timer !== undefined)
30084
30357
  clearTimeout(timer);
30085
30358
  if (graceTimer !== undefined)
@@ -30962,7 +31235,7 @@ function consolidateAnchors(removed) {
30962
31235
  // src/harness/tool/output-spill.ts
30963
31236
  import { createHash as createHash11 } from "crypto";
30964
31237
  import { chmod as chmod4, mkdir as mkdir14, open as open5 } from "fs/promises";
30965
- import path70 from "path";
31238
+ import path71 from "path";
30966
31239
  var TOOL_OUTPUT_SPILL_MAX_LINES = 2000;
30967
31240
  var TOOL_OUTPUT_SPILL_MAX_BYTES = 50 * 1024;
30968
31241
  var TOOL_OUTPUT_PREVIEW_CHARS = 16 * 1024;
@@ -31018,14 +31291,14 @@ var TOOL_OUTPUT_DIR_MODE = 448;
31018
31291
  var TOOL_OUTPUT_FILE_MODE = 384;
31019
31292
  var MAX_NAME_ATTEMPTS = 50;
31020
31293
  async function writeUniqueOutputFile(sessionDir, toolCallId, text) {
31021
- const dir = path70.join(sessionDir, TOOL_OUTPUT_DIRNAME);
31294
+ const dir = path71.join(sessionDir, TOOL_OUTPUT_DIRNAME);
31022
31295
  try {
31023
31296
  await mkdir14(dir, { recursive: true, mode: TOOL_OUTPUT_DIR_MODE });
31024
31297
  await chmod4(dir, TOOL_OUTPUT_DIR_MODE);
31025
31298
  const hash = createHash11("sha256").update(text).digest("hex").slice(0, 8);
31026
31299
  const base = `${Date.now()}-${hash}-${safeFileStem(toolCallId)}`;
31027
31300
  for (let attempt = 0;attempt < MAX_NAME_ATTEMPTS; attempt++) {
31028
- const filePath = path70.join(dir, `${base}${attempt === 0 ? "" : `-${attempt}`}.txt`);
31301
+ const filePath = path71.join(dir, `${base}${attempt === 0 ? "" : `-${attempt}`}.txt`);
31029
31302
  let handle;
31030
31303
  try {
31031
31304
  handle = await open5(filePath, "wx", TOOL_OUTPUT_FILE_MODE);
@@ -31051,11 +31324,11 @@ async function writeToolOutputFile(sessionDir, toolCallId, text) {
31051
31324
  return writeUniqueOutputFile(sessionDir, toolCallId, text);
31052
31325
  }
31053
31326
  function isInsideToolOutputDir(sessionDir, candidate) {
31054
- if (!path70.isAbsolute(candidate)) {
31327
+ if (!path71.isAbsolute(candidate)) {
31055
31328
  return false;
31056
31329
  }
31057
- const rel = path70.relative(path70.join(sessionDir, TOOL_OUTPUT_DIRNAME), path70.resolve(candidate));
31058
- return rel !== "" && rel !== ".." && !rel.startsWith(`..${path70.sep}`) && !path70.isAbsolute(rel);
31330
+ const rel = path71.relative(path71.join(sessionDir, TOOL_OUTPUT_DIRNAME), path71.resolve(candidate));
31331
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${path71.sep}`) && !path71.isAbsolute(rel);
31059
31332
  }
31060
31333
  async function spillToolOutput(text, ctx) {
31061
31334
  if (ctx.sessionDir === undefined || !exceedsSpillThreshold(text)) {
@@ -31377,12 +31650,12 @@ import {
31377
31650
  renameSync as renameSync5,
31378
31651
  writeFileSync as writeFileSync6
31379
31652
  } from "fs";
31380
- import path72 from "path";
31653
+ import path73 from "path";
31381
31654
 
31382
31655
  // src/session/paths.ts
31383
31656
  import { existsSync as existsSync18 } from "fs";
31384
31657
  import { homedir as homedir3 } from "os";
31385
- import path71 from "path";
31658
+ import path72 from "path";
31386
31659
  function keryxDataDir(override) {
31387
31660
  if (override !== undefined && override.length > 0) {
31388
31661
  return override;
@@ -31394,22 +31667,22 @@ function keryxDataDir(override) {
31394
31667
  const home = homedir3();
31395
31668
  if (process.platform === "win32") {
31396
31669
  const appData = process.env.APPDATA;
31397
- const base = appData !== undefined && appData.length > 0 ? appData : path71.join(home, "AppData", "Roaming");
31398
- return path71.join(base, "keryx");
31670
+ const base = appData !== undefined && appData.length > 0 ? appData : path72.join(home, "AppData", "Roaming");
31671
+ return path72.join(base, "keryx");
31399
31672
  }
31400
31673
  const xdg = process.env.XDG_DATA_HOME;
31401
- const base = xdg !== undefined && xdg.length > 0 ? xdg : path71.join(home, ".local", "share");
31402
- return path71.join(base, "keryx");
31674
+ const base = xdg !== undefined && xdg.length > 0 ? xdg : path72.join(home, ".local", "share");
31675
+ return path72.join(base, "keryx");
31403
31676
  }
31404
31677
  function resolveProjectRoot2(cwd) {
31405
- const abs = path71.resolve(cwd);
31678
+ const abs = path72.resolve(cwd);
31406
31679
  let dir = abs;
31407
31680
  for (;; ) {
31408
- const gitPath = path71.join(dir, ".git");
31681
+ const gitPath = path72.join(dir, ".git");
31409
31682
  if (existsSync18(gitPath)) {
31410
31683
  return dir;
31411
31684
  }
31412
- const parent = path71.dirname(dir);
31685
+ const parent = path72.dirname(dir);
31413
31686
  if (parent === dir) {
31414
31687
  break;
31415
31688
  }
@@ -31418,12 +31691,12 @@ function resolveProjectRoot2(cwd) {
31418
31691
  return abs;
31419
31692
  }
31420
31693
  function projectKeyFromPath(projectPath) {
31421
- const abs = path71.resolve(projectPath);
31694
+ const abs = path72.resolve(projectPath);
31422
31695
  const encoded = encodeURIComponent(abs);
31423
31696
  if (encoded.length <= 200) {
31424
31697
  return encoded;
31425
31698
  }
31426
- const base = path71.basename(abs).replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 40);
31699
+ const base = path72.basename(abs).replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 40);
31427
31700
  let h = 0;
31428
31701
  for (let i = 0;i < abs.length; i++) {
31429
31702
  h = Math.imul(31, h) + abs.charCodeAt(i) | 0;
@@ -31433,10 +31706,10 @@ function projectKeyFromPath(projectPath) {
31433
31706
  }
31434
31707
  function projectSessionsDir(projectPath, dataDir) {
31435
31708
  const key = projectKeyFromPath(resolveProjectRoot2(projectPath));
31436
- return path71.join(keryxDataDir(dataDir), "sessions", key);
31709
+ return path72.join(keryxDataDir(dataDir), "sessions", key);
31437
31710
  }
31438
31711
  function sessionDir(projectPath, sessionId, dataDir) {
31439
- return path71.join(projectSessionsDir(projectPath, dataDir), sessionId);
31712
+ return path72.join(projectSessionsDir(projectPath, dataDir), sessionId);
31440
31713
  }
31441
31714
 
31442
31715
  // src/session/store.ts
@@ -31532,7 +31805,7 @@ function parseRemote(value) {
31532
31805
  function readSummaryFile(file) {
31533
31806
  let pending;
31534
31807
  try {
31535
- pending = readPendingHistory(path72.dirname(file));
31808
+ pending = readPendingHistory(path73.dirname(file));
31536
31809
  } catch {
31537
31810
  pending = undefined;
31538
31811
  }
@@ -31584,11 +31857,11 @@ class TranscriptUnreadableError extends Error {
31584
31857
  }
31585
31858
  }
31586
31859
  function readJsonl(file) {
31587
- const pending = readPendingHistory(path72.dirname(file));
31860
+ const pending = readPendingHistory(path73.dirname(file));
31588
31861
  if (pending === undefined && !existsSync19(file)) {
31589
31862
  return [];
31590
31863
  }
31591
- const read = pending !== undefined ? { ok: true, text: pending.files[path72.basename(file)] } : readTranscriptFile(file);
31864
+ const read = pending !== undefined ? { ok: true, text: pending.files[path73.basename(file)] } : readTranscriptFile(file);
31592
31865
  if (!read.ok) {
31593
31866
  throw new TranscriptUnreadableError(file, read.reason);
31594
31867
  }
@@ -31639,11 +31912,11 @@ function listSessions(cwd, dataDir) {
31639
31912
  if (name.startsWith(".")) {
31640
31913
  continue;
31641
31914
  }
31642
- const summary = readSummaryFile(path72.join(root, name, "summary.json"));
31915
+ const summary = readSummaryFile(path73.join(root, name, "summary.json"));
31643
31916
  if (summary === undefined) {
31644
31917
  continue;
31645
31918
  }
31646
- if (path72.resolve(summary.projectPath) !== path72.resolve(projectPath)) {
31919
+ if (path73.resolve(summary.projectPath) !== path73.resolve(projectPath)) {
31647
31920
  continue;
31648
31921
  }
31649
31922
  out.push(summary);
@@ -31676,15 +31949,15 @@ async function readSessionSlate(cwd, sessionId, dataDir) {
31676
31949
  }
31677
31950
  function loadContext(cwd, sessionId, dataDir) {
31678
31951
  const dir = sessionDir(resolveProjectRoot2(cwd), sessionId, dataDir);
31679
- const contextPath = path72.join(dir, "context.jsonl");
31952
+ const contextPath = path73.join(dir, "context.jsonl");
31680
31953
  if (readPendingHistory(dir) !== undefined || existsSync19(contextPath)) {
31681
31954
  return readJsonl(contextPath);
31682
31955
  }
31683
- return readJsonl(path72.join(dir, "transcript.jsonl"));
31956
+ return readJsonl(path73.join(dir, "transcript.jsonl"));
31684
31957
  }
31685
31958
  function loadArchive(cwd, sessionId, dataDir, onDegraded) {
31686
31959
  const dir = sessionDir(resolveProjectRoot2(cwd), sessionId, dataDir);
31687
- const archivePath = path72.join(dir, "archive.jsonl");
31960
+ const archivePath = path73.join(dir, "archive.jsonl");
31688
31961
  if (readPendingHistory(dir) !== undefined || existsSync19(archivePath)) {
31689
31962
  try {
31690
31963
  const archive = readJsonl(archivePath);
@@ -32778,13 +33051,13 @@ async function executeWaves(tasks, waves, deps) {
32778
33051
  init_fs();
32779
33052
  init_slate();
32780
33053
  import { mkdir as mkdir15, readFile as readFile33 } from "fs/promises";
32781
- import path73 from "path";
33054
+ import path74 from "path";
32782
33055
  var listeners = new Set;
32783
33056
  function clonePlan(plan) {
32784
33057
  return { revision: plan.revision, items: plan.items.map((item) => ({ ...item })) };
32785
33058
  }
32786
33059
  function executionPlanPath(dir) {
32787
- return path73.join(dir, "plan.json");
33060
+ return path74.join(dir, "plan.json");
32788
33061
  }
32789
33062
  async function readPlanFile(dir) {
32790
33063
  let raw;
@@ -32921,7 +33194,7 @@ init_fs();
32921
33194
  init_slate();
32922
33195
  import { createHash as createHash23, randomUUID as randomUUID11 } from "crypto";
32923
33196
  import { mkdir as mkdir21 } from "fs/promises";
32924
- import path87 from "path";
33197
+ import path88 from "path";
32925
33198
 
32926
33199
  // src/sac/trusted-wrap-up.ts
32927
33200
  import { createHash as createHash13, randomUUID as randomUUID6 } from "crypto";
@@ -32965,12 +33238,12 @@ function digest(value) {
32965
33238
  init_fs();
32966
33239
  import { createHash as createHash22, randomUUID as randomUUID9 } from "crypto";
32967
33240
  import { appendFile as appendFile4, mkdir as mkdir20, readdir as readdir21, readFile as readFile44 } from "fs/promises";
32968
- import path86 from "path";
33241
+ import path87 from "path";
32969
33242
 
32970
33243
  // src/sac/index.ts
32971
33244
  import { access as access2, readFile as readFile34, realpath as realpath10 } from "fs/promises";
32972
33245
  import { createHash as createHash14 } from "crypto";
32973
- import path74 from "path";
33246
+ import path75 from "path";
32974
33247
  import { fileURLToPath as fileURLToPath3 } from "url";
32975
33248
 
32976
33249
  // src/sac/workspace-reference.ts
@@ -32993,21 +33266,21 @@ var normativeSchemaFiles = {
32993
33266
  "review-decision": "review-decision.schema.json"
32994
33267
  };
32995
33268
  var normativeSchemas = new Map;
32996
- var NORMATIVE_SCHEMA_DIR = path74.join("docs", "requirements", "shared-agent-context", "schemas");
33269
+ var NORMATIVE_SCHEMA_DIR = path75.join("docs", "requirements", "shared-agent-context", "schemas");
32997
33270
  async function resolveSacNormativeSchemaPath(fileName, searchFrom = [fileURLToPath3(new URL(".", import.meta.url)), process.cwd()]) {
32998
33271
  const seen = new Set;
32999
33272
  for (const start of searchFrom) {
33000
- let dir = path74.resolve(start);
33273
+ let dir = path75.resolve(start);
33001
33274
  for (let i = 0;i < 10; i++) {
33002
33275
  if (seen.has(dir))
33003
33276
  break;
33004
33277
  seen.add(dir);
33005
- const candidate = path74.join(dir, NORMATIVE_SCHEMA_DIR, fileName);
33278
+ const candidate = path75.join(dir, NORMATIVE_SCHEMA_DIR, fileName);
33006
33279
  try {
33007
33280
  await access2(candidate);
33008
33281
  return candidate;
33009
33282
  } catch {}
33010
- const parent = path74.dirname(dir);
33283
+ const parent = path75.dirname(dir);
33011
33284
  if (parent === dir)
33012
33285
  break;
33013
33286
  dir = parent;
@@ -33669,12 +33942,12 @@ class SacReferenceError extends Error {
33669
33942
  code = "unsafe_workspace_reference";
33670
33943
  }
33671
33944
  async function resolveWorkspaceReference(input) {
33672
- if (!workspacePathPattern.test(input.uri) || path74.isAbsolute(input.uri) || /^[a-z][a-z0-9+.-]*:/i.test(input.uri) || input.uri.includes("\\"))
33945
+ if (!workspacePathPattern.test(input.uri) || path75.isAbsolute(input.uri) || /^[a-z][a-z0-9+.-]*:/i.test(input.uri) || input.uri.includes("\\"))
33673
33946
  throw new SacReferenceError("unsafe workspace reference");
33674
- const lexicalRoot = path74.resolve(input.workspaceRoot);
33947
+ const lexicalRoot = path75.resolve(input.workspaceRoot);
33675
33948
  const root = await realpath10(lexicalRoot);
33676
- const candidate = path74.resolve(lexicalRoot, input.uri.slice(2));
33677
- if (candidate !== lexicalRoot && !candidate.startsWith(`${lexicalRoot}${path74.sep}`))
33949
+ const candidate = path75.resolve(lexicalRoot, input.uri.slice(2));
33950
+ if (candidate !== lexicalRoot && !candidate.startsWith(`${lexicalRoot}${path75.sep}`))
33678
33951
  throw new SacReferenceError("workspace reference escapes root");
33679
33952
  let resolved;
33680
33953
  try {
@@ -33682,7 +33955,7 @@ async function resolveWorkspaceReference(input) {
33682
33955
  } catch {
33683
33956
  throw new SacReferenceError("workspace reference is not resolvable");
33684
33957
  }
33685
- if (resolved !== root && !resolved.startsWith(`${root}${path74.sep}`))
33958
+ if (resolved !== root && !resolved.startsWith(`${root}${path75.sep}`))
33686
33959
  throw new SacReferenceError("workspace reference escapes root after realpath");
33687
33960
  return candidate;
33688
33961
  }
@@ -33738,16 +34011,16 @@ async function evaluateStrictSacGuard(input) {
33738
34011
  init_fs();
33739
34012
  import { mkdir as mkdir16, readdir as readdir19, readFile as readFile35 } from "fs/promises";
33740
34013
  import { createHash as createHash15, randomUUID as randomUUID7 } from "crypto";
33741
- import path76 from "path";
34014
+ import path77 from "path";
33742
34015
 
33743
34016
  // src/sac/secure-resource-read.ts
33744
34017
  init_contained_read();
33745
34018
  init_descriptor_read();
33746
- import path75 from "path";
34019
+ import path76 from "path";
33747
34020
  function readWorkspaceFileNoFollow(workspaceRoot, absolutePath) {
33748
- const relativePath = path75.relative(workspaceRoot, absolutePath);
33749
- const components = relativePath.split(path75.sep);
33750
- if (!relativePath || path75.isAbsolute(relativePath) || components.some((component) => !component || component === "." || component === "..")) {
34021
+ const relativePath = path76.relative(workspaceRoot, absolutePath);
34022
+ const components = relativePath.split(path76.sep);
34023
+ if (!relativePath || path76.isAbsolute(relativePath) || components.some((component) => !component || component === "." || component === "..")) {
33751
34024
  throw new Error("safe source path is not workspace-relative");
33752
34025
  }
33753
34026
  return readDescriptorChain(workspaceRoot, absolutePath, {
@@ -33774,8 +34047,8 @@ class WorkspaceService {
33774
34047
  now;
33775
34048
  constructor(options) {
33776
34049
  this.options = options;
33777
- this.root = path76.resolve(options.workspaceRoot);
33778
- this.storageRoot = path76.resolve(options.storageRoot ?? path76.join(this.root, ".metaproject", "workspaces"));
34050
+ this.root = path77.resolve(options.workspaceRoot);
34051
+ this.storageRoot = path77.resolve(options.storageRoot ?? path77.join(this.root, ".metaproject", "workspaces"));
33779
34052
  this.now = options.now ?? (() => new Date);
33780
34053
  }
33781
34054
  async create(input) {
@@ -34101,13 +34374,13 @@ class WorkspaceService {
34101
34374
  return parsed;
34102
34375
  }
34103
34376
  workspaceDir(id) {
34104
- return path76.join(this.storageRoot, id);
34377
+ return path77.join(this.storageRoot, id);
34105
34378
  }
34106
34379
  manifestPath(id) {
34107
- return path76.join(this.workspaceDir(id), "workspace.json");
34380
+ return path77.join(this.workspaceDir(id), "workspace.json");
34108
34381
  }
34109
34382
  lockPath(id) {
34110
- return path76.join(this.storageRoot, `.${id}.lock`);
34383
+ return path77.join(this.storageRoot, `.${id}.lock`);
34111
34384
  }
34112
34385
  timestamp() {
34113
34386
  return this.now().toISOString();
@@ -34162,7 +34435,7 @@ function bindingHash(owner, intent) {
34162
34435
  // src/sac/session-wrap-up.ts
34163
34436
  import { createHash as createHash17 } from "crypto";
34164
34437
  import { mkdir as mkdir17, writeFile as writeFile8 } from "fs/promises";
34165
- import path77 from "path";
34438
+ import path78 from "path";
34166
34439
  init_wrap_up_evidence();
34167
34440
  var WRAP_UP_TTL_MS = 60 * 60 * 1000;
34168
34441
 
@@ -34178,7 +34451,7 @@ function sessionEvidenceRef(workspaceId, sessionId) {
34178
34451
  }
34179
34452
  async function resolveSessionWrapUp(input) {
34180
34453
  const now = input.now ?? (() => new Date);
34181
- const sessionId = path77.posix.basename(input.sourceRef, ".md");
34454
+ const sessionId = path78.posix.basename(input.sourceRef, ".md");
34182
34455
  const summary = findSession(input.cwd, sessionId);
34183
34456
  if (summary === undefined || input.sourceRef !== sessionEvidenceRef(input.workspaceId, summary.id)) {
34184
34457
  throw new SessionWrapUpError("session_not_found", `no session matching "${input.sourceRef}" in this project \u2014 use \`keryx sessions list\``);
@@ -34195,7 +34468,7 @@ async function resolveSessionWrapUp(input) {
34195
34468
  throw new SessionWrapUpError("session_unreadable", `session "${summary.id}" could not be read: ${cause.message}`);
34196
34469
  }
34197
34470
  const relPath = sessionEvidenceRef(input.workspaceId, summary.id).slice(2);
34198
- const evidenceDir = path77.dirname(relPath);
34471
+ const evidenceDir = path78.dirname(relPath);
34199
34472
  const slate = await readSessionSlate(input.cwd, summary.id);
34200
34473
  const diff = await gitDiff(input.cwd);
34201
34474
  const diffBody = diff.kind === "measured" ? diff.text : unmeasurableDiffBody(diff.detail);
@@ -34217,23 +34490,23 @@ async function resolveSessionWrapUp(input) {
34217
34490
  ""
34218
34491
  ].join(`
34219
34492
  `);
34220
- const wrapUpRelPath = path77.join(evidenceDir, `${summary.id}.wrap-up.md`);
34221
- const diffRelPath = path77.join(evidenceDir, `${summary.id}.diff.txt`);
34222
- const noticeRelPath = path77.join(evidenceDir, `${summary.id}.redaction.md`);
34493
+ const wrapUpRelPath = path78.join(evidenceDir, `${summary.id}.wrap-up.md`);
34494
+ const diffRelPath = path78.join(evidenceDir, `${summary.id}.diff.txt`);
34495
+ const noticeRelPath = path78.join(evidenceDir, `${summary.id}.redaction.md`);
34223
34496
  const floor = await applyEvidenceRedactionFloor(input.cwd, [
34224
- { name: path77.basename(relPath), content: markdown, path: relPath, source: "generated" },
34225
- { name: path77.basename(wrapUpRelPath), content: wrapUpMarkdown, path: wrapUpRelPath, source: "generated" },
34226
- { name: path77.basename(diffRelPath), content: diffBody, path: diffRelPath, source: "tool-output" }
34497
+ { name: path78.basename(relPath), content: markdown, path: relPath, source: "generated" },
34498
+ { name: path78.basename(wrapUpRelPath), content: wrapUpMarkdown, path: wrapUpRelPath, source: "generated" },
34499
+ { name: path78.basename(diffRelPath), content: diffBody, path: diffRelPath, source: "tool-output" }
34227
34500
  ]);
34228
34501
  if (!floor.ok)
34229
34502
  throw new SessionWrapUpError("security_denied", floor.reason);
34230
34503
  const [safeSession, safeWrapUp, safeDiff] = floor.bodies;
34231
- await mkdir17(path77.join(input.cwd, evidenceDir), { recursive: true });
34232
- await writeFile8(path77.join(input.cwd, relPath), safeSession.content, "utf8");
34233
- await writeFile8(path77.join(input.cwd, wrapUpRelPath), safeWrapUp.content, "utf8");
34234
- await writeFile8(path77.join(input.cwd, diffRelPath), safeDiff.content, "utf8");
34504
+ await mkdir17(path78.join(input.cwd, evidenceDir), { recursive: true });
34505
+ await writeFile8(path78.join(input.cwd, relPath), safeSession.content, "utf8");
34506
+ await writeFile8(path78.join(input.cwd, wrapUpRelPath), safeWrapUp.content, "utf8");
34507
+ await writeFile8(path78.join(input.cwd, diffRelPath), safeDiff.content, "utf8");
34235
34508
  if (floor.notice !== undefined)
34236
- await writeFile8(path77.join(input.cwd, noticeRelPath), floor.notice, "utf8");
34509
+ await writeFile8(path78.join(input.cwd, noticeRelPath), floor.notice, "utf8");
34237
34510
  const observedAt = now().toISOString();
34238
34511
  const evidence = [
34239
34512
  { kind: "wrap-up", uri: `./${wrapUpRelPath}`, revision: createHash17("sha256").update(safeWrapUp.content).digest("hex"), observedAt },
@@ -34256,13 +34529,13 @@ async function resolveSessionWrapUp(input) {
34256
34529
  init_fs();
34257
34530
  import { createHash as createHash18, randomBytes as randomBytes3 } from "crypto";
34258
34531
  import { readFile as readFile36 } from "fs/promises";
34259
- import path78 from "path";
34532
+ import path79 from "path";
34260
34533
  var CONFIRM_TOKEN_TTL_MS = 2 * 60000;
34261
34534
  function confirmTokenPath(cwd, workspaceId, proposalId) {
34262
- return path78.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.confirm-token.json`);
34535
+ return path79.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.confirm-token.json`);
34263
34536
  }
34264
34537
  function confirmReceiptPath(cwd, workspaceId, proposalId, idempotencyKey) {
34265
- return path78.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${sha256(idempotencyKey)}.confirm-receipt.json`);
34538
+ return path79.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${sha256(idempotencyKey)}.confirm-receipt.json`);
34266
34539
  }
34267
34540
  function sha256(text) {
34268
34541
  return createHash18("sha256").update(text).digest("hex");
@@ -34303,21 +34576,21 @@ init_store();
34303
34576
  init_config4();
34304
34577
  import { readFile as readFile38, readdir as readdir20 } from "fs/promises";
34305
34578
  import { randomUUID as randomUUID8 } from "crypto";
34306
- import path81 from "path";
34579
+ import path82 from "path";
34307
34580
 
34308
34581
  // src/sac/proposal-evidence.ts
34309
34582
  init_fs();
34310
34583
  import { createHash as createHash19 } from "crypto";
34311
34584
  import { readFile as readFile37, rm as rm6 } from "fs/promises";
34312
- import path80 from "path";
34585
+ import path81 from "path";
34313
34586
  function proposalPath(cwd, workspaceId, proposalId) {
34314
- return path80.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.json`);
34587
+ return path81.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.json`);
34315
34588
  }
34316
34589
  function ownerReceiptPath(cwd, owner, workspaceId, idempotencyKey) {
34317
- return path80.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-write-receipts`, `${idempotencyKey}.json`);
34590
+ return path81.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-write-receipts`, `${idempotencyKey}.json`);
34318
34591
  }
34319
34592
  function proposalNotePath(cwd, workspaceId, proposalId) {
34320
- return path80.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.note.txt`);
34593
+ return path81.join(cwd, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.note.txt`);
34321
34594
  }
34322
34595
  async function readVerifiedProposalEvidence(cwd, workspaceId, proposalId) {
34323
34596
  let proposal;
@@ -34331,7 +34604,7 @@ async function readVerifiedProposalEvidence(cwd, workspaceId, proposalId) {
34331
34604
  return { ok: false, code: "no_evidence_to_write" };
34332
34605
  let content;
34333
34606
  try {
34334
- content = await readFile37(path80.join(cwd, evidence.uri), "utf8");
34607
+ content = await readFile37(path81.join(cwd, evidence.uri), "utf8");
34335
34608
  } catch {
34336
34609
  return { ok: false, code: "evidence_file_unreadable" };
34337
34610
  }
@@ -34361,22 +34634,22 @@ function targetRelPath(targetRef) {
34361
34634
  return targetRef.replace(/^\.\//, "");
34362
34635
  }
34363
34636
  function targetAbsolutePath(cwd, targetRef) {
34364
- return path80.join(cwd, ".metaproject", targetRelPath(targetRef));
34637
+ return path81.join(cwd, ".metaproject", targetRelPath(targetRef));
34365
34638
  }
34366
34639
  function targetKey(targetRef) {
34367
34640
  return digestOf(targetRelPath(targetRef)).slice(0, 32);
34368
34641
  }
34369
34642
  function ownerTargetVersionPath(cwd, owner, workspaceId, targetRef) {
34370
- return path80.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-target-versions`, `${targetKey(targetRef)}.json`);
34643
+ return path81.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-target-versions`, `${targetKey(targetRef)}.json`);
34371
34644
  }
34372
34645
  function ownerTargetLockPath(cwd, owner, targetRef) {
34373
- return path80.join(cwd, ".metaproject", "data", "sac", "target-locks", owner, `${targetKey(targetRef)}.lock`);
34646
+ return path81.join(cwd, ".metaproject", "data", "sac", "target-locks", owner, `${targetKey(targetRef)}.lock`);
34374
34647
  }
34375
34648
  function ownerStagingDir(cwd, owner, workspaceId, idempotencyKey) {
34376
- return path80.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-write-staging`, digestOf(idempotencyKey).slice(0, 32));
34649
+ return path81.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-write-staging`, digestOf(idempotencyKey).slice(0, 32));
34377
34650
  }
34378
34651
  function ownerConflictDir(cwd, owner, workspaceId, idempotencyKey) {
34379
- return path80.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-write-conflicts`, digestOf(idempotencyKey).slice(0, 32));
34652
+ return path81.join(cwd, ".metaproject", "workspaces", workspaceId, `${owner}-write-conflicts`, digestOf(idempotencyKey).slice(0, 32));
34380
34653
  }
34381
34654
  async function readJson7(file) {
34382
34655
  try {
@@ -34447,7 +34720,7 @@ async function applyGuardedTargetWrite(input) {
34447
34720
  staged: input.staged,
34448
34721
  stagedAt: receipt.completedAt
34449
34722
  };
34450
- await writeFileAtomic(path80.join(ownerStagingDir(cwd, owner, intent.workspaceId, intent.idempotencyKey), "plan.json"), `${JSON.stringify(staged, null, 2)}
34723
+ await writeFileAtomic(path81.join(ownerStagingDir(cwd, owner, intent.workspaceId, intent.idempotencyKey), "plan.json"), `${JSON.stringify(staged, null, 2)}
34451
34724
  `);
34452
34725
  const applied = await input.apply(input.staged);
34453
34726
  if (!applied.ok) {
@@ -34473,15 +34746,15 @@ async function recoverStagedOwnerWrite(input) {
34473
34746
  });
34474
34747
  }
34475
34748
  async function readStagedOwnerWrite(cwd, owner, workspaceId, idempotencyKey) {
34476
- return readJson7(path80.join(ownerStagingDir(cwd, owner, workspaceId, idempotencyKey), "plan.json"));
34749
+ return readJson7(path81.join(ownerStagingDir(cwd, owner, workspaceId, idempotencyKey), "plan.json"));
34477
34750
  }
34478
34751
  async function recordConflict(input) {
34479
34752
  const base = { targetRef: input.targetRef, expectedVersion: input.expectedVersion, currentVersion: input.currentVersion };
34480
34753
  if (input.proposedContent === undefined)
34481
34754
  return base;
34482
34755
  const dir = ownerConflictDir(input.cwd, input.owner, input.intent.workspaceId, input.intent.idempotencyKey);
34483
- await writeFileAtomic(path80.join(dir, "proposed"), input.proposedContent);
34484
- const diffRef = `./workspaces/${input.intent.workspaceId}/${input.owner}-write-conflicts/${path80.basename(dir)}/proposed`;
34756
+ await writeFileAtomic(path81.join(dir, "proposed"), input.proposedContent);
34757
+ const diffRef = `./workspaces/${input.intent.workspaceId}/${input.owner}-write-conflicts/${path81.basename(dir)}/proposed`;
34485
34758
  return { ...base, diffRef };
34486
34759
  }
34487
34760
 
@@ -34531,7 +34804,7 @@ async function resolveWorkspaceModule(cwd, workspaceId) {
34531
34804
  }
34532
34805
  }
34533
34806
  async function collectWikiDecisionEntries(cwd) {
34534
- const dir = path81.join(cwd, ".metaproject", "wiki", "decisions");
34807
+ const dir = path82.join(cwd, ".metaproject", "wiki", "decisions");
34535
34808
  let files;
34536
34809
  try {
34537
34810
  files = (await readdir20(dir)).filter((name) => name.endsWith(".md"));
@@ -34540,12 +34813,12 @@ async function collectWikiDecisionEntries(cwd) {
34540
34813
  }
34541
34814
  const entries = [];
34542
34815
  for (const file of files) {
34543
- const absolutePath = path81.join(dir, file);
34816
+ const absolutePath = path82.join(dir, file);
34544
34817
  try {
34545
34818
  const content = await readFile38(absolutePath, "utf8");
34546
34819
  entries.push({
34547
34820
  absolutePath,
34548
- relativePath: path81.posix.join("decisions", file),
34821
+ relativePath: path82.posix.join("decisions", file),
34549
34822
  type: extractHeaderField(content, "Type") ?? "decision",
34550
34823
  title: extractTitle(content),
34551
34824
  version: extractHeaderField(content, "Version") ?? null,
@@ -34767,7 +35040,7 @@ function createRealMemoryOwnerWriter(cwd, opts) {
34767
35040
  init_service4();
34768
35041
  init_guard2();
34769
35042
  import { readFile as readFile42 } from "fs/promises";
34770
- import path85 from "path";
35043
+ import path86 from "path";
34771
35044
  function renderWrapUpDecisionPage(input) {
34772
35045
  const note = input.note?.trim();
34773
35046
  return `# ${input.title}
@@ -34808,7 +35081,7 @@ export is the source of truth for what actually happened.
34808
35081
  `;
34809
35082
  }
34810
35083
  function wikiPageRelativePath(proposalId) {
34811
- return path85.posix.join("decisions", `sac-${proposalId}.md`);
35084
+ return path86.posix.join("decisions", `sac-${proposalId}.md`);
34812
35085
  }
34813
35086
  function createRealWikiOwnerWriter(cwd, opts) {
34814
35087
  const now = opts?.now ?? (() => new Date);
@@ -34816,7 +35089,7 @@ function createRealWikiOwnerWriter(cwd, opts) {
34816
35089
  const relativePath = staged.relativePath;
34817
35090
  const content = staged.content;
34818
35091
  const history = await openWikiWriteContext(cwd, "sac proposal accept");
34819
- await writeWikiPage(history, path85.join(cwd, ".metaproject", "wiki", relativePath), content);
35092
+ await writeWikiPage(history, path86.join(cwd, ".metaproject", "wiki", relativePath), content);
34820
35093
  return { ok: true };
34821
35094
  };
34822
35095
  return {
@@ -34965,7 +35238,7 @@ class ProposalLifecycleService {
34965
35238
  now;
34966
35239
  constructor(options) {
34967
35240
  this.options = options;
34968
- this.root = path86.resolve(options.workspaceRoot);
35241
+ this.root = path87.resolve(options.workspaceRoot);
34969
35242
  this.now = options.now ?? (() => new Date);
34970
35243
  }
34971
35244
  async create(input) {
@@ -34985,7 +35258,7 @@ class ProposalLifecycleService {
34985
35258
  if (manifest.status === "archived")
34986
35259
  throw new ProposalLifecycleError("guard_denied", "workspace is archived");
34987
35260
  const file = this.proposalPath(workspaceId, proposal.id);
34988
- await mkdir20(path86.dirname(file), { recursive: true, mode: 448 });
35261
+ await mkdir20(path87.dirname(file), { recursive: true, mode: 448 });
34989
35262
  return withFileLock2(`${file}.lock`, async () => {
34990
35263
  const consume = this.options.wrapUpAuthority.consume(input.wrapUp, { actor, workspaceId });
34991
35264
  if (consume !== "ok")
@@ -35013,7 +35286,7 @@ class ProposalLifecycleService {
35013
35286
  return this.options.workspaces.withAuthorizedActor({ actorContext: actor, workspaceId: input.workspaceId, action: "review", execute: async (manifest) => {
35014
35287
  const proposal = await this.loadProposal(input.workspaceId, input.proposalId);
35015
35288
  const ledger = this.ledgerPath(input.workspaceId);
35016
- await mkdir20(path86.dirname(ledger), { recursive: true, mode: 448 });
35289
+ await mkdir20(path87.dirname(ledger), { recursive: true, mode: 448 });
35017
35290
  return withFileLock2(`${ledger}.lock`, async () => {
35018
35291
  const records = (await this.records(ledger)).filter((record) => record.proposalId === proposal.id);
35019
35292
  const events = records.filter((record) => record.recordType === "proposal-transition");
@@ -35055,7 +35328,7 @@ class ProposalLifecycleService {
35055
35328
  } });
35056
35329
  }
35057
35330
  async listProposedProposals(workspaceId) {
35058
- const proposalsDir = path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals");
35331
+ const proposalsDir = path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals");
35059
35332
  let entries;
35060
35333
  try {
35061
35334
  entries = (await readdir21(proposalsDir)).filter((name) => name.endsWith(".json"));
@@ -35067,7 +35340,7 @@ class ProposalLifecycleService {
35067
35340
  const proposals = [];
35068
35341
  for (const entry of entries) {
35069
35342
  try {
35070
- const parsed = JSON.parse(await readFile44(path86.join(proposalsDir, entry), "utf8"));
35343
+ const parsed = JSON.parse(await readFile44(path87.join(proposalsDir, entry), "utf8"));
35071
35344
  if (parsed.recordType === "proposal-created")
35072
35345
  proposals.push(parsed);
35073
35346
  } catch {}
@@ -35333,31 +35606,31 @@ class ProposalLifecycleService {
35333
35606
  }
35334
35607
  }
35335
35608
  proposalPath(workspaceId, proposalId) {
35336
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.json`);
35609
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.json`);
35337
35610
  }
35338
35611
  decisionRef(proposalId, key) {
35339
35612
  return `./proposals/${proposalId}.${hash2(key)}.decision.json`;
35340
35613
  }
35341
35614
  decisionPath(workspaceId, proposalId, key) {
35342
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.decision.json`);
35615
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.decision.json`);
35343
35616
  }
35344
35617
  approvalRef(proposalId, key) {
35345
35618
  return `./proposals/${proposalId}.${hash2(key)}.approval.json`;
35346
35619
  }
35347
35620
  approvalPath(workspaceId, proposalId, key) {
35348
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.approval.json`);
35621
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.approval.json`);
35349
35622
  }
35350
35623
  writeResultPath(workspaceId, proposalId, key) {
35351
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.write-result.json`);
35624
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.write-result.json`);
35352
35625
  }
35353
35626
  intentRef(proposalId, key) {
35354
35627
  return `./proposals/${proposalId}.${hash2(key)}.write-intent.json`;
35355
35628
  }
35356
35629
  intentPath(workspaceId, proposalId, key) {
35357
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.write-intent.json`);
35630
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.write-intent.json`);
35358
35631
  }
35359
35632
  attemptPath(workspaceId, proposalId, key) {
35360
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.owner-write-attempt.json`);
35633
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "proposals", `${proposalId}.${hash2(key)}.owner-write-attempt.json`);
35361
35634
  }
35362
35635
  async loadWriteResult(workspaceId, proposalId, key) {
35363
35636
  try {
@@ -35384,7 +35657,7 @@ class ProposalLifecycleService {
35384
35657
  }
35385
35658
  }
35386
35659
  ledgerPath(workspaceId) {
35387
- return path86.join(this.root, ".metaproject", "workspaces", workspaceId, "activity.jsonl");
35660
+ return path87.join(this.root, ".metaproject", "workspaces", workspaceId, "activity.jsonl");
35388
35661
  }
35389
35662
  timestamp() {
35390
35663
  return this.now().toISOString();
@@ -35613,11 +35886,11 @@ async function resolveMachineWrapUp(input) {
35613
35886
  `;
35614
35887
  const seedsJson = `${JSON.stringify(seedsForKind.map((seed) => ({ text: seed.text, source: describeSource(seed.source) })), null, 2)}
35615
35888
  `;
35616
- const evidenceRelBase = path87.posix.join(".metaproject", "workspaces", input.workspaceId, "machine-evidence");
35889
+ const evidenceRelBase = path88.posix.join(".metaproject", "workspaces", input.workspaceId, "machine-evidence");
35617
35890
  const floor = await applyEvidenceRedactionFloor(input.cwd, [
35618
- { name: `${input.kind}.diff.txt`, content: diffBody, path: path87.posix.join(evidenceRelBase, `${input.kind}.diff.txt`), source: "tool-output" },
35619
- { name: `${input.kind}.flow.json`, content: flowSnapshotJson, path: path87.posix.join(evidenceRelBase, `${input.kind}.flow.json`), source: "generated" },
35620
- { name: `${input.kind}.seeds.json`, content: seedsJson, path: path87.posix.join(evidenceRelBase, `${input.kind}.seeds.json`), source: "generated" }
35891
+ { name: `${input.kind}.diff.txt`, content: diffBody, path: path88.posix.join(evidenceRelBase, `${input.kind}.diff.txt`), source: "tool-output" },
35892
+ { name: `${input.kind}.flow.json`, content: flowSnapshotJson, path: path88.posix.join(evidenceRelBase, `${input.kind}.flow.json`), source: "generated" },
35893
+ { name: `${input.kind}.seeds.json`, content: seedsJson, path: path88.posix.join(evidenceRelBase, `${input.kind}.seeds.json`), source: "generated" }
35621
35894
  ]);
35622
35895
  if (!floor.ok)
35623
35896
  return { ok: false, code: "security_denied", detail: floor.reason };
@@ -35671,14 +35944,14 @@ ${safeSeeds.content}`;
35671
35944
  }
35672
35945
  summary = result.text.trim().length > 0 ? result.text.trim() : mechanicalSummary(summaryDiff, course);
35673
35946
  }
35674
- const evidenceDir = path87.join(input.cwd, ".metaproject", "workspaces", input.workspaceId, "machine-evidence");
35947
+ const evidenceDir = path88.join(input.cwd, ".metaproject", "workspaces", input.workspaceId, "machine-evidence");
35675
35948
  await mkdir21(evidenceDir, { recursive: true });
35676
35949
  const diffFile = `${input.kind}.${shortHash}.diff.txt`;
35677
35950
  const flowFile = `${input.kind}.${shortHash}.flow.json`;
35678
35951
  const seedsFile = `${input.kind}.${shortHash}.seeds.json`;
35679
- await writeFileAtomic(path87.join(evidenceDir, diffFile), safeDiff.content);
35680
- await writeFileAtomic(path87.join(evidenceDir, flowFile), safeFlow.content);
35681
- await writeFileAtomic(path87.join(evidenceDir, seedsFile), safeSeeds.content);
35952
+ await writeFileAtomic(path88.join(evidenceDir, diffFile), safeDiff.content);
35953
+ await writeFileAtomic(path88.join(evidenceDir, flowFile), safeFlow.content);
35954
+ await writeFileAtomic(path88.join(evidenceDir, seedsFile), safeSeeds.content);
35682
35955
  const observedAt = now().toISOString();
35683
35956
  const relBase = `./.metaproject/workspaces/${input.workspaceId}/machine-evidence`;
35684
35957
  const evidence = [
@@ -35688,7 +35961,7 @@ ${safeSeeds.content}`;
35688
35961
  ];
35689
35962
  if (floor.notice !== undefined) {
35690
35963
  const noticeFile = `${input.kind}.${shortHash}.redaction.md`;
35691
- await writeFileAtomic(path87.join(evidenceDir, noticeFile), floor.notice);
35964
+ await writeFileAtomic(path88.join(evidenceDir, noticeFile), floor.notice);
35692
35965
  evidence.push({ kind: REDACTION_NOTICE_KIND, uri: `${relBase}/${noticeFile}`, revision: sha2563(floor.notice), observedAt });
35693
35966
  }
35694
35967
  return {
@@ -35707,18 +35980,18 @@ async function writeFlooredArchiveArtifact(params) {
35707
35980
  {
35708
35981
  name: params.filename,
35709
35982
  content: params.content,
35710
- path: path87.posix.join("slate-archive", params.filename),
35983
+ path: path88.posix.join("slate-archive", params.filename),
35711
35984
  source: "generated"
35712
35985
  }
35713
35986
  ]);
35714
35987
  if (!floor.ok)
35715
35988
  return { ok: false, code: "security_denied", detail: floor.reason };
35716
35989
  const body = floor.bodies[0];
35717
- const archiveDir = path87.join(params.dir, "slate-archive");
35990
+ const archiveDir = path88.join(params.dir, "slate-archive");
35718
35991
  await mkdir21(archiveDir, { recursive: true });
35719
- await writeFileAtomic(path87.join(archiveDir, params.filename), body.content);
35992
+ await writeFileAtomic(path88.join(archiveDir, params.filename), body.content);
35720
35993
  if (floor.notice !== undefined) {
35721
- await writeFileAtomic(path87.join(archiveDir, `${params.filename}${ARCHIVE_REDACTION_NOTICE_SUFFIX}`), floor.notice);
35994
+ await writeFileAtomic(path88.join(archiveDir, `${params.filename}${ARCHIVE_REDACTION_NOTICE_SUFFIX}`), floor.notice);
35722
35995
  }
35723
35996
  return { ok: true, altered: body.altered };
35724
35997
  }
@@ -35754,9 +36027,9 @@ async function writeWrapUpOutcomeArtifact(cwd, dir, trigger, now, groups) {
35754
36027
  return;
35755
36028
  const refusalIso = now().toISOString();
35756
36029
  const refusalFilename = `${refusalIso.replace(/[:.]/g, "-")}-wrap-up-outcome.json`;
35757
- const archiveDir = path87.join(dir, "slate-archive");
36030
+ const archiveDir = path88.join(dir, "slate-archive");
35758
36031
  await mkdir21(archiveDir, { recursive: true });
35759
- await writeFileAtomic(path87.join(archiveDir, refusalFilename), `${JSON.stringify({
36032
+ await writeFileAtomic(path88.join(archiveDir, refusalFilename), `${JSON.stringify({
35760
36033
  recordType: "wrap-up-outcome",
35761
36034
  trigger,
35762
36035
  generatedAt: refusalIso,
@@ -36091,7 +36364,7 @@ init_fs();
36091
36364
  init_repomap();
36092
36365
  init_redact();
36093
36366
  init_slate();
36094
- import path88 from "path";
36367
+ import path89 from "path";
36095
36368
  var DEFAULT_TERMINAL_STATE_MAX_TOKENS = 2000;
36096
36369
  function boundedRedactedAnchorsSnapshot(anchors, maxTokens) {
36097
36370
  const fence = anchors.fence?.map((entry) => redactSensitiveText(entry));
@@ -36126,7 +36399,7 @@ function renderTerminalStateBlock(state, opts) {
36126
36399
  `);
36127
36400
  }
36128
36401
  async function writeTerminalState(dir, state) {
36129
- await writeFileAtomic(path88.join(dir, "terminal-state.json"), `${JSON.stringify(state, null, 2)}
36402
+ await writeFileAtomic(path89.join(dir, "terminal-state.json"), `${JSON.stringify(state, null, 2)}
36130
36403
  `);
36131
36404
  }
36132
36405
 
@@ -38625,13 +38898,24 @@ async function executeCall(...args) {
38625
38898
  function executeCallTraced(...args) {
38626
38899
  const call = args[0];
38627
38900
  if (call.name !== "spawn_subagent")
38628
- return executeCallUnbounded(...args);
38901
+ return executeCallRegistered(call.id, call.name, () => executeCallUnbounded(...args));
38629
38902
  return runWithCallWatchdog(call.name, (signal, stage) => {
38630
38903
  const next = [...args];
38631
38904
  next[9] = signal;
38632
38905
  next[18] = stage;
38633
38906
  return executeCallUnbounded(...next);
38634
- }, { signal: args[9] });
38907
+ }, { signal: args[9], callId: call.id });
38908
+ }
38909
+ async function executeCallRegistered(id, name, run) {
38910
+ const key = callDiagnostics.begin(id, name, { watched: false });
38911
+ let kind = "error";
38912
+ try {
38913
+ const result = await run();
38914
+ kind = result.isError === true ? "error" : "ok";
38915
+ return result;
38916
+ } finally {
38917
+ callDiagnostics.end(key, kind);
38918
+ }
38635
38919
  }
38636
38920
  function personRefused(approver, signal) {
38637
38921
  const { attended, current } = approver;