@aspectlylabs/mikka 0.0.722 → 0.0.741

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.
package/main.js CHANGED
@@ -2655,14 +2655,14 @@ function captureRunFailure(error, context = {}) {
2655
2655
  import { randomBytes as randomBytes6, randomUUID as randomUUID10 } from "node:crypto";
2656
2656
  import {
2657
2657
  chmodSync as chmodSync3,
2658
- existsSync as existsSync9,
2658
+ existsSync as existsSync10,
2659
2659
  mkdirSync as mkdirSync19,
2660
2660
  readFileSync as readFileSync15,
2661
2661
  rmSync as rmSync21,
2662
2662
  realpathSync as realpathSync15
2663
2663
  } from "node:fs";
2664
2664
  import { arch as arch2, hostname, platform as platform2 } from "node:os";
2665
- import { join as join35 } from "node:path";
2665
+ import { join as join36 } from "node:path";
2666
2666
  import { fileURLToPath as fileURLToPath2 } from "node:url";
2667
2667
 
2668
2668
  // ../protocol/src/accounts.ts
@@ -6072,7 +6072,7 @@ import { join } from "node:path";
6072
6072
  // package.json
6073
6073
  var package_default = {
6074
6074
  name: "@mikka/daemon",
6075
- version: "0.0.722",
6075
+ version: "0.0.741",
6076
6076
  description: "Local Mikka daemon: runs agents through the user's own CLIs",
6077
6077
  type: "module",
6078
6078
  private: true,
@@ -6140,7 +6140,7 @@ var package_default = {
6140
6140
  engines: {
6141
6141
  node: ">=22"
6142
6142
  },
6143
- gitHead: "914312e42a3dfe77c2e47344b22976ef0a840d64"
6143
+ gitHead: "0b7e13795e13a5539bc161e1a78750bd47bb09b4"
6144
6144
  };
6145
6145
 
6146
6146
  // src/paths.ts
@@ -10804,7 +10804,7 @@ function claudeSettings(workspace) {
10804
10804
  attribution: { pr: "" }
10805
10805
  };
10806
10806
  }
10807
- function claudeChunks(message) {
10807
+ function claudeChunks(message, turnModel) {
10808
10808
  const chunks = [];
10809
10809
  if (message.type === "assistant") {
10810
10810
  message.message.content.forEach((block, index) => {
@@ -10849,11 +10849,15 @@ function claudeChunks(message) {
10849
10849
  );
10850
10850
  }
10851
10851
  } else if (message.type === "result") {
10852
+ const usedModels = Object.keys(message.modelUsage ?? {});
10852
10853
  chunks.push({
10853
10854
  type: "data-usage",
10854
10855
  data: {
10855
10856
  inputTokens: message.usage.input_tokens ?? 0,
10856
10857
  outputTokens: message.usage.output_tokens ?? 0,
10858
+ model: turnModel ?? (usedModels.length === 1 ? usedModels[0] : void 0),
10859
+ cacheReadTokens: message.usage.cache_read_input_tokens ?? null,
10860
+ cacheWriteTokens: message.usage.cache_creation_input_tokens ?? null,
10857
10861
  costUsd: message.total_cost_usd ?? null,
10858
10862
  source: "claude agent sdk result"
10859
10863
  }
@@ -11219,6 +11223,7 @@ var ClaudeAdapter = class {
11219
11223
  let written = 0;
11220
11224
  let results = 0;
11221
11225
  let runtimeModel = null;
11226
+ let turnModel;
11222
11227
  let ending = false;
11223
11228
  let failureDetails;
11224
11229
  let lastError;
@@ -11482,8 +11487,10 @@ var ClaudeAdapter = class {
11482
11487
  runRuntimeTimings.agentAccepted(options.runId, "claude_user_ack");
11483
11488
  if (message.type === "system" && message.subtype === "init" && typeof message.model === "string")
11484
11489
  runtimeModel = message.model || null;
11485
- if (message.type === "assistant" && message.parent_tool_use_id == null && typeof message.message.model === "string")
11490
+ if (message.type === "assistant" && message.parent_tool_use_id == null && typeof message.message.model === "string") {
11486
11491
  runtimeModel = message.message.model || null;
11492
+ if (!message.error && runtimeModel) turnModel = runtimeModel;
11493
+ }
11487
11494
  if (runtimeModel && (message.type === "system" && message.subtype === "init" || message.type === "assistant" && message.parent_tool_use_id == null))
11488
11495
  options.onRuntimeModel?.(sessionId, runtimeModel);
11489
11496
  if (provesSession(message)) {
@@ -11497,8 +11504,9 @@ var ClaudeAdapter = class {
11497
11504
  quota = mergeQuota(quota, claudeQuotaSignal(message));
11498
11505
  if (message.type === "tool_progress" && message.session_id === sessionId) queue.progress();
11499
11506
  if (!(message.type === "assistant" && message.error))
11500
- for (const chunk of claudeChunks(message)) queue.chunk(chunk);
11507
+ for (const chunk of claudeChunks(message, turnModel)) queue.chunk(chunk);
11501
11508
  if (message.type !== "result") continue;
11509
+ turnModel = void 0;
11502
11510
  results++;
11503
11511
  failureDetails = message.is_error ? capture(message) : void 0;
11504
11512
  providerFailure = claudeProviderFailure(message, assistantError);
@@ -12212,7 +12220,12 @@ function jsonlConnection(input, output) {
12212
12220
  import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync2, lstatSync as lstatSync9, mkdirSync as mkdirSync8, openSync as openSync3, readSync as readSync2 } from "node:fs";
12213
12221
  import { isAbsolute as isAbsolute4, join as join12, relative as relative3, sep as sep2 } from "node:path";
12214
12222
  import { isDeepStrictEqual } from "node:util";
12215
- var unavailable2 = () => new Error("Run mailbox requires a verified original Codex thread");
12223
+ var UNAVAILABLE = "Run mailbox requires a verified original Codex thread";
12224
+ var unavailable2 = (reason, cause) => Object.assign(
12225
+ new Error(`${UNAVAILABLE} (${reason})`, { cause }),
12226
+ { name: "codex_mailbox_unavailable", detail: reason }
12227
+ );
12228
+ var isUnavailable = (error) => error instanceof Error && error.name === "codex_mailbox_unavailable";
12216
12229
  function codexMailboxResumeVersion(userAgent) {
12217
12230
  const version = typeof userAgent === "string" ? /^[A-Za-z0-9._-]+\/(0\.163\.0|0\.166\.0|0\.167\.0)(?:\s|$)/.exec(userAgent)?.[1] : void 0;
12218
12231
  return version === "0.163.0" || version === "0.166.0" || version === "0.167.0" ? version : null;
@@ -12221,24 +12234,33 @@ function codexMailboxCatalogue(mailbox) {
12221
12234
  return JSON.parse(JSON.stringify(mailbox.tools.map((tool) => ({ type: "function", ...tool }))));
12222
12235
  }
12223
12236
  function historyParts(value) {
12224
- if (typeof value !== "string" || value.length > 1024 || /[\\\0]/.test(value)) throw unavailable2();
12237
+ if (typeof value !== "string" || value.length > 1024 || /[\\\0]/.test(value)) throw unavailable2("history_path");
12225
12238
  const parts = value.split("/");
12226
- if (!["sessions", "archived_sessions"].includes(parts[0]) || parts.length < 2 || parts.some((part) => !part || part === "." || part === "..") || !value.endsWith(".jsonl")) throw unavailable2();
12239
+ if (!["sessions", "archived_sessions"].includes(parts[0]) || parts.length < 2 || parts.some((part) => !part || part === "." || part === "..") || !value.endsWith(".jsonl")) throw unavailable2("history_path");
12227
12240
  return parts;
12228
12241
  }
12229
12242
  function receiptFile(stateDir, runId) {
12230
12243
  return join12(stateDir, "codex-mailbox", assertSafeId("run id", runId) + ".json");
12231
12244
  }
12232
- function readJson2(file, limit, firstLine = false) {
12233
- const fd = openSync3(file, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
12245
+ function readJson2(file, limit, firstLine = false, reason = "history_file") {
12246
+ let fd;
12247
+ try {
12248
+ fd = openSync3(file, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
12249
+ } catch {
12250
+ throw unavailable2(reason);
12251
+ }
12234
12252
  try {
12235
12253
  const stat3 = fstatSync2(fd);
12236
- if (!stat3.isFile() || stat3.nlink !== 1 || !firstLine && stat3.size > limit) throw unavailable2();
12254
+ if (!stat3.isFile() || stat3.nlink !== 1 || !firstLine && stat3.size > limit) throw unavailable2(reason);
12237
12255
  const buffer = Buffer.alloc(Math.min(stat3.size, limit + 1));
12238
12256
  const length = readSync2(fd, buffer, 0, buffer.length, 0);
12239
12257
  const end = firstLine ? buffer.subarray(0, length).indexOf(10) : length;
12240
- if (end < 0 || end > limit) throw unavailable2();
12241
- return JSON.parse(buffer.subarray(0, end).toString("utf8"));
12258
+ if (end < 0 || end > limit) throw unavailable2(reason);
12259
+ try {
12260
+ return JSON.parse(buffer.subarray(0, end).toString("utf8"));
12261
+ } catch {
12262
+ throw unavailable2(reason);
12263
+ }
12242
12264
  } finally {
12243
12265
  closeSync3(fd);
12244
12266
  }
@@ -12249,36 +12271,36 @@ function verifyHistory(home, path3, threadId, catalogue) {
12249
12271
  for (const part of ["", ...parts.slice(0, -1)]) {
12250
12272
  if (part) parent = join12(parent, part);
12251
12273
  const stat3 = lstatSync9(parent);
12252
- if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2();
12274
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2("history_dir");
12253
12275
  }
12254
- const header = readJson2(join12(home, ...parts), 1024 * 1024, true);
12255
- if (header?.type !== "session_meta" || header.payload?.id !== threadId || !isDeepStrictEqual(header.payload.dynamic_tools, catalogue)) throw unavailable2();
12276
+ const header = readJson2(join12(home, ...parts), 1024 * 1024, true, "history_meta");
12277
+ if (header?.type !== "session_meta" || header.payload?.id !== threadId || !isDeepStrictEqual(header.payload.dynamic_tools, catalogue)) throw unavailable2("history_meta");
12256
12278
  }
12257
12279
  function verifyCodexMailboxResume(stateDir, sourceRunId, home, threadId, catalogue) {
12258
12280
  try {
12259
12281
  const dir = lstatSync9(join12(stateDir, "codex-mailbox"));
12260
- if (!dir.isDirectory() || dir.isSymbolicLink()) throw unavailable2();
12261
- const receipt = readJson2(receiptFile(stateDir, sourceRunId), 256 * 1024);
12262
- if (receipt?.version !== 1 || receipt.nativeVersion !== "0.163.0" && receipt.nativeVersion !== "0.166.0" && receipt.nativeVersion !== "0.167.0" || receipt.runId !== sourceRunId || receipt.threadId !== threadId || !isDeepStrictEqual(receipt.catalogue, catalogue) || typeof receipt.historyPath !== "string") throw unavailable2();
12282
+ if (!dir.isDirectory() || dir.isSymbolicLink()) throw unavailable2("mailbox_dir");
12283
+ const receipt = readJson2(receiptFile(stateDir, sourceRunId), 256 * 1024, false, "receipt");
12284
+ if (receipt?.version !== 1 || receipt.nativeVersion !== "0.163.0" && receipt.nativeVersion !== "0.166.0" && receipt.nativeVersion !== "0.167.0" || receipt.runId !== sourceRunId || receipt.threadId !== threadId || !isDeepStrictEqual(receipt.catalogue, catalogue) || typeof receipt.historyPath !== "string") throw unavailable2("receipt_mismatch");
12263
12285
  verifyHistory(home, receipt.historyPath, threadId, catalogue);
12264
12286
  return receipt.nativeVersion;
12265
- } catch {
12266
- throw unavailable2();
12287
+ } catch (error) {
12288
+ throw isUnavailable(error) ? error : unavailable2("verify", error);
12267
12289
  }
12268
12290
  }
12269
12291
  function recordCodexMailboxSession(stateDir, runId, home, thread, catalogue, resumed, nativeVersion) {
12270
12292
  try {
12271
- if (!thread.id || typeof thread.path !== "string" || !isAbsolute4(thread.path)) throw unavailable2();
12293
+ if (!thread.id || typeof thread.path !== "string" || !isAbsolute4(thread.path)) throw unavailable2("thread_path");
12272
12294
  const historyPath = relative3(home, thread.path).split(sep2).join("/");
12273
12295
  historyParts(historyPath);
12274
12296
  if (resumed) verifyHistory(home, historyPath, thread.id, catalogue);
12275
12297
  const dir = join12(stateDir, "codex-mailbox");
12276
12298
  mkdirSync8(dir, { recursive: true, mode: 448 });
12277
12299
  const stat3 = lstatSync9(dir);
12278
- if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2();
12300
+ if (!stat3.isDirectory() || stat3.isSymbolicLink()) throw unavailable2("mailbox_dir");
12279
12301
  writeJsonAtomic(receiptFile(stateDir, runId), { version: 1, nativeVersion, runId, threadId: thread.id, historyPath, catalogue });
12280
- } catch {
12281
- if (resumed) throw unavailable2();
12302
+ } catch (error) {
12303
+ if (resumed) throw isUnavailable(error) ? error : unavailable2("record", error);
12282
12304
  }
12283
12305
  }
12284
12306
 
@@ -12756,7 +12778,15 @@ var CodexAdapter = class {
12756
12778
  let quota;
12757
12779
  let rateLimits;
12758
12780
  let usage = { inputTokens: 0, outputTokens: 0 };
12759
- const generations = new CodexGenerationMetrics((metrics) => nativeGenerations ? nativeGenerations.collector.observeFallback(metrics, sessionId) : daemonTracer.generation({ ...metrics, nativeUnavailableReason }, traceContext));
12781
+ let turnUsage;
12782
+ const generations = new CodexGenerationMetrics((metrics) => {
12783
+ turnUsage = {
12784
+ inputTokens: (turnUsage?.inputTokens ?? 0) + (metrics.inputTokens ?? 0),
12785
+ outputTokens: (turnUsage?.outputTokens ?? 0) + (metrics.outputTokens ?? 0)
12786
+ };
12787
+ if (nativeGenerations) nativeGenerations.collector.observeFallback(metrics, sessionId);
12788
+ else daemonTracer.generation({ ...metrics, nativeUnavailableReason }, traceContext);
12789
+ });
12760
12790
  const pendingMcp = /* @__PURE__ */ new Map();
12761
12791
  const handInTools = /* @__PURE__ */ new Set([
12762
12792
  "submit",
@@ -12939,11 +12969,14 @@ var CodexAdapter = class {
12939
12969
  type: "data-usage",
12940
12970
  data: {
12941
12971
  ...usage,
12972
+ turnUsage,
12973
+ model: runtimeModel ?? void 0,
12942
12974
  // Priced later with the LiteLLM table (ADR 0003).
12943
12975
  costUsd: null,
12944
12976
  source: "codex app-server thread/tokenUsage"
12945
12977
  }
12946
12978
  });
12979
+ turnUsage = void 0;
12947
12980
  if (ending) return;
12948
12981
  if (cancelling) return finish({ outcome: "cancelled" });
12949
12982
  const handoff = ctx.readHandoff(log);
@@ -12991,6 +13024,7 @@ var CodexAdapter = class {
12991
13024
  throw new Error(SUBSCRIPTION_AUTH_ERROR, { cause: error });
12992
13025
  }
12993
13026
  }
13027
+ turnUsage = void 0;
12994
13028
  generations.startTurn();
12995
13029
  const result = rpc.sendRequest("turn/start", {
12996
13030
  threadId: sessionId,
@@ -14803,8 +14837,8 @@ function removeRunCredentials(stateDir, runId) {
14803
14837
 
14804
14838
  // src/subscription-local-runner.ts
14805
14839
  var unavailable3 = (detail, cause) => new CodedError("subscription_local_runtime_unavailable", { detail, cause });
14806
- var isUnavailable = (error) => error instanceof CodedError && error.code === "subscription_local_runtime_unavailable";
14807
- var startFailed = (error) => isUnavailable(error) ? error : error instanceof SubscriptionCredentialError ? unavailable3(error.detail, error.cause ?? error) : unavailable3(findCodedError(error, "subscription_local_runtime_unavailable")?.detail ?? "adapter_start_failed", error);
14840
+ var isUnavailable2 = (error) => error instanceof CodedError && error.code === "subscription_local_runtime_unavailable";
14841
+ var startFailed = (error) => isUnavailable2(error) ? error : error instanceof SubscriptionCredentialError ? unavailable3(error.detail, error.cause ?? error) : unavailable3(findCodedError(error, "subscription_local_runtime_unavailable")?.detail ?? "adapter_start_failed", error);
14808
14842
  function createLocalSubscriptionRunner(host) {
14809
14843
  return {
14810
14844
  async start(assignment, options) {
@@ -15041,7 +15075,7 @@ async function acquireCloudWorkspaceControl(input, root = CLOUD_WORKSPACE_CONTRO
15041
15075
  }
15042
15076
 
15043
15077
  // src/lock.ts
15044
- import { mkdirSync as mkdirSync15, readFileSync as readFileSync12, rmSync as rmSync16 } from "node:fs";
15078
+ import { existsSync as existsSync7, mkdirSync as mkdirSync15, readFileSync as readFileSync12, rmSync as rmSync16 } from "node:fs";
15045
15079
  import { createConnection } from "node:net";
15046
15080
  import { join as join26 } from "node:path";
15047
15081
  import { setTimeout as sleep2 } from "node:timers/promises";
@@ -15108,16 +15142,18 @@ async function acquireLock(dataDir, lockfilePath, onCompromised = () => void 0,
15108
15142
  };
15109
15143
  const deadline = Date.now() + (options.takeoverMs ?? LOCK_TAKEOVER_MS);
15110
15144
  for (; ; ) {
15111
- try {
15112
- return await lock();
15113
- } catch (error) {
15114
- if (error.code !== "ELOCKED") throw error;
15115
- }
15116
15145
  if (options.socketPath && await socketAnswers(options.socketPath)) {
15117
15146
  throw new DaemonAlreadyRunningError(dataDir);
15118
15147
  }
15119
15148
  const pid = holderPid(dataDir);
15120
15149
  const crashed = pid !== null && pid !== process.pid && !processAlive(pid);
15150
+ if (pid === null || crashed || !existsSync7(lockfilePath)) {
15151
+ try {
15152
+ return await lock();
15153
+ } catch (error) {
15154
+ if (error.code !== "ELOCKED") throw error;
15155
+ }
15156
+ }
15121
15157
  if (crashed || pid === null && Date.now() >= deadline) {
15122
15158
  rmSync16(lockfilePath, { recursive: true, force: true });
15123
15159
  try {
@@ -15711,6 +15747,405 @@ var RunJournal = class {
15711
15747
  }
15712
15748
  };
15713
15749
 
15750
+ // src/runs/publication.ts
15751
+ import { createHash as createHash10 } from "node:crypto";
15752
+ import { lstatSync as lstatSync11, readFileSync as readFileSync14, readdirSync as readdirSync8 } from "node:fs";
15753
+ import { join as join28 } from "node:path";
15754
+ import { execa as execa10 } from "execa";
15755
+
15756
+ // src/runs/check.ts
15757
+ import { execa as execa9 } from "execa";
15758
+ async function fixedCheckSnapshot(repoPath, worktree, sha5, signal) {
15759
+ signal?.throwIfAborted();
15760
+ if (!/^[a-f0-9]{40}$/.test(sha5))
15761
+ throw new Error("Check requires an exact candidate SHA");
15762
+ const gitDir = await worktreeGitDir(repoPath, worktree, signal);
15763
+ const git3 = async (...args) => (await execa9(
15764
+ "git",
15765
+ [
15766
+ "-c",
15767
+ "core.hooksPath=/dev/null",
15768
+ "-c",
15769
+ "core.fsmonitor=false",
15770
+ ...args
15771
+ ],
15772
+ {
15773
+ cwd: worktree,
15774
+ env: { GIT_DIR: gitDir, GIT_WORK_TREE: worktree },
15775
+ stdin: "ignore",
15776
+ cancelSignal: signal,
15777
+ killDescendants: true
15778
+ }
15779
+ )).stdout.trim();
15780
+ if (await git3("rev-parse", "HEAD") !== sha5)
15781
+ throw new Error("Check worktree HEAD differs from the fixed candidate");
15782
+ if (await git3("status", "--porcelain"))
15783
+ throw new Error(
15784
+ "Check worktree contains changes outside the fixed candidate"
15785
+ );
15786
+ return { sha: sha5, tree: await git3("rev-parse", `${sha5}^{tree}`) };
15787
+ }
15788
+
15789
+ // src/runs/publication.ts
15790
+ var VERIFY_TIMEOUT_MS = 30 * 6e4;
15791
+ var MAX_REPORTED_FILES = 5e3;
15792
+ var MAX_REPORTED_CRITERIA = 200;
15793
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
15794
+ async function verifyAndPublish(context, event) {
15795
+ const { assignment, repo, worktree, signal } = context;
15796
+ const initialStopReason = context.getStopReason();
15797
+ const error = event.error ?? (initialStopReason === "turn_ended" ? "Session ended without a submission" : initialStopReason === "timeout" ? "No progress before the watchdog limit" : initialStopReason === "device_lost" ? "Run lease expired; the server could not be reached" : void 0);
15798
+ let outcome;
15799
+ try {
15800
+ if (assignment.benchmark && !context.cancelRequested) {
15801
+ const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.benchmark.sourceCommit, signal);
15802
+ if (createHash10("sha256").update(fixed.sha).digest("hex") !== assignment.benchmark.fixtureDigest)
15803
+ throw new Error("Benchmark fixture changed during model execution");
15804
+ }
15805
+ outcome = await collectReport(context, initialStopReason, error, event.report);
15806
+ } catch (error2) {
15807
+ if (!signal.aborted) throw error2;
15808
+ outcome = { report: { ...baseReport(), ...pickAgentReport(event.report) } };
15809
+ }
15810
+ if (context.isStopping()) return;
15811
+ const stopReason = context.getStopReason();
15812
+ const { verifyError, tree } = outcome;
15813
+ let report2 = stopReason === "quota_exhausted" ? { ...outcome.report, resetsAt: event.quota?.resetsAt ?? null } : outcome.report;
15814
+ if (stopReason === "provider_failure") {
15815
+ report2 = {
15816
+ ...report2,
15817
+ providerFailure: providerFailureSchema.parse(event.providerFailure),
15818
+ ...event.quota ? { resetsAt: event.quota.resetsAt } : {}
15819
+ };
15820
+ }
15821
+ const policy = runPolicy(assignment.policy);
15822
+ const { publisher } = context.deps;
15823
+ if (stopReason === "submitted" && report2.verify.status !== "failed" && tree && publisher && // The draft-PR exception requires an explicit repository push
15824
+ // approval. It must not even create a local commit without it.
15825
+ (report2.verify.status === "passed" || pushDecision(policy).push) && // A read-only check (ADR 0046) never commits or pushes: it reports
15826
+ // on the commit the implementation run already pushed.
15827
+ policy.readOnly !== true) {
15828
+ const publish = await publishRun2(context, publisher, report2, tree);
15829
+ report2 = { ...report2, publish };
15830
+ }
15831
+ return { report: report2, error: error ?? verifyError };
15832
+ }
15833
+ function finishRun(context, stopReason, error, report2 = baseReport(error), failureDetails) {
15834
+ const { runId, journal, active } = context;
15835
+ if (active?.cancelRequested || active?.forcedStop) {
15836
+ stopReason = active.forcedStop ?? "cancelled";
15837
+ error = void 0;
15838
+ }
15839
+ active?.span?.set("mikka.outcome", stopReason);
15840
+ if (stopReason !== "provider_failure" && report2.providerFailure) {
15841
+ const { providerFailure: _failure, ...rest } = report2;
15842
+ report2 = rest;
15843
+ }
15844
+ if (stopReason !== "provider_failure" && stopReason !== "quota_exhausted" && report2.providerCheckpoint) {
15845
+ const { providerCheckpoint: _checkpoint, ...rest } = report2;
15846
+ report2 = rest;
15847
+ }
15848
+ const entry = journal.get(runId);
15849
+ const planning = entry?.assignment.kind === "plan";
15850
+ if (entry && stopReason === "blocked" && report2.repositorySelection)
15851
+ entry.assignment.preserveQuestionWorktree = true;
15852
+ const readOnlyTask = entry && (isReadOnlyTask(entry.assignment) || entry.assignment.factoryCheck?.reportOnly === true || entry.assignment.factoryExecuteKind === "deliverable");
15853
+ const { sourceCommit: _source, deliverableCommit: _delivery, skillMount: _mount, skillPrompt: _prompt, execution: _execution, runtime: _runtime, safePoint: _safePoint, ...content } = report2;
15854
+ report2 = {
15855
+ ...content,
15856
+ ...active?.safePoint ? { safePoint: active.safePoint } : {},
15857
+ ...entry?.baseCommit && /^[a-f0-9]{40}$/.test(entry.baseCommit) ? { sourceCommit: entry.baseCommit } : {},
15858
+ ...entry?.assignment.factoryExecuteKind === "deliverable" && entry.deliverableCommit ? { deliverableCommit: entry.deliverableCommit } : {},
15859
+ // What the prompt actually carried of the run's skills; a deferred body
15860
+ // is a fact the person needs to see, not something to leave unsaid.
15861
+ ...entry && skillPromptOf(entry.assignment) ? { skillPrompt: skillPromptOf(entry.assignment) } : {},
15862
+ ...entry?.skillMount && entry.skillMount.sessionId === entry.sessionId && entry.skillMount.receiptId === entry.assignment.skillReceipt?.id && entry.skillMount.versionId === entry.assignment.skillReceipt?.artifact.versionId && entry.skillMount.sha256 === entry.assignment.skillReceipt?.artifact.sha256 ? {
15863
+ skillMount: entry.skillMount,
15864
+ ...entry.runtime ? { runtime: {
15865
+ ...entry.runtime,
15866
+ observedModel: active?.session?.runtimeModel ?? entry.runtime.observedModel
15867
+ } } : {},
15868
+ ...entry.execution && entry.assignment.benchmark ? { execution: {
15869
+ ...entry.execution,
15870
+ observedModel: active?.session?.runtimeModel ?? entry.execution.observedModel
15871
+ } } : {}
15872
+ } : {}
15873
+ };
15874
+ context.closeOutput(report2, planning);
15875
+ if (stopReason === "submitted") context.setState("finishing");
15876
+ let state2 = runStateForStop(stopReason);
15877
+ if (stopReason === "submitted" && report2.verify.status !== "passed") {
15878
+ const failed = report2.verify.status === "failed";
15879
+ if (!planning && !readOnlyTask) state2 = failed ? "failed" : report2.publish?.pushed === true ? "succeeded" : "stopped";
15880
+ if (!failed && !planning && !readOnlyTask)
15881
+ error ??= "Submitted, but no verify command ran; the work is unverified";
15882
+ }
15883
+ if ((stopReason === "asked_human" || stopReason === "blocked") && report2.question) {
15884
+ journal.update(runId, {
15885
+ waitingQuestionId: report2.question.questionId
15886
+ });
15887
+ }
15888
+ if (state2 === "failed") active?.span?.fail({ name: "RunFailure" }, stopReason);
15889
+ else active?.span?.set("mikka.outcome", stopReason);
15890
+ context.setState(state2, {
15891
+ stopReason,
15892
+ ...error ? { error } : {}
15893
+ });
15894
+ const terminalFailure = state2 === "failed" && !active?.cancelRequested && !active?.forcedStop ? captureRunFailure(failureDetails ?? new Error(error ?? report2.summary), {
15895
+ runId,
15896
+ appVersion: DAEMON_VERSION,
15897
+ sensitiveText: [entry?.assignment.prompt ?? ""]
15898
+ }) : void 0;
15899
+ context.complete({ stopReason, report: report2, ...terminalFailure ? { failureDetails: terminalFailure } : {} });
15900
+ }
15901
+ async function collectReport(context, stopReason, error, agent) {
15902
+ const { deps, runId, worktree, repo, assignment, signal } = context;
15903
+ const profileSkills = profileSkillReport(runId, assignment, deps.adapterStateDir);
15904
+ let report2 = {
15905
+ ...baseReport(error),
15906
+ ...pickAgentReport(agent),
15907
+ ...profileSkills ? { profileSkills } : {}
15908
+ };
15909
+ const filesChanged = (await deps.worktrees.changedFiles(worktree, deps.journal.get(runId)?.baseCommit).catch(() => [])).slice(0, MAX_REPORTED_FILES);
15910
+ const inferred = assignment.factoryCheck?.stage === "verify" && assignment.factoryCheck.inferCommand && !assignment.factoryCheck.reportOnly ? report2.verificationCommand : void 0;
15911
+ const command = assignment.verifyCommand ?? inferred?.command;
15912
+ if (stopReason === "submitted") context.assertLive();
15913
+ if (stopReason === "submitted" && assignment.factoryExecuteKind === "deliverable") {
15914
+ const deliverableCommit = await retainDeliverable(repo.path, worktree, runId, signal);
15915
+ context.assertLive();
15916
+ deps.journal.update(runId, { deliverableCommit });
15917
+ }
15918
+ if (stopReason !== "submitted" && fixedCandidateCheck(assignment)) {
15919
+ const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).catch(() => null);
15920
+ if (fixed) report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
15921
+ }
15922
+ if (stopReason !== "submitted" || assignment.kind === "plan" || isReadOnlyTask(assignment) || assignment.factoryExecuteKind === "deliverable")
15923
+ return {
15924
+ report: { ...report2, filesChanged, verify: { status: "not_run" } }
15925
+ };
15926
+ if (!command) {
15927
+ if (fixedCandidateCheck(assignment)) {
15928
+ const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal);
15929
+ report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
15930
+ }
15931
+ context.assertLive();
15932
+ const tree = await deps.publisher?.snapshot({ worktree, repo, signal });
15933
+ context.assertLive();
15934
+ return { report: { ...report2, filesChanged, verify: { status: "not_run" } }, tree };
15935
+ }
15936
+ let execution = {};
15937
+ const failed = (output2, verifyError) => ({
15938
+ report: {
15939
+ ...report2,
15940
+ filesChanged,
15941
+ verify: { status: "failed", command, output: output2, ...execution }
15942
+ },
15943
+ verifyError
15944
+ });
15945
+ const publisher = deps.publisher;
15946
+ let before;
15947
+ try {
15948
+ if (fixedCandidateCheck(assignment)) {
15949
+ if (runPolicy(assignment.policy).readOnly !== true)
15950
+ throw new Error("Check assignment is missing its read-only policy");
15951
+ const fixed = await fixedCheckSnapshot(
15952
+ repo.path,
15953
+ worktree,
15954
+ assignment.baseBranch,
15955
+ signal
15956
+ );
15957
+ report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
15958
+ before = fixed.tree;
15959
+ } else {
15960
+ before = await publisher?.snapshot({ worktree, repo, signal });
15961
+ }
15962
+ } catch (snapshotError) {
15963
+ signal.throwIfAborted();
15964
+ return failed("", `Could not read the worktree: ${String(snapshotError)}`);
15965
+ }
15966
+ context.assertLive();
15967
+ const result = await (deps.verify ?? unsandboxedVerify)({
15968
+ runId,
15969
+ worktree,
15970
+ repo,
15971
+ command,
15972
+ timeoutMs: VERIFY_TIMEOUT_MS,
15973
+ signal,
15974
+ readOnly: runPolicy(assignment.policy).readOnly === true,
15975
+ githubEnvironment: context.githubEnvironment()
15976
+ });
15977
+ context.assertLive();
15978
+ execution = {
15979
+ exitCode: result.exitCode,
15980
+ signal: result.signal,
15981
+ timedOut: result.timedOut
15982
+ };
15983
+ const output = result.output.slice(-4e3);
15984
+ if (result.exitCode !== 0 || result.timedOut)
15985
+ return failed(output, verifyFailure(command, result));
15986
+ const after = fixedCandidateCheck(assignment) ? await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).then((fixed) => fixed.tree).catch(() => null) : publisher ? await publisher.snapshot({ worktree, repo, signal }).catch(() => null) : void 0;
15987
+ context.assertLive();
15988
+ if (after !== before)
15989
+ return failed(
15990
+ output,
15991
+ `Submitted, but the verify command changed the worktree (\`${command}\`); the work is unverified`
15992
+ );
15993
+ return {
15994
+ report: {
15995
+ ...report2,
15996
+ filesChanged,
15997
+ verify: { status: "passed", command, output, ...inferred ? { inferredFrom: inferred.basis } : {}, ...execution }
15998
+ },
15999
+ tree: before
16000
+ };
16001
+ }
16002
+ async function publishRun2(context, publisher, report2, tree) {
16003
+ const { runId, worktree, repo, assignment, signal } = context;
16004
+ let data;
16005
+ try {
16006
+ context.assertLive();
16007
+ data = await publisher.publish({
16008
+ runId,
16009
+ worktree,
16010
+ repo,
16011
+ assignment,
16012
+ report: report2,
16013
+ tree,
16014
+ githubEnvironment: context.githubEnvironment(),
16015
+ signal
16016
+ });
16017
+ } catch (error) {
16018
+ const message = error instanceof Error ? error.message : String(error);
16019
+ if (!signal.aborted) context.logPublishError(error);
16020
+ data = {
16021
+ branch: "",
16022
+ commit: null,
16023
+ pushed: false,
16024
+ remote: null,
16025
+ note: signal.aborted ? "Run stopped before publication completed" : `Commit failed: ${message}`.slice(0, 2e3)
16026
+ };
16027
+ }
16028
+ context.emitPublish(data);
16029
+ return data;
16030
+ }
16031
+ function profileSkillReport(runId, assignment, adapterStateDir) {
16032
+ const configured = (assignment.profileSkills ?? []).map((skill) => ({ id: skill.id, name: skill.name, source: skill.source, digest: skill.digest }));
16033
+ for (const slug of assignment.repositorySkills ?? []) {
16034
+ if (!configured.some((ref) => ref.id === `repository:${slug}`)) configured.push({ id: `repository:${slug}`, name: slug, source: "repository", digest: null });
16035
+ }
16036
+ if (configured.length === 0) return void 0;
16037
+ const loaded = [];
16038
+ if (adapterStateDir) {
16039
+ const dir = join28(runPaths(adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
16040
+ try {
16041
+ for (const name of readdirSync8(dir).sort()) {
16042
+ if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
16043
+ const file = join28(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
16044
+ if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
16045
+ const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
16046
+ if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
16047
+ if (!configured.some((ref) => ref.id === receipt.data.id && (ref.digest === null || ref.digest === receipt.data.digest))) continue;
16048
+ loaded.push(receipt.data);
16049
+ }
16050
+ } catch {
16051
+ }
16052
+ }
16053
+ return { configured, loaded };
16054
+ }
16055
+ function pickAgentReport(agent) {
16056
+ if (!agent) return {};
16057
+ const picked = {};
16058
+ if (agent.repositorySelection) picked.repositorySelection = agent.repositorySelection;
16059
+ if (agent.verificationCommand && typeof agent.verificationCommand.command === "string" && agent.verificationCommand.command.trim() && typeof agent.verificationCommand.basis === "string" && agent.verificationCommand.basis.trim())
16060
+ picked.verificationCommand = { command: agent.verificationCommand.command.trim().slice(0, 2e3), basis: agent.verificationCommand.basis.trim().slice(0, 2e3) };
16061
+ const visualEvidence = runVisualEvidence.safeParse(agent.visualEvidence);
16062
+ if (visualEvidence.success) picked.visualEvidence = visualEvidence.data;
16063
+ const verdict = reviewVerdict.safeParse(agent.reviewVerdict);
16064
+ if (verdict.success) picked.reviewVerdict = verdict.data;
16065
+ if (typeof agent.summary === "string")
16066
+ picked.summary = agent.summary.slice(0, 1e4);
16067
+ if (Array.isArray(agent.openQuestions) && agent.openQuestions.every((q) => typeof q === "string"))
16068
+ picked.openQuestions = agent.openQuestions.slice(0, 50).map((q) => q.slice(0, 2e3));
16069
+ if (typeof agent.nextStep === "string")
16070
+ picked.nextStep = agent.nextStep.slice(0, 2e3);
16071
+ else if (agent.nextStep === null) picked.nextStep = null;
16072
+ if (typeof agent.blockedOn === "string")
16073
+ picked.blockedOn = agent.blockedOn.slice(0, 500);
16074
+ const question = runQuestion.safeParse(agent.question);
16075
+ if (question.success) picked.question = question.data;
16076
+ if (agent.plan) picked.plan = agent.plan;
16077
+ if (typeof agent.previewDatabaseBranch === "string" && agent.previewDatabaseBranch.trim())
16078
+ picked.previewDatabaseBranch = agent.previewDatabaseBranch.trim().slice(0, 500);
16079
+ if (Array.isArray(agent.criteria)) {
16080
+ const criteria = [];
16081
+ for (const entry of agent.criteria) {
16082
+ if (criteria.length >= MAX_REPORTED_CRITERIA) break;
16083
+ if (!entry || typeof entry !== "object") continue;
16084
+ const { criterionId, text: text4, passed, status: status3, reason, resolution, evidence, command, exitCode } = entry;
16085
+ if (!(typeof criterionId === "string" && UUID_RE.test(criterionId)) && !(typeof text4 === "string" && text4.trim()))
16086
+ continue;
16087
+ if (typeof passed !== "boolean") continue;
16088
+ const criterion = runCriterion.safeParse({
16089
+ ...typeof criterionId === "string" && UUID_RE.test(criterionId) ? { criterionId } : {},
16090
+ ...typeof text4 === "string" && text4.trim() ? { text: text4.trim().slice(0, 2e3) } : {},
16091
+ passed,
16092
+ ...status3 !== void 0 ? { status: status3 } : {},
16093
+ ...typeof reason === "string" && reason.trim() ? { reason: reason.trim().slice(0, 2e3) } : {},
16094
+ ...typeof resolution === "string" && resolution.trim() ? { resolution: resolution.trim().slice(0, 2e3) } : {},
16095
+ ...typeof command === "string" && command.trim() ? { command: command.trim().slice(0, 2e3), ...exitCode === null || typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? { exitCode } : {} } : {},
16096
+ ...typeof evidence === "string" ? { evidence: evidence.slice(0, 1e4) } : {}
16097
+ });
16098
+ if (criterion.success) criteria.push(criterion.data);
16099
+ }
16100
+ picked.criteria = criteria;
16101
+ }
16102
+ return picked;
16103
+ }
16104
+ async function unsandboxedVerify(run3) {
16105
+ const result = await execa10(run3.command, {
16106
+ shell: true,
16107
+ cwd: run3.worktree,
16108
+ env: buildChildEnv(),
16109
+ extendEnv: false,
16110
+ reject: false,
16111
+ all: true,
16112
+ stdin: "ignore",
16113
+ timeout: run3.timeoutMs,
16114
+ cancelSignal: run3.signal,
16115
+ killDescendants: true
16116
+ });
16117
+ return {
16118
+ exitCode: result.exitCode ?? null,
16119
+ signal: result.signal ?? null,
16120
+ timedOut: result.timedOut,
16121
+ output: String(result.all ?? "")
16122
+ };
16123
+ }
16124
+ function verifyFailure(command, result) {
16125
+ const how = result.timedOut ? "timed out" : result.exitCode !== null ? `exited with code ${result.exitCode}` : result.signal ? `was killed by ${result.signal}` : "did not finish";
16126
+ return `Submitted, but the verify command failed: \`${command}\` ${how}`;
16127
+ }
16128
+ function baseReport(summary = "") {
16129
+ return emptyRunReport(summary.slice(0, 1e4));
16130
+ }
16131
+ function isReadOnlyTask(assignment) {
16132
+ return runPolicy(assignment.policy).readOnly === true && assignment.kind !== "acceptance" && !assignment.benchmark;
16133
+ }
16134
+ function skillPromptOf(assignment) {
16135
+ const skills = assignment.skills;
16136
+ if (!skills?.length) return void 0;
16137
+ const plan = skillPromptPlan(skills);
16138
+ return {
16139
+ budgetChars: plan.budgetChars,
16140
+ usedChars: plan.usedChars,
16141
+ inlined: plan.inlined.map((entry) => entry.name),
16142
+ deferred: plan.degraded.map((entry) => entry.name)
16143
+ };
16144
+ }
16145
+ function fixedCandidateCheck(assignment) {
16146
+ return assignment.kind === "acceptance" && runPolicy(assignment.policy).readOnly === true && typeof assignment.baseBranch === "string" && /^[a-f0-9]{40}$/.test(assignment.baseBranch);
16147
+ }
16148
+
15714
16149
  // src/tool-duration.ts
15715
16150
  function toolDuration(clock = () => performance.now()) {
15716
16151
  const starts = /* @__PURE__ */ new Map();
@@ -15934,9 +16369,9 @@ async function startTaskSecretBridge(options) {
15934
16369
  }
15935
16370
 
15936
16371
  // src/agents/chat-files.ts
15937
- import { createHash as createHash10 } from "node:crypto";
16372
+ import { createHash as createHash11 } from "node:crypto";
15938
16373
  import { lstat as lstat3, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile2 } from "node:fs/promises";
15939
- import { join as join28 } from "node:path";
16374
+ import { join as join29 } from "node:path";
15940
16375
 
15941
16376
  // ../protocol/src/chat-attachments.ts
15942
16377
  import { z as z35 } from "zod";
@@ -15996,19 +16431,19 @@ async function materializeChatFiles(text4, directory, download2) {
15996
16431
  const file = chatFileDownloadSchema.parse(await download2(ref.id));
15997
16432
  if (file.id !== ref.id) throw Error("Attachment identity mismatch");
15998
16433
  const bytes = Buffer.from(file.data, "base64");
15999
- if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash10("sha256").update(bytes).digest("hex") !== file.sha256)
16434
+ if (bytes.length !== file.size || bytes.toString("base64") !== file.data || createHash11("sha256").update(bytes).digest("hex") !== file.sha256)
16000
16435
  throw Error("Attachment content mismatch");
16001
16436
  const ext = /\.([a-z0-9]{1,12})$/i.exec(file.name)?.[1]?.toLowerCase() ?? "bin";
16002
- const path3 = join28(directory, `${file.id}.${ext}`);
16437
+ const path3 = join29(directory, `${file.id}.${ext}`);
16003
16438
  try {
16004
16439
  await writeFile2(path3, bytes, { flag: "wx", mode: 256 });
16005
16440
  } catch (error) {
16006
- if (error.code !== "EEXIST" || (await lstat3(path3)).isSymbolicLink() || createHash10("sha256").update(await readFile4(path3)).digest("hex") !== file.sha256)
16441
+ if (error.code !== "EEXIST" || (await lstat3(path3)).isSymbolicLink() || createHash11("sha256").update(await readFile4(path3)).digest("hex") !== file.sha256)
16007
16442
  throw Error("Attachment file unavailable");
16008
16443
  }
16009
16444
  let textPath;
16010
16445
  if (file.text !== null) {
16011
- textPath = join28(directory, `${file.id}.extracted.txt`);
16446
+ textPath = join29(directory, `${file.id}.extracted.txt`);
16012
16447
  try {
16013
16448
  await writeFile2(textPath, file.text, { flag: "wx", mode: 256 });
16014
16449
  } catch (error) {
@@ -16024,42 +16459,6 @@ Attached files (read the original files; extracted document text is provided whe
16024
16459
  ${JSON.stringify(entries)}`;
16025
16460
  }
16026
16461
 
16027
- // src/runs/check.ts
16028
- import { execa as execa9 } from "execa";
16029
- async function fixedCheckSnapshot(repoPath, worktree, sha5, signal) {
16030
- signal?.throwIfAborted();
16031
- if (!/^[a-f0-9]{40}$/.test(sha5))
16032
- throw new Error("Check requires an exact candidate SHA");
16033
- const gitDir = await worktreeGitDir(repoPath, worktree, signal);
16034
- const git3 = async (...args) => (await execa9(
16035
- "git",
16036
- [
16037
- "-c",
16038
- "core.hooksPath=/dev/null",
16039
- "-c",
16040
- "core.fsmonitor=false",
16041
- ...args
16042
- ],
16043
- {
16044
- cwd: worktree,
16045
- env: { GIT_DIR: gitDir, GIT_WORK_TREE: worktree },
16046
- stdin: "ignore",
16047
- cancelSignal: signal,
16048
- killDescendants: true
16049
- }
16050
- )).stdout.trim();
16051
- if (await git3("rev-parse", "HEAD") !== sha5)
16052
- throw new Error("Check worktree HEAD differs from the fixed candidate");
16053
- if (await git3("status", "--porcelain"))
16054
- throw new Error(
16055
- "Check worktree contains changes outside the fixed candidate"
16056
- );
16057
- return { sha: sha5, tree: await git3("rev-parse", `${sha5}^{tree}`) };
16058
- }
16059
-
16060
- // src/runs/supervisor.ts
16061
- import { lstatSync as lstatSync11, readFileSync as readFileSync14, readdirSync as readdirSync8 } from "node:fs";
16062
-
16063
16462
  // src/secret-mask.ts
16064
16463
  import { gunzipSync, gzipSync } from "node:zlib";
16065
16464
  var MASK_MIN_LENGTH = 8;
@@ -16202,23 +16601,22 @@ function createRunMasker(secrets) {
16202
16601
 
16203
16602
  // src/runs/supervisor.ts
16204
16603
  import { stdSerializers } from "pino";
16205
- import { createHash as createHash12, randomUUID as randomUUID6 } from "node:crypto";
16206
- import { join as join30, resolve as resolve13 } from "node:path";
16604
+ import { createHash as createHash13, randomUUID as randomUUID6 } from "node:crypto";
16605
+ import { join as join31, resolve as resolve13 } from "node:path";
16207
16606
  import { tmpdir as tmpdir5 } from "node:os";
16208
- import { execa as execa12 } from "execa";
16209
16607
 
16210
16608
  // src/agents/checkpoint.ts
16211
16609
  import { mkdtempSync as mkdtempSync9, rmSync as rmSync19, writeFileSync as writeFileSync9 } from "node:fs";
16212
16610
  import { tmpdir as tmpdir4 } from "node:os";
16213
- import { join as join29 } from "node:path";
16611
+ import { join as join30 } from "node:path";
16214
16612
  import { gunzipSync as gunzipSync2, gzipSync as gzipSync2 } from "node:zlib";
16215
- import { execa as execa11 } from "execa";
16613
+ import { execa as execa12 } from "execa";
16216
16614
 
16217
16615
  // src/coding-workspace/checkpoint.ts
16218
- import { createHash as createHash11 } from "node:crypto";
16616
+ import { createHash as createHash12 } from "node:crypto";
16219
16617
  import { resolve as resolve12 } from "node:path";
16220
- import { execa as execa10 } from "execa";
16221
- var digest6 = (value) => createHash11("sha256").update(value).digest("hex");
16618
+ import { execa as execa11 } from "execa";
16619
+ var digest6 = (value) => createHash12("sha256").update(value).digest("hex");
16222
16620
  var oid = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
16223
16621
  var MANIFEST_BYTES = 1536 * 1024;
16224
16622
  var regular = (mode) => mode === null || mode === "100644" || mode === "100755";
@@ -16259,7 +16657,7 @@ async function captureCheckpointReview(input) {
16259
16657
  };
16260
16658
  const git3 = async (args, text4, maximum = MANIFEST_BYTES) => {
16261
16659
  signal.throwIfAborted();
16262
- const child = await execa10("git", [
16660
+ const child = await execa11("git", [
16263
16661
  "--no-optional-locks",
16264
16662
  "-c",
16265
16663
  "core.hooksPath=/dev/null",
@@ -16437,8 +16835,8 @@ async function takeCheckpoint(options) {
16437
16835
  }
16438
16836
  async function applyCheckpoint(options) {
16439
16837
  const git3 = await pinnedGit(options.repoPath, options.worktree);
16440
- const dir = mkdtempSync9(join29(tmpdir4(), "mikka-checkpoint-"));
16441
- const file = join29(dir, "checkpoint.patch");
16838
+ const dir = mkdtempSync9(join30(tmpdir4(), "mikka-checkpoint-"));
16839
+ const file = join30(dir, "checkpoint.patch");
16442
16840
  try {
16443
16841
  const patch = gunzipSync2(Buffer.from(options.checkpoint.patch, "base64"));
16444
16842
  if (!patch.length && options.checkpoint.files === 0) return true;
@@ -16459,7 +16857,7 @@ async function applyCheckpoint(options) {
16459
16857
  }
16460
16858
  }
16461
16859
  async function hasCommit(repoPath, commit) {
16462
- return execa11(
16860
+ return execa12(
16463
16861
  "git",
16464
16862
  ["-c", "core.hooksPath=/dev/null", "cat-file", "-e", `${commit}^{commit}`],
16465
16863
  { cwd: repoPath, stdin: "ignore" }
@@ -16782,10 +17180,6 @@ var MemoryServer = class {
16782
17180
  var DEFAULT_STALL_MS = 10 * 6e4;
16783
17181
  var DEFAULT_STOP_GRACE_MS = 3e3;
16784
17182
  var DEFAULT_CANCEL_GRACE_MS = 1e4;
16785
- var VERIFY_TIMEOUT_MS = 30 * 6e4;
16786
- var MAX_REPORTED_FILES = 5e3;
16787
- var MAX_REPORTED_CRITERIA = 200;
16788
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16789
17183
  var CHECKPOINT_EVERY_MS = 2 * 6e4;
16790
17184
  var RunSupervisor = class {
16791
17185
  constructor(deps) {
@@ -17232,7 +17626,7 @@ var RunSupervisor = class {
17232
17626
  const entry = this.deps.journal.get(runId);
17233
17627
  if (splitChatFiles(text4).files.length) {
17234
17628
  if (!entry || !this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
17235
- text4 = await materializeChatFiles(text4, join30(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
17629
+ text4 = await materializeChatFiles(text4, join31(this.deps.adapterStateDir, "inputs", runId), (id5) => this.deps.downloadChatFile(entry.assignment, id5, run3.abort.signal));
17236
17630
  }
17237
17631
  await run3.session.send(text4, mode);
17238
17632
  }
@@ -17403,80 +17797,25 @@ var RunSupervisor = class {
17403
17797
  * The only way into a terminal state: the terminal patch, then exactly one
17404
17798
  * completion for the server, then the outbox is compacted.
17405
17799
  */
17406
- finish(runId, stopReason, error, report2 = baseReport(error), failureDetails) {
17800
+ finish(runId, stopReason, error, report2, failureDetails) {
17407
17801
  this.active.get(runId)?.toolApproval?.revoke();
17408
17802
  const active = this.active.get(runId);
17409
- if (active?.cancelRequested || active?.forcedStop) {
17410
- stopReason = active.forcedStop ?? "cancelled";
17411
- error = void 0;
17412
- }
17413
- active?.span?.set("mikka.outcome", stopReason);
17414
- if (stopReason !== "provider_failure" && report2.providerFailure) {
17415
- const { providerFailure: _failure, ...rest } = report2;
17416
- report2 = rest;
17417
- }
17418
- if (stopReason !== "provider_failure" && stopReason !== "quota_exhausted" && report2.providerCheckpoint) {
17419
- const { providerCheckpoint: _checkpoint, ...rest } = report2;
17420
- report2 = rest;
17421
- }
17422
- const entry = this.deps.journal.get(runId);
17423
- const planning = entry?.assignment.kind === "plan";
17424
- if (entry && stopReason === "blocked" && report2.repositorySelection)
17425
- entry.assignment.preserveQuestionWorktree = true;
17426
- const readOnlyTask = entry && (isReadOnlyTask(entry.assignment) || entry.assignment.factoryCheck?.reportOnly === true || entry.assignment.factoryExecuteKind === "deliverable");
17427
- const { sourceCommit: _source, deliverableCommit: _delivery, skillMount: _mount, skillPrompt: _prompt, execution: _execution, runtime: _runtime, safePoint: _safePoint, ...content } = report2;
17428
- report2 = {
17429
- ...content,
17430
- ...active?.safePoint ? { safePoint: active.safePoint } : {},
17431
- ...entry?.baseCommit && /^[a-f0-9]{40}$/.test(entry.baseCommit) ? { sourceCommit: entry.baseCommit } : {},
17432
- ...entry?.assignment.factoryExecuteKind === "deliverable" && entry.deliverableCommit ? { deliverableCommit: entry.deliverableCommit } : {},
17433
- // What the prompt actually carried of the run's skills; a deferred body
17434
- // is a fact the person needs to see, not something to leave unsaid.
17435
- ...entry && skillPromptOf(entry.assignment) ? { skillPrompt: skillPromptOf(entry.assignment) } : {},
17436
- ...entry?.skillMount && entry.skillMount.sessionId === entry.sessionId && entry.skillMount.receiptId === entry.assignment.skillReceipt?.id && entry.skillMount.versionId === entry.assignment.skillReceipt?.artifact.versionId && entry.skillMount.sha256 === entry.assignment.skillReceipt?.artifact.sha256 ? {
17437
- skillMount: entry.skillMount,
17438
- ...entry.runtime ? { runtime: {
17439
- ...entry.runtime,
17440
- observedModel: this.active.get(runId)?.session?.runtimeModel ?? entry.runtime.observedModel
17441
- } } : {},
17442
- ...entry.execution && entry.assignment.benchmark ? { execution: {
17443
- ...entry.execution,
17444
- observedModel: this.active.get(runId)?.session?.runtimeModel ?? entry.execution.observedModel
17445
- } } : {}
17446
- } : {}
17447
- };
17448
- this.emitPlanCards(runId, report2, planning);
17449
- this.endMessage(runId, this.active.get(runId)?.runtimeTiming?.finish());
17450
- this.flushMasker(runId);
17451
- this.openParts.delete(runId);
17452
- if (stopReason === "submitted") this.setState(runId, "finishing");
17453
- let state2 = runStateForStop(stopReason);
17454
- if (stopReason === "submitted" && report2.verify.status !== "passed") {
17455
- const failed = report2.verify.status === "failed";
17456
- if (!planning && !readOnlyTask) state2 = failed ? "failed" : report2.publish?.pushed === true ? "succeeded" : "stopped";
17457
- if (!failed && !planning && !readOnlyTask)
17458
- error ??= "Submitted, but no verify command ran; the work is unverified";
17459
- }
17460
- if ((stopReason === "asked_human" || stopReason === "blocked") && report2.question) {
17461
- this.deps.journal.update(runId, {
17462
- waitingQuestionId: report2.question.questionId
17463
- });
17464
- }
17465
- if (state2 === "failed") active?.span?.fail({ name: "RunFailure" }, stopReason);
17466
- else active?.span?.set("mikka.outcome", stopReason);
17467
- this.setState(runId, state2, {
17468
- stopReason,
17469
- ...error ? { error } : {}
17470
- });
17471
- const terminalFailure = state2 === "failed" && !active?.cancelRequested && !active?.forcedStop ? captureRunFailure(failureDetails ?? new Error(error ?? report2.summary), {
17803
+ finishRun({
17472
17804
  runId,
17473
- appVersion: DAEMON_VERSION,
17474
- sensitiveText: [entry?.assignment.prompt ?? ""]
17475
- }) : void 0;
17476
- this.push(runId, {
17477
- kind: "complete",
17478
- completion: { stopReason, report: report2, ...terminalFailure ? { failureDetails: terminalFailure } : {} }
17479
- });
17805
+ journal: this.deps.journal,
17806
+ active,
17807
+ closeOutput: (report3, planning) => {
17808
+ this.emitPlanCards(runId, report3, planning);
17809
+ this.endMessage(runId, this.active.get(runId)?.runtimeTiming?.finish());
17810
+ this.flushMasker(runId);
17811
+ this.openParts.delete(runId);
17812
+ },
17813
+ setState: (state2, extra) => this.setState(runId, state2, extra),
17814
+ complete: (completion) => this.push(runId, { kind: "complete", completion })
17815
+ }, stopReason, error, report2, failureDetails);
17816
+ this.cleanupFinishedRun(runId);
17817
+ }
17818
+ cleanupFinishedRun(runId) {
17480
17819
  this.disposeMasker(runId);
17481
17820
  const run3 = this.active.get(runId);
17482
17821
  if (run3) void this.closeMailbox(run3).catch(() => this.deps.log.warn("Run mailbox shutdown failed"));
@@ -17577,143 +17916,6 @@ var RunSupervisor = class {
17577
17916
  this.forceStop(runId, run3, "device_lost");
17578
17917
  signal.throwIfAborted();
17579
17918
  }
17580
- /**
17581
- * What the frozen Profile selected and what its agent actually loaded. The
17582
- * load receipts are written by the `load_skill` tool itself; a configured
17583
- * Skill without a receipt is not reported as used. Digests must match the
17584
- * configured pinned body, so a tampered manifest cannot mint a receipt.
17585
- */
17586
- profileSkillReport(runId, assignment) {
17587
- const configured = (assignment.profileSkills ?? []).map((skill) => ({ id: skill.id, name: skill.name, source: skill.source, digest: skill.digest }));
17588
- for (const slug of assignment.repositorySkills ?? []) {
17589
- if (!configured.some((ref) => ref.id === `repository:${slug}`)) configured.push({ id: `repository:${slug}`, name: slug, source: "repository", digest: null });
17590
- }
17591
- if (configured.length === 0) return void 0;
17592
- const loaded = [];
17593
- if (this.deps.adapterStateDir) {
17594
- const dir = join30(runPaths(this.deps.adapterStateDir, runId).runDir, PROFILE_SKILLS_DIR, PROFILE_SKILL_LOADS_DIR);
17595
- try {
17596
- for (const name of readdirSync8(dir).sort()) {
17597
- if (!name.endsWith(".json") || loaded.length >= configured.length) continue;
17598
- const file = join30(dir, name), meta = lstatSync11(file, { throwIfNoEntry: false });
17599
- if (!meta?.isFile() || meta.isSymbolicLink() || meta.nlink !== 1 || meta.size < 2 || meta.size > 4096) continue;
17600
- const receipt = profileSkillLoadReceiptSchema.safeParse(JSON.parse(readFileSync14(file, "utf8")));
17601
- if (!receipt.success || loaded.some((item) => item.id === receipt.data.id)) continue;
17602
- if (!configured.some((ref) => ref.id === receipt.data.id && (ref.digest === null || ref.digest === receipt.data.digest))) continue;
17603
- loaded.push(receipt.data);
17604
- }
17605
- } catch {
17606
- }
17607
- }
17608
- return { configured, loaded };
17609
- }
17610
- /**
17611
- * The handoff report: the agent's own words (summary, questions, next
17612
- * step, blocker) plus what only the daemon may state: changed files and,
17613
- * after a submit, the verify result. Anything else the agent sent
17614
- * (a self-reported verify, say) is dropped. `verifyError` describes a
17615
- * failed verify (command and exit code) for the run's error text.
17616
- */
17617
- async report(runId, worktree, repo, assignment, stopReason, error, agent, signal) {
17618
- const profileSkills = this.profileSkillReport(runId, assignment);
17619
- let report2 = {
17620
- ...baseReport(error),
17621
- ...pickAgentReport(agent),
17622
- ...profileSkills ? { profileSkills } : {}
17623
- };
17624
- const filesChanged = (await this.deps.worktrees.changedFiles(worktree, this.deps.journal.get(runId)?.baseCommit).catch(() => [])).slice(0, MAX_REPORTED_FILES);
17625
- const inferred = assignment.factoryCheck?.stage === "verify" && assignment.factoryCheck.inferCommand && !assignment.factoryCheck.reportOnly ? report2.verificationCommand : void 0;
17626
- const command = assignment.verifyCommand ?? inferred?.command;
17627
- if (stopReason === "submitted") this.assertFinishingRunLive(runId, signal);
17628
- if (stopReason === "submitted" && assignment.factoryExecuteKind === "deliverable") {
17629
- const deliverableCommit = await retainDeliverable(repo.path, worktree, runId, signal);
17630
- this.assertFinishingRunLive(runId, signal);
17631
- this.deps.journal.update(runId, { deliverableCommit });
17632
- }
17633
- if (stopReason !== "submitted" && fixedCandidateCheck(assignment)) {
17634
- const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).catch(() => null);
17635
- if (fixed) report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
17636
- }
17637
- if (stopReason !== "submitted" || assignment.kind === "plan" || isReadOnlyTask(assignment) || assignment.factoryExecuteKind === "deliverable")
17638
- return {
17639
- report: { ...report2, filesChanged, verify: { status: "not_run" } }
17640
- };
17641
- if (!command) {
17642
- if (fixedCandidateCheck(assignment)) {
17643
- const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal);
17644
- report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
17645
- }
17646
- this.assertFinishingRunLive(runId, signal);
17647
- const tree = await this.deps.publisher?.snapshot({ worktree, repo, signal });
17648
- this.assertFinishingRunLive(runId, signal);
17649
- return { report: { ...report2, filesChanged, verify: { status: "not_run" } }, tree };
17650
- }
17651
- let execution = {};
17652
- const failed = (output2, verifyError) => ({
17653
- report: {
17654
- ...report2,
17655
- filesChanged,
17656
- verify: { status: "failed", command, output: output2, ...execution }
17657
- },
17658
- verifyError
17659
- });
17660
- const publisher = this.deps.publisher;
17661
- let before;
17662
- try {
17663
- if (fixedCandidateCheck(assignment)) {
17664
- if (runPolicy(assignment.policy).readOnly !== true)
17665
- throw new Error("Check assignment is missing its read-only policy");
17666
- const fixed = await fixedCheckSnapshot(
17667
- repo.path,
17668
- worktree,
17669
- assignment.baseBranch,
17670
- signal
17671
- );
17672
- report2 = { ...report2, check: { sha: fixed.sha, readOnly: true } };
17673
- before = fixed.tree;
17674
- } else {
17675
- before = await publisher?.snapshot({ worktree, repo, signal });
17676
- }
17677
- } catch (snapshotError) {
17678
- signal.throwIfAborted();
17679
- return failed("", `Could not read the worktree: ${String(snapshotError)}`);
17680
- }
17681
- this.assertFinishingRunLive(runId, signal);
17682
- const result = await (this.deps.verify ?? unsandboxedVerify)({
17683
- runId,
17684
- worktree,
17685
- repo,
17686
- command,
17687
- timeoutMs: VERIFY_TIMEOUT_MS,
17688
- signal,
17689
- readOnly: runPolicy(assignment.policy).readOnly === true,
17690
- githubEnvironment: this.active.get(runId)?.github?.env
17691
- });
17692
- this.assertFinishingRunLive(runId, signal);
17693
- execution = {
17694
- exitCode: result.exitCode,
17695
- signal: result.signal,
17696
- timedOut: result.timedOut
17697
- };
17698
- const output = result.output.slice(-4e3);
17699
- if (result.exitCode !== 0 || result.timedOut)
17700
- return failed(output, verifyFailure(command, result));
17701
- const after = fixedCandidateCheck(assignment) ? await fixedCheckSnapshot(repo.path, worktree, assignment.baseBranch, signal).then((fixed) => fixed.tree).catch(() => null) : publisher ? await publisher.snapshot({ worktree, repo, signal }).catch(() => null) : void 0;
17702
- this.assertFinishingRunLive(runId, signal);
17703
- if (after !== before)
17704
- return failed(
17705
- output,
17706
- `Submitted, but the verify command changed the worktree (\`${command}\`); the work is unverified`
17707
- );
17708
- return {
17709
- report: {
17710
- ...report2,
17711
- filesChanged,
17712
- verify: { status: "passed", command, output, ...inferred ? { inferredFrom: inferred.basis } : {}, ...execution }
17713
- },
17714
- tree: before
17715
- };
17716
- }
17717
17919
  /**
17718
17920
  * Where a fresh worktree starts: the issue's branch on the remote when
17719
17921
  * the run pushes there (ADR 0024), so it builds on what earlier runs and
@@ -17739,7 +17941,7 @@ var RunSupervisor = class {
17739
17941
  try {
17740
17942
  return await withRunGitCredentials(
17741
17943
  assignment,
17742
- runPaths(this.deps.adapterStateDir ?? join30(tmpdir5(), "mikka-run-state"), runId).privateDir,
17944
+ runPaths(this.deps.adapterStateDir ?? join31(tmpdir5(), "mikka-run-state"), runId).privateDir,
17743
17945
  (env) => this.deps.worktrees.fetchBranch(
17744
17946
  repo.path,
17745
17947
  repo.push?.remote ?? "origin",
@@ -17757,39 +17959,6 @@ var RunSupervisor = class {
17757
17959
  return base;
17758
17960
  }
17759
17961
  }
17760
- /**
17761
- * A failed commit or push is reported (in a `data-publish` chunk and in
17762
- * the completion's report), never fails the verified run.
17763
- */
17764
- async publish(runId, worktree, repo, assignment, report2, tree, signal) {
17765
- const publisher = this.deps.publisher;
17766
- let data;
17767
- try {
17768
- this.assertFinishingRunLive(runId, signal);
17769
- data = await publisher.publish({
17770
- runId,
17771
- worktree,
17772
- repo,
17773
- assignment,
17774
- report: report2,
17775
- tree,
17776
- githubEnvironment: this.active.get(runId)?.github?.env,
17777
- signal
17778
- });
17779
- } catch (error) {
17780
- const message = error instanceof Error ? error.message : String(error);
17781
- if (!signal.aborted) this.deps.log.error({ run_id: runId, err: this.logError(runId, error) }, "publish failed");
17782
- data = {
17783
- branch: "",
17784
- commit: null,
17785
- pushed: false,
17786
- remote: null,
17787
- note: signal.aborted ? "Run stopped before publication completed" : `Commit failed: ${message}`.slice(0, 2e3)
17788
- };
17789
- }
17790
- this.emit(runId, { type: "data-publish", data });
17791
- return data;
17792
- }
17793
17962
  launch(runId, repo, initialClaim = false) {
17794
17963
  const run3 = {
17795
17964
  repoPath: repo.path,
@@ -18138,7 +18307,7 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
18138
18307
  let followUp = assignment.followUp;
18139
18308
  if (splitChatFiles(prompt).files.length || followUp && splitChatFiles(followUp).files.length) {
18140
18309
  if (!this.deps.downloadChatFile || !this.deps.adapterStateDir) throw Error("Run attachments unavailable");
18141
- const directory = join30(this.deps.adapterStateDir, "inputs", runId);
18310
+ const directory = join31(this.deps.adapterStateDir, "inputs", runId);
18142
18311
  const download2 = (id5) => this.deps.downloadChatFile(assignment, id5, run3.abort.signal);
18143
18312
  prompt = await materializeChatFiles(prompt, directory, download2);
18144
18313
  if (followUp) followUp = await materializeChatFiles(followUp, directory, download2);
@@ -18160,13 +18329,13 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
18160
18329
  if (assignment.requireSessionResume && (!assignment.resumeSessionId || !assignment.continuesRunId || !adapter.capabilities.supportsResume || !resuming && !continueSession || resuming && entry.sessionId !== assignment.resumeSessionId))
18161
18330
  throw new Error("factory_question_session_resume_required");
18162
18331
  const benchmark = assignment.benchmark;
18163
- const policyDigest = assignment.skillReceipt ? createHash12("sha256").update(runPolicyDigestInput(assignment.policy)).digest("hex") : void 0;
18332
+ const policyDigest = assignment.skillReceipt ? createHash13("sha256").update(runPolicyDigestInput(assignment.policy)).digest("hex") : void 0;
18164
18333
  if (benchmark && (!assignment.skillReceipt || assignment.harness === "mock" || !assignment.verifyCommand || benchmark.sourceCommit !== this.deps.journal.get(runId)?.baseCommit || policyDigest !== benchmark.policyDigest)) throw new Error("Frozen benchmark execution configuration mismatch");
18165
18334
  let fixtureDigest;
18166
18335
  if (benchmark) {
18167
18336
  if (runPolicy(assignment.policy).readOnly !== true) throw new Error("Benchmark fixture must be read-only");
18168
18337
  const fixed = await fixedCheckSnapshot(repo.path, worktree, benchmark.sourceCommit);
18169
- fixtureDigest = createHash12("sha256").update(fixed.sha).digest("hex");
18338
+ fixtureDigest = createHash13("sha256").update(fixed.sha).digest("hex");
18170
18339
  if (fixtureDigest !== benchmark.fixtureDigest) throw new Error("Frozen benchmark fixture digest mismatch");
18171
18340
  }
18172
18341
  const previousMount = entry.skillMount;
@@ -18207,7 +18376,7 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
18207
18376
  if (!this.deps.adapterStateDir || assignment.harness === "mock" || !session.sessionId || resuming && session.sessionId !== entry.sessionId || assignment.requireSessionResume && session.sessionId !== assignment.resumeSessionId)
18208
18377
  throw new Error("Skill mount requires the actual original harness session");
18209
18378
  verifySkillAssignment(assignment);
18210
- const file = join30(
18379
+ const file = join31(
18211
18380
  runPaths(this.deps.adapterStateDir, runId).runDir,
18212
18381
  SKILLS_DIR,
18213
18382
  skillSlug(assignment.skills[0].name),
@@ -18319,55 +18488,29 @@ ${run3.drive.folders.map((folder) => `- ${folder.scope}: ${folder.path}${folder.
18319
18488
  const finishingSignal = AbortSignal.any([this.stopController.signal, run3.abort.signal]);
18320
18489
  run3.runtimeTiming?.finishing();
18321
18490
  await this.closeMailbox(run3);
18322
- let stopReason = stopReasonOf(event, run3, assignment);
18323
- const error = event.error ?? (stopReason === "turn_ended" ? "Session ended without a submission" : stopReason === "timeout" ? "No progress before the watchdog limit" : stopReason === "device_lost" ? "Run lease expired; the server could not be reached" : void 0);
18324
- let outcome;
18325
- try {
18326
- if (assignment.benchmark && !run3.cancelRequested) {
18327
- const fixed = await fixedCheckSnapshot(repo.path, worktree, assignment.benchmark.sourceCommit, finishingSignal);
18328
- if (createHash12("sha256").update(fixed.sha).digest("hex") !== assignment.benchmark.fixtureDigest)
18329
- throw new Error("Benchmark fixture changed during model execution");
18330
- }
18331
- outcome = await this.report(runId, worktree, repo, assignment, stopReason, error, event.report, finishingSignal);
18332
- } catch (error2) {
18333
- if (!finishingSignal.aborted) throw error2;
18334
- outcome = { report: { ...baseReport(), ...pickAgentReport(event.report) } };
18335
- }
18336
- if (this.stopping) return;
18337
- stopReason = stopReasonOf(event, run3, assignment);
18338
- const { verifyError, tree } = outcome;
18339
- let report2 = stopReason === "quota_exhausted" ? { ...outcome.report, resetsAt: event.quota?.resetsAt ?? null } : outcome.report;
18340
- if (stopReason === "provider_failure") {
18341
- report2 = {
18342
- ...report2,
18343
- providerFailure: providerFailureSchema.parse(event.providerFailure),
18344
- ...event.quota ? { resetsAt: event.quota.resetsAt } : {}
18345
- };
18346
- }
18347
- const policy = runPolicy(assignment.policy);
18348
- if (stopReason === "submitted" && report2.verify.status !== "failed" && tree && // The draft-PR exception requires an explicit repository push
18349
- // approval. It must not even create a local commit without it.
18350
- (report2.verify.status === "passed" || pushDecision(policy).push) && // A read-only check (ADR 0046) never commits or pushes: it reports
18351
- // on the commit the implementation run already pushed.
18352
- policy.readOnly !== true) {
18353
- const publish = await this.publish(
18354
- runId,
18355
- worktree,
18356
- repo,
18357
- assignment,
18358
- report2,
18359
- tree,
18360
- finishingSignal
18361
- );
18362
- report2 = { ...report2, publish };
18363
- stopReason = stopReasonOf(event, run3, assignment);
18364
- }
18491
+ const publication = await verifyAndPublish({
18492
+ deps: this.deps,
18493
+ runId,
18494
+ worktree,
18495
+ repo,
18496
+ assignment,
18497
+ signal: finishingSignal,
18498
+ assertLive: () => this.assertFinishingRunLive(runId, finishingSignal),
18499
+ githubEnvironment: () => this.active.get(runId)?.github?.env,
18500
+ getStopReason: () => stopReasonOf(event, run3, assignment),
18501
+ isStopping: () => this.stopping,
18502
+ cancelRequested: run3.cancelRequested,
18503
+ logPublishError: (error) => this.deps.log.error({ run_id: runId, err: this.logError(runId, error) }, "publish failed"),
18504
+ emitPublish: (data) => this.emit(runId, { type: "data-publish", data })
18505
+ }, event);
18506
+ if (!publication) return;
18507
+ let { report: report2 } = publication;
18365
18508
  const capturesSaved = !this.stopping && await this.flushCaptures(runId, finishingSignal);
18366
- stopReason = stopReasonOf(event, run3, assignment);
18509
+ const stopReason = stopReasonOf(event, run3, assignment);
18367
18510
  const checkpoint = await this.saveTerminalCheckpoint(runId, run3, capturesSaved);
18368
18511
  if (stopReason === "provider_failure" || stopReason === "quota_exhausted") report2 = { ...report2, providerCheckpoint: checkpoint.checkpoint };
18369
18512
  if (this.stopping) return;
18370
- this.finish(runId, stopReason, error ?? verifyError, report2, event.failureDetails);
18513
+ this.finish(runId, stopReason, publication.error, report2, event.failureDetails);
18371
18514
  log.info(
18372
18515
  { outcome: event.outcome, stop_reason: stopReason },
18373
18516
  "run ended"
@@ -18415,55 +18558,6 @@ function abortPromise(signal) {
18415
18558
  signal.addEventListener("abort", () => resolve19(ABORTED), { once: true });
18416
18559
  });
18417
18560
  }
18418
- function pickAgentReport(agent) {
18419
- if (!agent) return {};
18420
- const picked = {};
18421
- if (agent.repositorySelection) picked.repositorySelection = agent.repositorySelection;
18422
- if (agent.verificationCommand && typeof agent.verificationCommand.command === "string" && agent.verificationCommand.command.trim() && typeof agent.verificationCommand.basis === "string" && agent.verificationCommand.basis.trim())
18423
- picked.verificationCommand = { command: agent.verificationCommand.command.trim().slice(0, 2e3), basis: agent.verificationCommand.basis.trim().slice(0, 2e3) };
18424
- const visualEvidence = runVisualEvidence.safeParse(agent.visualEvidence);
18425
- if (visualEvidence.success) picked.visualEvidence = visualEvidence.data;
18426
- const verdict = reviewVerdict.safeParse(agent.reviewVerdict);
18427
- if (verdict.success) picked.reviewVerdict = verdict.data;
18428
- if (typeof agent.summary === "string")
18429
- picked.summary = agent.summary.slice(0, 1e4);
18430
- if (Array.isArray(agent.openQuestions) && agent.openQuestions.every((q) => typeof q === "string"))
18431
- picked.openQuestions = agent.openQuestions.slice(0, 50).map((q) => q.slice(0, 2e3));
18432
- if (typeof agent.nextStep === "string")
18433
- picked.nextStep = agent.nextStep.slice(0, 2e3);
18434
- else if (agent.nextStep === null) picked.nextStep = null;
18435
- if (typeof agent.blockedOn === "string")
18436
- picked.blockedOn = agent.blockedOn.slice(0, 500);
18437
- const question = runQuestion.safeParse(agent.question);
18438
- if (question.success) picked.question = question.data;
18439
- if (agent.plan) picked.plan = agent.plan;
18440
- if (typeof agent.previewDatabaseBranch === "string" && agent.previewDatabaseBranch.trim())
18441
- picked.previewDatabaseBranch = agent.previewDatabaseBranch.trim().slice(0, 500);
18442
- if (Array.isArray(agent.criteria)) {
18443
- const criteria = [];
18444
- for (const entry of agent.criteria) {
18445
- if (criteria.length >= MAX_REPORTED_CRITERIA) break;
18446
- if (!entry || typeof entry !== "object") continue;
18447
- const { criterionId, text: text4, passed, status: status3, reason, resolution, evidence, command, exitCode } = entry;
18448
- if (!(typeof criterionId === "string" && UUID_RE.test(criterionId)) && !(typeof text4 === "string" && text4.trim()))
18449
- continue;
18450
- if (typeof passed !== "boolean") continue;
18451
- const criterion = runCriterion.safeParse({
18452
- ...typeof criterionId === "string" && UUID_RE.test(criterionId) ? { criterionId } : {},
18453
- ...typeof text4 === "string" && text4.trim() ? { text: text4.trim().slice(0, 2e3) } : {},
18454
- passed,
18455
- ...status3 !== void 0 ? { status: status3 } : {},
18456
- ...typeof reason === "string" && reason.trim() ? { reason: reason.trim().slice(0, 2e3) } : {},
18457
- ...typeof resolution === "string" && resolution.trim() ? { resolution: resolution.trim().slice(0, 2e3) } : {},
18458
- ...typeof command === "string" && command.trim() ? { command: command.trim().slice(0, 2e3), ...exitCode === null || typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? { exitCode } : {} } : {},
18459
- ...typeof evidence === "string" ? { evidence: evidence.slice(0, 1e4) } : {}
18460
- });
18461
- if (criterion.success) criteria.push(criterion.data);
18462
- }
18463
- picked.criteria = criteria;
18464
- }
18465
- return picked;
18466
- }
18467
18561
  var KEEP_WORKTREE = ["turn_ended", "asked_human", "quota_exhausted", "provider_failure"];
18468
18562
  function startupProviderFailure(error) {
18469
18563
  for (let depth = 0; depth < 5 && error instanceof Error; depth++, error = error.cause) {
@@ -18479,50 +18573,6 @@ function stopReasonOf(event, run3, assignment) {
18479
18573
  if (event.outcome === "failed" && event.quota && quotaStopApplies(assignment)) return "quota_exhausted";
18480
18574
  return event.outcome === "failed" ? "error" : "turn_ended";
18481
18575
  }
18482
- async function unsandboxedVerify(run3) {
18483
- const result = await execa12(run3.command, {
18484
- shell: true,
18485
- cwd: run3.worktree,
18486
- env: buildChildEnv(),
18487
- extendEnv: false,
18488
- reject: false,
18489
- all: true,
18490
- stdin: "ignore",
18491
- timeout: run3.timeoutMs,
18492
- cancelSignal: run3.signal,
18493
- killDescendants: true
18494
- });
18495
- return {
18496
- exitCode: result.exitCode ?? null,
18497
- signal: result.signal ?? null,
18498
- timedOut: result.timedOut,
18499
- output: String(result.all ?? "")
18500
- };
18501
- }
18502
- function verifyFailure(command, result) {
18503
- const how = result.timedOut ? "timed out" : result.exitCode !== null ? `exited with code ${result.exitCode}` : result.signal ? `was killed by ${result.signal}` : "did not finish";
18504
- return `Submitted, but the verify command failed: \`${command}\` ${how}`;
18505
- }
18506
- function baseReport(summary = "") {
18507
- return emptyRunReport(summary.slice(0, 1e4));
18508
- }
18509
- function isReadOnlyTask(assignment) {
18510
- return runPolicy(assignment.policy).readOnly === true && assignment.kind !== "acceptance" && !assignment.benchmark;
18511
- }
18512
- function skillPromptOf(assignment) {
18513
- const skills = assignment.skills;
18514
- if (!skills?.length) return void 0;
18515
- const plan = skillPromptPlan(skills);
18516
- return {
18517
- budgetChars: plan.budgetChars,
18518
- usedChars: plan.usedChars,
18519
- inlined: plan.inlined.map((entry) => entry.name),
18520
- deferred: plan.degraded.map((entry) => entry.name)
18521
- };
18522
- }
18523
- function fixedCandidateCheck(assignment) {
18524
- return assignment.kind === "acceptance" && runPolicy(assignment.policy).readOnly === true && typeof assignment.baseBranch === "string" && /^[a-f0-9]{40}$/.test(assignment.baseBranch);
18525
- }
18526
18576
 
18527
18577
  // src/device-gateway.ts
18528
18578
  var DEVICE_GATEWAY_PING = "ping";
@@ -18753,10 +18803,10 @@ import { constants as constants7 } from "node:fs";
18753
18803
  import { open as open2, readFile as readFile5, realpath as realpath2 } from "node:fs/promises";
18754
18804
  import { execFile as execFile7 } from "node:child_process";
18755
18805
  import { promisify as promisify7 } from "node:util";
18756
- import { createHash as createHash13 } from "node:crypto";
18806
+ import { createHash as createHash14 } from "node:crypto";
18757
18807
  import { extname, resolve as resolve14 } from "node:path";
18758
18808
  var execute2 = promisify7(execFile7);
18759
- var hash = (value) => createHash13("sha256").update(value).digest("hex");
18809
+ var hash = (value) => createHash14("sha256").update(value).digest("hex");
18760
18810
  var denied = () => new CodingWorkspaceError("workspace_path_unavailable");
18761
18811
  function isFileReadRequest(request2) {
18762
18812
  return request2.kind === "file" || request2.kind === "tree" || request2.kind === "search" || request2.kind === "context";
@@ -19005,8 +19055,8 @@ async function readWorkspaceReceipt(command, entry) {
19005
19055
  // src/coding-workspace/diff.ts
19006
19056
  import { constants as constants8 } from "node:fs";
19007
19057
  import { open as open3, realpath as realpath3, mkdtemp as mkdtemp2, mkdir as mkdir4, writeFile as writeFile3, rm as rm3, lstat as lstat4 } from "node:fs/promises";
19008
- import { createHash as createHash14 } from "node:crypto";
19009
- import { resolve as resolve15, dirname as dirname15, join as join31, posix } from "node:path";
19058
+ import { createHash as createHash15 } from "node:crypto";
19059
+ import { resolve as resolve15, dirname as dirname15, join as join32, posix } from "node:path";
19010
19060
  import { tmpdir as tmpdir6 } from "node:os";
19011
19061
  import { execa as execa13 } from "execa";
19012
19062
 
@@ -19075,7 +19125,7 @@ var CRLFCleaner = class {
19075
19125
  };
19076
19126
 
19077
19127
  // src/coding-workspace/diff.ts
19078
- var digest7 = (value) => createHash14("sha256").update(value).digest("hex");
19128
+ var digest7 = (value) => createHash15("sha256").update(value).digest("hex");
19079
19129
  var fenceMode = (mode) => mode === "100644" || mode === "100755" || mode === "120000" || mode === "160000" ? mode : null;
19080
19130
  var oid2 = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
19081
19131
  var MAX_SCAN_BYTES = 64 * 1024 * 1024;
@@ -19184,12 +19234,12 @@ async function conversionSettings(git3) {
19184
19234
  const host = buildChildEnv({});
19185
19235
  const defaults = ["/etc/gitattributes", "/usr/etc/gitattributes", "/usr/local/etc/gitattributes"];
19186
19236
  if (!external) {
19187
- const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join31(host.HOME, ".config") : void 0);
19188
- if (configHome) defaults.push(join31(configHome, "git", "attributes"));
19237
+ const configHome = host.XDG_CONFIG_HOME || (host.HOME ? join32(host.HOME, ".config") : void 0);
19238
+ if (configHome) defaults.push(join32(configHome, "git", "attributes"));
19189
19239
  }
19190
- const info = join31(git3.commonDir, "info");
19240
+ const info = join32(git3.commonDir, "info");
19191
19241
  if (await existsWithoutReading(info)) {
19192
- if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join31(info, "attributes")))
19242
+ if (!(await lstat4(info)).isDirectory() || await existsWithoutReading(join32(info, "attributes")))
19193
19243
  throw new CodingWorkspaceError("workspace_unsupported");
19194
19244
  }
19195
19245
  for (const path3 of defaults) if (await existsWithoutReading(path3)) throw new CodingWorkspaceError("workspace_unsupported");
@@ -19235,10 +19285,10 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19235
19285
  throw new CodingWorkspaceError("workspace_unsupported");
19236
19286
  attributeBytes.set(path3, bytes);
19237
19287
  }
19238
- const directory = await mkdtemp2(join31(tmpdir6(), "mikka-diff-attributes-"));
19288
+ const directory = await mkdtemp2(join32(tmpdir6(), "mikka-diff-attributes-"));
19239
19289
  const actions = /* @__PURE__ */ new Map();
19240
19290
  try {
19241
- const gitDir = join31(directory, "git"), worktree = join31(directory, "worktree");
19291
+ const gitDir = join32(directory, "git"), worktree = join32(directory, "worktree");
19242
19292
  await mkdir4(worktree, { mode: 448 });
19243
19293
  const env = {
19244
19294
  ...buildChildEnv({}),
@@ -19258,7 +19308,7 @@ async function workingConversion(git3, root, paths, head, signal, budget) {
19258
19308
  killDescendants: true
19259
19309
  });
19260
19310
  for (const [path3, bytes] of attributeBytes) {
19261
- const target = join31(worktree, path3);
19311
+ const target = join32(worktree, path3);
19262
19312
  await mkdir4(dirname15(target), { recursive: true, mode: 448 });
19263
19313
  await writeFile3(target, bytes, { mode: 384, flag: "wx" });
19264
19314
  }
@@ -19341,7 +19391,7 @@ async function currentFile(root, path3, head, budget, signal, conversion, git3)
19341
19391
  budget.bytes += size;
19342
19392
  if (budget.bytes > MAX_SCAN_BYTES) throw new CodingWorkspaceError("workspace_limit_exceeded");
19343
19393
  const algorithm = head.length === 64 ? "sha256" : "sha1";
19344
- const hasher = createHash14(algorithm).update(`blob ${size}\0`), stats = new GitTextStats();
19394
+ const hasher = createHash15(algorithm).update(`blob ${size}\0`), stats = new GitTextStats();
19345
19395
  const bytes = size <= WORKSPACE_DIFF_MAX_BLOB_BYTES ? Buffer.alloc(size) : null;
19346
19396
  const chunk = Buffer.alloc(64 * 1024);
19347
19397
  let offset = 0;
@@ -19381,7 +19431,7 @@ async function currentFile(root, path3, head, budget, signal, conversion, git3)
19381
19431
  let blob = rawBlob, cleanSize = size;
19382
19432
  if (normalize) {
19383
19433
  cleanSize -= stats.crlf;
19384
- const cleaned = createHash14(algorithm).update(`blob ${cleanSize}\0`), cleaner = new CRLFCleaner();
19434
+ const cleaned = createHash15(algorithm).update(`blob ${cleanSize}\0`), cleaner = new CRLFCleaner();
19385
19435
  if (bytes) cleaned.update(cleaner.push(bytes));
19386
19436
  else {
19387
19437
  budget.bytes += size;
@@ -19665,8 +19715,8 @@ async function readWorkspaceRevertPreview(command, entry, repoPath) {
19665
19715
  // src/coding-workspace/git.ts
19666
19716
  import { constants as constants9 } from "node:fs";
19667
19717
  import { lstat as lstat5, mkdtemp as mkdtemp3, open as open4, readFile as readFile6, realpath as realpath4, rm as rm4, unlink, writeFile as writeFile4 } from "node:fs/promises";
19668
- import { createHash as createHash15 } from "node:crypto";
19669
- import { join as join32, resolve as resolve16 } from "node:path";
19718
+ import { createHash as createHash16 } from "node:crypto";
19719
+ import { join as join33, resolve as resolve16 } from "node:path";
19670
19720
  import { tmpdir as tmpdir7 } from "node:os";
19671
19721
  import { execa as execa14 } from "execa";
19672
19722
 
@@ -19800,7 +19850,7 @@ function parseHistoryCursor(cursor, headSha2) {
19800
19850
  var historyCursor = (headSha2, offset) => `${headSha2}:${offset}`;
19801
19851
 
19802
19852
  // src/coding-workspace/git.ts
19803
- var digest8 = (value) => createHash15("sha256").update(value).digest("hex");
19853
+ var digest8 = (value) => createHash16("sha256").update(value).digest("hex");
19804
19854
  var oid4 = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/;
19805
19855
  var STATUS_BYTES = 8 * 1024 * 1024;
19806
19856
  var STATUS_SCAN_BYTES = 16 * 1024 * 1024;
@@ -20262,7 +20312,7 @@ function runGit(cwd, args, env, signal, maximum = 8 * 1024 * 1024) {
20262
20312
  }
20263
20313
  async function readTempFile(worktree, path3) {
20264
20314
  if (!visibleWorkspacePath(path3)) throw new CodingWorkspaceError("workspace_path_unavailable");
20265
- const full = join32(worktree, ...path3.split("/"));
20315
+ const full = join33(worktree, ...path3.split("/"));
20266
20316
  if (!full.startsWith(`${worktree}/`)) throw new CodingWorkspaceError("workspace_path_unavailable");
20267
20317
  try {
20268
20318
  const stat3 = await lstat5(full);
@@ -20283,8 +20333,8 @@ async function dryRunCheckpoint(git3, root, identity, statusBase, patchBase, pat
20283
20333
  } catch (error) {
20284
20334
  throw new CodingWorkspaceError("workspace_unsupported", { cause: error });
20285
20335
  }
20286
- const parent = await mkdtemp3(join32(tmpdir7(), "mikka-git-restore-"));
20287
- const worktree = join32(parent, "wt"), patchFile = join32(parent, "checkpoint.patch");
20336
+ const parent = await mkdtemp3(join33(tmpdir7(), "mikka-git-restore-"));
20337
+ const worktree = join33(parent, "wt"), patchFile = join33(parent, "checkpoint.patch");
20288
20338
  try {
20289
20339
  await writeFile4(patchFile, patch, { mode: 384 });
20290
20340
  await runGit(git3.commonDir, ["worktree", "add", "--detach", "--quiet", worktree, head], commonEnv(git3), signal);
@@ -20564,9 +20614,9 @@ async function handleWorkspaceGitRequest(command, entry, repoPath) {
20564
20614
  }
20565
20615
 
20566
20616
  // src/repositories.ts
20567
- import { createHash as createHash16, randomUUID as randomUUID7 } from "node:crypto";
20568
- import { existsSync as existsSync7, lstatSync as lstatSync12, mkdirSync as mkdirSync17, readdirSync as readdirSync9, realpathSync as realpathSync13, renameSync as renameSync5, rmSync as rmSync20 } from "node:fs";
20569
- import { dirname as dirname16, join as join33, resolve as resolve17 } from "node:path";
20617
+ import { createHash as createHash17, randomUUID as randomUUID7 } from "node:crypto";
20618
+ import { existsSync as existsSync8, lstatSync as lstatSync12, mkdirSync as mkdirSync17, readdirSync as readdirSync9, realpathSync as realpathSync13, renameSync as renameSync5, rmSync as rmSync20 } from "node:fs";
20619
+ import { dirname as dirname16, join as join34, resolve as resolve17 } from "node:path";
20570
20620
  import { setTimeout as delay } from "node:timers/promises";
20571
20621
  import { execa as execa15 } from "execa";
20572
20622
  import lockfile2 from "proper-lockfile";
@@ -20590,7 +20640,7 @@ var RepositoryCache = class {
20590
20640
  retainResources;
20591
20641
  pathFor(remoteUrl) {
20592
20642
  const { key: key2 } = normalizeRepository(remoteUrl, { allowFile: this.allowFile });
20593
- const path3 = resolve17(this.root, "v2", createHash16("sha256").update(key2).digest("hex"));
20643
+ const path3 = resolve17(this.root, "v2", createHash17("sha256").update(key2).digest("hex"));
20594
20644
  if (!isInside(resolve17(this.root), path3) || path3 === resolve17(this.root)) throw new Error("Invalid repository cache path");
20595
20645
  return path3;
20596
20646
  }
@@ -20626,7 +20676,7 @@ var RepositoryCache = class {
20626
20676
  return diagnostics.timer ? diagnostics.timer.measure(phase, traced) : traced();
20627
20677
  };
20628
20678
  let cloned = false;
20629
- if (!existsSync7(path3)) {
20679
+ if (!existsSync8(path3)) {
20630
20680
  const temporary = `${path3}.clone-${randomUUID7()}`;
20631
20681
  try {
20632
20682
  await git3(["clone", "--depth=50", "--no-single-branch", "--no-checkout", "--no-hardlinks", "--no-recurse-submodules", "--", remote, temporary]);
@@ -20638,7 +20688,7 @@ var RepositoryCache = class {
20638
20688
  } else {
20639
20689
  this.assertClone(path3);
20640
20690
  await git3(["remote", "set-url", "origin", remote], path3);
20641
- const depth = existsSync7(join33(path3, ".git", "shallow")) ? ["--depth=50"] : [];
20691
+ const depth = existsSync8(join34(path3, ".git", "shallow")) ? ["--depth=50"] : [];
20642
20692
  await git3(["fetch", ...depth, ...this.retainResources ? [] : ["--prune"], "--no-tags", "--no-recurse-submodules", "--no-write-fetch-head", "origin"], path3);
20643
20693
  }
20644
20694
  this.assertClone(path3);
@@ -20729,12 +20779,12 @@ var RepositoryCache = class {
20729
20779
  /** Cache paths for retention/orphan cleanup; never consult user checkouts. */
20730
20780
  paths() {
20731
20781
  const visit = (path3) => {
20732
- if (!existsSync7(path3) || lstatSync12(path3).isSymbolicLink()) return [];
20733
- if (existsSync7(join33(path3, ".git"))) {
20782
+ if (!existsSync8(path3) || lstatSync12(path3).isSymbolicLink()) return [];
20783
+ if (existsSync8(join34(path3, ".git"))) {
20734
20784
  this.assertClone(path3);
20735
20785
  return [path3];
20736
20786
  }
20737
- return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join33(path3, entry.name)) : []);
20787
+ return readdirSync9(path3, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() && !entry.name.endsWith(".lock") && !entry.name.includes(".clone-") ? visit(join34(path3, entry.name)) : []);
20738
20788
  };
20739
20789
  return visit(resolve17(this.root));
20740
20790
  }
@@ -20744,14 +20794,14 @@ var RepositoryCache = class {
20744
20794
  const root = realpathSync13(this.root);
20745
20795
  let current = resolve17(this.root);
20746
20796
  for (const part of path3.slice(current.length + 1).split("/").filter(Boolean)) {
20747
- current = join33(current, part);
20748
- if (existsSync7(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
20797
+ current = join34(current, part);
20798
+ if (existsSync8(current) && lstatSync12(current).isSymbolicLink()) throw new Error("Repository cache contains a symlink");
20749
20799
  mkdirSync17(current, { recursive: true, mode: 448 });
20750
20800
  if (!isInside(root, realpathSync13(current))) throw new Error("Repository cache escapes its directory");
20751
20801
  }
20752
20802
  }
20753
20803
  assertClone(path3) {
20754
- if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join33(path3, ".git")).isDirectory() || lstatSync12(join33(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
20804
+ if (lstatSync12(path3).isSymbolicLink() || !lstatSync12(join34(path3, ".git")).isDirectory() || lstatSync12(join34(path3, ".git")).isSymbolicLink()) throw new Error("Repository cache is not a standard clone");
20755
20805
  if (!isInside(realpathSync13(this.root), realpathSync13(path3))) throw new Error("Repository cache escapes its directory");
20756
20806
  }
20757
20807
  async lock(path3, signal) {
@@ -20856,12 +20906,12 @@ async function prepareRunRepository(repositories, privateDir, assignment, signal
20856
20906
  // src/subscription-hosted-runner.ts
20857
20907
  import { randomUUID as randomUUID8 } from "node:crypto";
20858
20908
  import { spawn as spawn5 } from "node:child_process";
20859
- import { existsSync as existsSync8, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
20860
- import { dirname as dirname17, join as join34, resolve as resolve18 } from "node:path";
20909
+ import { existsSync as existsSync9, mkdirSync as mkdirSync18, realpathSync as realpathSync14 } from "node:fs";
20910
+ import { dirname as dirname17, join as join35, resolve as resolve18 } from "node:path";
20861
20911
  import { fileURLToPath } from "node:url";
20862
20912
 
20863
20913
  // src/official-cli-timing.ts
20864
- import { createHash as createHash17, randomBytes as randomBytes4 } from "node:crypto";
20914
+ import { createHash as createHash18, randomBytes as randomBytes4 } from "node:crypto";
20865
20915
  import { createServer as createServer4 } from "node:http";
20866
20916
 
20867
20917
  // src/mcp-http-timing.ts
@@ -21185,7 +21235,7 @@ var OfficialCliTimingCollector = class {
21185
21235
  };
21186
21236
  async function startCliTimingCollector({ runId, harness, remoteMcpServerCount, decisionCatalogue }) {
21187
21237
  const collector = new OfficialCliTimingCollector(runId, harness);
21188
- const expectedCatalogueSha256 = decisionCatalogue ? createHash17("sha256").update(JSON.stringify(decisionCatalogue)).digest("hex") : null;
21238
+ const expectedCatalogueSha256 = decisionCatalogue ? createHash18("sha256").update(JSON.stringify(decisionCatalogue)).digest("hex") : null;
21189
21239
  const mcpCollector = new McpHttpTimingCollector(runId, harness, remoteMcpServerCount, Date.now, expectedCatalogueSha256);
21190
21240
  const path3 = `/v1/logs/${randomBytes4(16).toString("hex")}`;
21191
21241
  const mcpPath = `/v1/mcp-http/${randomBytes4(16).toString("hex")}`;
@@ -21492,7 +21542,7 @@ async function createHostedBotRunner(host) {
21492
21542
  });
21493
21543
  Object.assign(env, github.env);
21494
21544
  }
21495
- const ledger = join34(host.stateDir, "native-ledgers", assignment.runId + ".json");
21545
+ const ledger = join35(host.stateDir, "native-ledgers", assignment.runId + ".json");
21496
21546
  const scope = selected && subscription ? {
21497
21547
  runId: assignment.runId,
21498
21548
  bindingId: selected.bindingId,
@@ -21504,12 +21554,12 @@ async function createHostedBotRunner(host) {
21504
21554
  accountId: subscription.first.accountId,
21505
21555
  modelId: subscription.first.modelId
21506
21556
  } : void 0;
21507
- if (continuation && existsSync8(ledger)) throw unavailable5("ledger_mismatch");
21508
- const previousLedger = continuation ? join34(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
21557
+ if (continuation && existsSync9(ledger)) throw unavailable5("ledger_mismatch");
21558
+ const previousLedger = continuation ? join35(host.stateDir, "native-ledgers", continuation.runId + ".json") : ledger;
21509
21559
  const previous = scope ? readJson(previousLedger) : void 0;
21510
21560
  if (preparation && previous) throw unavailable5("ledger_mismatch");
21511
21561
  const expectedScope = scope && continuation ? { ...scope, runId: continuation.runId } : scope;
21512
- if (scope && (existsSync8(previousLedger) && (!previous || JSON.stringify(previous.scope) !== JSON.stringify(expectedScope) || typeof previous.sessionId !== "string") || assignment.requireSessionResume && (!previous || previous.sessionId !== assignment.resumeSessionId))) throw unavailable5("ledger_mismatch");
21562
+ if (scope && (existsSync9(previousLedger) && (!previous || JSON.stringify(previous.scope) !== JSON.stringify(expectedScope) || typeof previous.sessionId !== "string") || assignment.requireSessionResume && (!previous || previous.sessionId !== assignment.resumeSessionId))) throw unavailable5("ledger_mismatch");
21513
21563
  if (scope) mkdirSync18(dirname17(ledger), { recursive: true, mode: 448 });
21514
21564
  const record3 = async (sessionId) => {
21515
21565
  assertOpen();
@@ -21771,7 +21821,7 @@ async function createHostedBotRunner(host) {
21771
21821
  import {
21772
21822
  randomBytes as randomBytes5,
21773
21823
  randomUUID as randomUUID9,
21774
- createHash as createHash19,
21824
+ createHash as createHash20,
21775
21825
  timingSafeEqual as timingSafeEqual2
21776
21826
  } from "node:crypto";
21777
21827
  import { chmodSync as chmodSync2 } from "node:fs";
@@ -21781,7 +21831,7 @@ import { createServer as createServer5 } from "node:net";
21781
21831
  import { spawn as spawn6 } from "node:child_process";
21782
21832
  import { execFile as execFile8 } from "node:child_process";
21783
21833
  import { promisify as promisify8 } from "node:util";
21784
- import { createHash as createHash18 } from "node:crypto";
21834
+ import { createHash as createHash19 } from "node:crypto";
21785
21835
  import { readFile as readFile7, realpath as realpath5 } from "node:fs/promises";
21786
21836
  import { createInterface } from "node:readline";
21787
21837
  var exec3 = promisify8(execFile8);
@@ -21798,7 +21848,7 @@ async function detectComputerDriver(binary = "cua-driver") {
21798
21848
  installed: true,
21799
21849
  version,
21800
21850
  path: path3,
21801
- fingerprint: createHash18("sha256").update(await readFile7(path3)).digest("hex")
21851
+ fingerprint: createHash19("sha256").update(await readFile7(path3)).digest("hex")
21802
21852
  };
21803
21853
  } catch {
21804
21854
  return null;
@@ -21865,7 +21915,7 @@ async function executeDriver(driver, input, display, leaseGuard, assertLive = ()
21865
21915
  if (display !== void 0 && !/^:[1-9][0-9]{0,3}$/.test(display))
21866
21916
  throw new Error("Invalid desktop display");
21867
21917
  const call = normalizeCall(input);
21868
- const fingerprint2 = createHash18("sha256").update(await readFile7(driver.path)).digest("hex");
21918
+ const fingerprint2 = createHash19("sha256").update(await readFile7(driver.path)).digest("hex");
21869
21919
  if (fingerprint2 !== driver.fingerprint)
21870
21920
  throw new Error("Driver changed; restart and approve a new request");
21871
21921
  const args = driverArguments(call);
@@ -22160,7 +22210,7 @@ var ComputerBroker = class {
22160
22210
  call,
22161
22211
  expiresAt: this.now() + this.ttl
22162
22212
  };
22163
- const digest9 = createHash19("sha256").update(JSON.stringify(request2)).digest("hex");
22213
+ const digest9 = createHash20("sha256").update(JSON.stringify(request2)).digest("hex");
22164
22214
  return new Promise((resolve19, reject) => {
22165
22215
  const timer = setTimeout(() => {
22166
22216
  this.pending.delete(request2.id);
@@ -22277,10 +22327,10 @@ var ComputerBroker = class {
22277
22327
  };
22278
22328
 
22279
22329
  // src/computer/credential-executor.ts
22280
- import { createHash as createHash20 } from "node:crypto";
22330
+ import { createHash as createHash21 } from "node:crypto";
22281
22331
  function credentialAwareExecutor(deps) {
22282
22332
  return async (driver, call, display, runId, context) => {
22283
- const digest9 = createHash20("sha256").update(JSON.stringify(call)).digest("hex");
22333
+ const digest9 = createHash21("sha256").update(JSON.stringify(call)).digest("hex");
22284
22334
  const resolved = await deps.consumeMatchingIntent(runId, context.actionId, digest9);
22285
22335
  context.assertLive();
22286
22336
  if (resolved.kind === "ordinary") return deps.executeOrdinary(driver, call, display, runId, context.assertLive);
@@ -22562,7 +22612,7 @@ var Daemon = class {
22562
22612
  if (this.options.credential)
22563
22613
  this.saveDevice({ credential: this.options.credential });
22564
22614
  this.journal = new RunJournal(paths.journal);
22565
- this.captureUploader = new CaptureUploader((runId) => join35(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join35(paths.dataDir, "capture-pending"));
22615
+ this.captureUploader = new CaptureUploader((runId) => join36(runPaths(paths.adapterState, runId).runDir, CAPTURES_DIR), this.options.link, this.log, join36(paths.dataDir, "capture-pending"));
22566
22616
  this.outbox = new Outbox(
22567
22617
  paths.outbox,
22568
22618
  this.options.link,
@@ -22581,7 +22631,7 @@ var Daemon = class {
22581
22631
  if (this.localComputerDriver && this.options.link.syncComputerReviews) {
22582
22632
  this.localComputerBroker = new ComputerBroker({
22583
22633
  driver: this.localComputerDriver,
22584
- socketPath: join35(paths.dataDir, "local-computer.sock"),
22634
+ socketPath: join36(paths.dataDir, "local-computer.sock"),
22585
22635
  transport: "tcp",
22586
22636
  needsPerson: this.computerNeedsPerson(),
22587
22637
  permitted: (runId) => {
@@ -22624,7 +22674,7 @@ var Daemon = class {
22624
22674
  };
22625
22675
  this.cloudComputerBroker = new ComputerBroker({
22626
22676
  driver,
22627
- socketPath: join35(paths.dataDir, "computer.sock"),
22677
+ socketPath: join36(paths.dataDir, "computer.sock"),
22628
22678
  needsPerson: this.computerNeedsPerson(),
22629
22679
  permitted: (runId) => {
22630
22680
  const entry = this.journal.get(runId);
@@ -22719,7 +22769,7 @@ var Daemon = class {
22719
22769
  prepareRunDrive: this.options.link.prepareRunDrive?.bind(this.options.link),
22720
22770
  prepareRunToolApproval: this.options.link.prepareRunToolApproval?.bind(this.options.link),
22721
22771
  prepareRunGitHub: hosted ? void 0 : (assignment, signal, onCredential) => prepareLocalGitHub(assignment, {
22722
- stateDir: join35(this.paths.adapterState, "github"),
22772
+ stateDir: join36(this.paths.adapterState, "github"),
22723
22773
  link: this.options.link,
22724
22774
  signal,
22725
22775
  onCredential,
@@ -22789,7 +22839,7 @@ var Daemon = class {
22789
22839
  worktree,
22790
22840
  tree,
22791
22841
  github: { ...assignment.github, runToken: assignment.mcp?.token, issueId: assignment.issueId },
22792
- privateDir: join35(paths.adapterState, "pids"),
22842
+ privateDir: join36(paths.adapterState, "pids"),
22793
22843
  ...hosted ? { hosted: true } : {},
22794
22844
  env: hosted ? process.env : githubReceiptEnvironment(),
22795
22845
  githubEnvironment,
@@ -23504,11 +23554,11 @@ var Daemon = class {
23504
23554
  return runVerify(sandbox, {
23505
23555
  command,
23506
23556
  worktree: realpathSync15(worktree),
23507
- tmpRoot: join35(this.paths.adapterState, "verify", runId),
23557
+ tmpRoot: join36(this.paths.adapterState, "verify", runId),
23508
23558
  privateDir: paths.privateDir,
23509
23559
  pidFile: paths.pidFile.replace(/\.pgid$/, ".verify.pgid"),
23510
23560
  networkAllow: repo.networkAllow,
23511
- env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join35(paths.runDir, "handoff.json") },
23561
+ env: { ...buildChildEnv(), ...githubEnvironment, MIKKA_HANDOFF_FILE: join36(paths.runDir, "handoff.json") },
23512
23562
  timeoutMs,
23513
23563
  signal,
23514
23564
  readOnly
@@ -23583,7 +23633,7 @@ var Daemon = class {
23583
23633
  void this.stop().finally(() => this.options.onLockLost?.(error));
23584
23634
  }
23585
23635
  ensureSecret() {
23586
- if (existsSync9(this.paths.secret)) {
23636
+ if (existsSync10(this.paths.secret)) {
23587
23637
  return readFileSync15(this.paths.secret, "utf8").trim();
23588
23638
  }
23589
23639
  const secret = randomBytes6(32).toString("hex");
@@ -24063,7 +24113,7 @@ var Daemon = class {
24063
24113
  });
24064
24114
  }
24065
24115
  get updateStateFile() {
24066
- return join35(this.paths.dataDir, "auto-update.json");
24116
+ return join36(this.paths.dataDir, "auto-update.json");
24067
24117
  }
24068
24118
  /** A server named this release (a report answer, a commands read, a 426), or npm did for a refused daemon. */
24069
24119
  learnRelease(latest) {