@kitman-sh/cli 0.14.9 → 0.15.1

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.
Files changed (30) hide show
  1. package/dist/{chunk-cwdrhsvk.js → chunk-0ws25xvg.js} +2 -2
  2. package/dist/{chunk-czmbgsqr.js → chunk-2vxb3q01.js} +656 -39
  3. package/dist/{chunk-mgjer6c7.js → chunk-39ykbhq8.js} +3 -3
  4. package/dist/{chunk-vt8aqeby.js → chunk-3ns4sbfb.js} +1 -1
  5. package/dist/{chunk-c80dvhxf.js → chunk-5hkdgzh4.js} +1 -6
  6. package/dist/{chunk-0x5r7h2g.js → chunk-60fhzjx3.js} +1127 -109
  7. package/dist/{chunk-enmtmq63.js → chunk-69xka6ew.js} +1 -1
  8. package/dist/{chunk-vjt0d9zj.js → chunk-6h70kent.js} +7 -7
  9. package/dist/{chunk-qb9jft1r.js → chunk-8wpg3rph.js} +2 -2
  10. package/dist/{chunk-ftre6ndb.js → chunk-91tmbf95.js} +6 -6
  11. package/dist/chunk-csxxwscf.js +39 -0
  12. package/dist/chunk-d40233pm.js +3080 -0
  13. package/dist/{chunk-jsb61dsk.js → chunk-dv4v0tbn.js} +1815 -117
  14. package/dist/{chunk-wttgq85b.js → chunk-dx792s4w.js} +1396 -41
  15. package/dist/{chunk-dd7wknyk.js → chunk-f36s9s1g.js} +1512 -125
  16. package/dist/{chunk-y9x0yv20.js → chunk-fggwdr03.js} +461 -224
  17. package/dist/{chunk-93xj74qp.js → chunk-fzaecdgv.js} +3 -3
  18. package/dist/{chunk-2r4jy82z.js → chunk-k2wd9r6t.js} +4 -4
  19. package/dist/{chunk-h7qv6nzc.js → chunk-kskb0hkb.js} +7 -7
  20. package/dist/{chunk-6qygqj10.js → chunk-tgt9a3yz.js} +6 -6
  21. package/dist/{chunk-bmwf2ea5.js → chunk-vg78dz3w.js} +85 -26
  22. package/dist/{chunk-axr8avvs.js → chunk-wh4bpc4w.js} +4 -4
  23. package/dist/chunk-xrjt25ns.js +4345 -0
  24. package/dist/{chunk-e3c15bgw.js → chunk-xx711t5r.js} +4 -4
  25. package/dist/{chunk-b2yy07ag.js → chunk-ygx2pda7.js} +7 -7
  26. package/dist/{chunk-cpss81fx.js → chunk-zy4sv70r.js} +13 -5
  27. package/dist/index.js +4 -4
  28. package/package.json +2 -1
  29. package/dist/chunk-3hdjd2c3.js +0 -1192
  30. package/dist/chunk-qvyqfm54.js +0 -526
@@ -35,6 +35,7 @@ import {
35
35
  isResult,
36
36
  isFailure,
37
37
  isSuccess,
38
+ chunksOf,
38
39
  TaggedError,
39
40
  succeed3,
40
41
  void_2,
@@ -83,7 +84,7 @@ import {
83
84
  result,
84
85
  option2,
85
86
  exit,
86
- map8,
87
+ map9,
87
88
  as,
88
89
  asSome2,
89
90
  asVoid,
@@ -169,12 +170,7 @@ import {
169
170
  decodeJsonStringSync,
170
171
  encodeUnknownJsonStringSync,
171
172
  storable
172
- } from "./chunk-wttgq85b.js";
173
- import {
174
- Id,
175
- secretReference,
176
- secretPlaceholder
177
- } from "./chunk-c80dvhxf.js";
173
+ } from "./chunk-dx792s4w.js";
178
174
  import {
179
175
  currentTimeMillis,
180
176
  SecureRandom,
@@ -205,7 +201,13 @@ import {
205
201
  testOutcomes,
206
202
  checkTests,
207
203
  reportedModelName,
204
+ calverNumbers,
205
+ compareCalver,
208
206
  MeasureSample,
207
+ compareCommitMax,
208
+ commitMessageMax,
209
+ commandTimeoutMillisDefault,
210
+ commandTextLimit,
209
211
  catchUpPathLimit,
210
212
  createId,
211
213
  digestSha256,
@@ -255,7 +257,7 @@ import {
255
257
  checkServicesFile,
256
258
  checkServices,
257
259
  serviceChecks
258
- } from "./chunk-dd7wknyk.js";
260
+ } from "./chunk-f36s9s1g.js";
259
261
  import {
260
262
  join,
261
263
  interrupt,
@@ -270,6 +272,7 @@ import {
270
272
  map2,
271
273
  filter,
272
274
  take2,
275
+ mapAccum,
273
276
  decodeText,
274
277
  encodeText,
275
278
  splitLines,
@@ -300,7 +303,7 @@ import {
300
303
  writeSrtSettings2,
301
304
  srtStepArgv2,
302
305
  srtArgv2
303
- } from "./chunk-bmwf2ea5.js";
306
+ } from "./chunk-vg78dz3w.js";
304
307
  import {
305
308
  writeAgentEnvironmentConfigFile2,
306
309
  readManifestSkillPaths2,
@@ -316,8 +319,8 @@ import {
316
319
  applyAgentEnvironmentMaterialization2,
317
320
  isPathWithin2,
318
321
  skillIdentity2
319
- } from "./chunk-b2yy07ag.js";
320
- import"./chunk-h7qv6nzc.js";
322
+ } from "./chunk-ygx2pda7.js";
323
+ import"./chunk-kskb0hkb.js";
321
324
  import {
322
325
  egressAllowed,
323
326
  writeSecretRegistry,
@@ -327,7 +330,7 @@ import {
327
330
  secretFilter2,
328
331
  opaqueTunnelRefusal2,
329
332
  isOpaqueConnectReason2
330
- } from "./chunk-cwdrhsvk.js";
333
+ } from "./chunk-0ws25xvg.js";
331
334
  import {
332
335
  sliceBytes2,
333
336
  maxLineBytes2,
@@ -335,23 +338,29 @@ import {
335
338
  decodedOption2,
336
339
  decoded2,
337
340
  readOpencode2
338
- } from "./chunk-mgjer6c7.js";
341
+ } from "./chunk-39ykbhq8.js";
339
342
  import {
340
343
  uploadRunFile,
341
344
  programLease,
342
345
  rpcRunFiles,
343
346
  programHostsEnv,
344
347
  undeclaredHostsEnv
345
- } from "./chunk-3hdjd2c3.js";
346
- import"./chunk-cpss81fx.js";
348
+ } from "./chunk-d40233pm.js";
349
+ import"./chunk-zy4sv70r.js";
347
350
  import {
348
351
  nextInt
349
- } from "./chunk-vt8aqeby.js";
352
+ } from "./chunk-3ns4sbfb.js";
353
+ import"./chunk-csxxwscf.js";
350
354
  import {
351
355
  ChildProcessSpawner,
352
356
  make3
353
- } from "./chunk-2r4jy82z.js";
354
- import"./chunk-ftre6ndb.js";
357
+ } from "./chunk-k2wd9r6t.js";
358
+ import"./chunk-91tmbf95.js";
359
+ import {
360
+ Id,
361
+ secretReference,
362
+ secretPlaceholder
363
+ } from "./chunk-5hkdgzh4.js";
355
364
 
356
365
  // packages/core/src/sync-kit.ts
357
366
  import { createHash } from "crypto";
@@ -972,7 +981,7 @@ var resolvePackagePlugins = (input, plan) => gen(function* () {
972
981
  const source = packageSource(plugin);
973
982
  if (source === undefined || source.version !== undefined && input.versions !== "latest")
974
983
  return succeed6([plugin]);
975
- return resolver.npmLatest(source.packageName).pipe(map8((version) => [
984
+ return resolver.npmLatest(source.packageName).pipe(map9((version) => [
976
985
  {
977
986
  ...plugin,
978
987
  item: {
@@ -2423,7 +2432,7 @@ var openCodeStore = (source) => gen(function* () {
2423
2432
  var runOpenCode = (binary, store, args) => runCommand2(binary, [...args, "--standalone"], { env: store.env, timeout: "30 seconds" });
2424
2433
  var readOpenCodeLogin = (binary, source) => gen(function* () {
2425
2434
  const store = yield* openCodeStore(source);
2426
- const exported = store === undefined ? none() : yield* runOpenCode(binary, store, ["auth", "export"]).pipe(map8(decodeExport), orElseSucceed(() => none()));
2435
+ const exported = store === undefined ? none() : yield* runOpenCode(binary, store, ["auth", "export"]).pipe(map9(decodeExport), orElseSucceed(() => none()));
2427
2436
  if (isNone(exported)) {
2428
2437
  const credentials = yield* fileCredentials(source);
2429
2438
  return credentials === undefined ? undefined : { credentials };
@@ -2470,17 +2479,17 @@ var renewers = {
2470
2479
  grant_type: "refresh_token",
2471
2480
  refresh_token: login.refresh,
2472
2481
  client_id: "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
2473
- }))).pipe(map8(refreshed(now))),
2482
+ }))).pipe(map9(refreshed(now))),
2474
2483
  openai: (login, now) => answer("openai", TokenAnswer, post("https://auth.openai.com/oauth/token").pipe(bodyUrlParams({
2475
2484
  grant_type: "refresh_token",
2476
2485
  refresh_token: login.refresh,
2477
2486
  client_id: "app_EMoamEEZ73f0CkXaXp7hrann"
2478
- }))).pipe(map8(refreshed(now))),
2487
+ }))).pipe(map9(refreshed(now))),
2479
2488
  xai: (login, now) => answer("xai", XaiAnswer, post("https://auth.x.ai/oauth2/token").pipe(acceptJson, bodyUrlParams({
2480
2489
  grant_type: "refresh_token",
2481
2490
  refresh_token: login.refresh,
2482
2491
  client_id: "b1a00492-073a-47ea-816f-4c329264a828"
2483
- }))).pipe(map8((answered) => ({
2492
+ }))).pipe(map9((answered) => ({
2484
2493
  access: answered.access_token,
2485
2494
  ...answered.refresh_token === undefined ? undefined : { refresh: answered.refresh_token },
2486
2495
  expires: xaiExpiry(answered, now)
@@ -2489,8 +2498,8 @@ var renewers = {
2489
2498
  grant_type: "refresh_token",
2490
2499
  refresh_token: login.refresh,
2491
2500
  client_id: "opencode-cli"
2492
- }))).pipe(map8(refreshed(now))),
2493
- "github-copilot": (login) => answer("github-copilot", CopilotAnswer, get("https://api.github.com/copilot_internal/v2/token").pipe(setHeaders({ authorization: `Bearer ${login.refresh}`, accept: "application/json" }))).pipe(map8((answered) => ({ access: answered.token, expires: answered.expires_at * 1000 })))
2501
+ }))).pipe(map9(refreshed(now))),
2502
+ "github-copilot": (login) => answer("github-copilot", CopilotAnswer, get("https://api.github.com/copilot_internal/v2/token").pipe(setHeaders({ authorization: `Bearer ${login.refresh}`, accept: "application/json" }))).pipe(map9((answered) => ({ access: answered.token, expires: answered.expires_at * 1000 })))
2494
2503
  };
2495
2504
  var renewerFor = (provider) => isKeyOf(renewers, provider) ? renewers[provider] : undefined;
2496
2505
  var renewableLogin = (provider, credential) => getOrUndefined(filter2(decodeRenewable(credential), (login) => renewerFor(provider) !== undefined && (provider !== "github-copilot" || login.access !== login.refresh)));
@@ -2555,7 +2564,7 @@ var filesUnder = (root) => gen(function* () {
2555
2564
  if (skipped.has(entry))
2556
2565
  continue;
2557
2566
  const path = relative === "" ? entry : `${relative}/${entry}`;
2558
- const type = yield* fs.stat(`${root}/${path}`).pipe(map8((info) => info.type), orElseSucceed(() => {
2567
+ const type = yield* fs.stat(`${root}/${path}`).pipe(map9((info) => info.type), orElseSucceed(() => {
2559
2568
  return;
2560
2569
  }));
2561
2570
  if (type === "Directory")
@@ -2571,7 +2580,7 @@ var dependenciesOf = (root, files) => gen(function* () {
2571
2580
  const fs = yield* FileSystem;
2572
2581
  const names = new Set;
2573
2582
  for (const file of files.filter((path) => path === "package.json" || path.endsWith("/package.json"))) {
2574
- const manifest = yield* fs.readFileString(`${root}/${file}`).pipe(map8((text) => decodeJsonStringSync(text)), orElseSucceed(() => {
2583
+ const manifest = yield* fs.readFileString(`${root}/${file}`).pipe(map9((text) => decodeJsonStringSync(text)), orElseSucceed(() => {
2575
2584
  return;
2576
2585
  }));
2577
2586
  if (!isJsonObject(manifest))
@@ -2744,7 +2753,7 @@ var credentialsIn = (source) => gen(function* () {
2744
2753
  const credentials = getOrUndefined(decodeJsonStringOption(text));
2745
2754
  return isJsonObject(credentials) ? credentials : undefined;
2746
2755
  });
2747
- var loginCredentials = (login) => login.format === "opencode" ? map8(readOpenCodeLogin(login.binary, login.source), (read) => read?.credentials) : credentialsIn(login.source);
2756
+ var loginCredentials = (login) => login.format === "opencode" ? map9(readOpenCodeLogin(login.binary, login.source), (read) => read?.credentials) : credentialsIn(login.source);
2748
2757
  var neverExpires = 253402300799000;
2749
2758
  var isOAuth = (credential) => isJsonObject(credential) && credential.type === "oauth";
2750
2759
  var claudeOAuth = "claudeAiOauth";
@@ -2912,7 +2921,7 @@ var refreshOperatorLogin = (login, expired, http) => gen(function* () {
2912
2921
  }
2913
2922
  }
2914
2923
  });
2915
- var stepLogin = (login, reference) => map8(loginCredentials(login), (credentials) => {
2924
+ var stepLogin = (login, reference) => map9(loginCredentials(login), (credentials) => {
2916
2925
  if (credentials === undefined)
2917
2926
  return;
2918
2927
  const format = loginFormats[login.format];
@@ -2991,7 +3000,7 @@ var loginHostsWithProviders = (operatorFiles) => gen(function* () {
2991
3000
  };
2992
3001
  return { ...login, hosts };
2993
3002
  });
2994
- var carriedLoginHosts = (launch) => launch.renewedLogin?.format === "opencode" ? map8(loginCredentials(launch.renewedLogin), openCodeConsoleHosts) : succeed6([]);
3003
+ var carriedLoginHosts = (launch) => launch.renewedLogin?.format === "opencode" ? map9(loginCredentials(launch.renewedLogin), openCodeConsoleHosts) : succeed6([]);
2995
3004
  var carriedProviderHosts = (launch) => gen(function* () {
2996
3005
  const providers = launch.operatorFiles?.providers;
2997
3006
  if (providers === undefined)
@@ -3152,7 +3161,7 @@ var decodeSetupArchive = decodeEffect(fromJsonString(SetupArchive));
3152
3161
  var runsOnHost = (command) => gen(function* () {
3153
3162
  const fs = yield* FileSystem;
3154
3163
  const path = yield* Path;
3155
- const executable = (file) => fs.stat(file).pipe(map8((info) => info.type === "File" && (info.mode & 73) !== 0), orElseSucceed(() => false));
3164
+ const executable = (file) => fs.stat(file).pipe(map9((info) => info.type === "File" && (info.mode & 73) !== 0), orElseSucceed(() => false));
3156
3165
  if (command.includes("/"))
3157
3166
  return yield* executable(command);
3158
3167
  for (const directory of ((yield* optionalEnv("PATH")) ?? "").split(":"))
@@ -3180,7 +3189,7 @@ var stepKitSetup = (agent, harness) => gen(function* () {
3180
3189
  const fetch = agent.setupArchive;
3181
3190
  if (fetch === undefined)
3182
3191
  return unavailable("this Runner fetches no setup archives");
3183
- const setups = yield* forEach(kits, (kit) => fetch(kit.setupDigest).pipe(flatMap3(decodeSetupArchive), map8((archive) => ({ name: kit.name, version: kit.version, archive })))).pipe(result);
3192
+ const setups = yield* forEach(kits, (kit) => fetch(kit.setupDigest).pipe(flatMap3(decodeSetupArchive), map9((archive) => ({ name: kit.name, version: kit.version, archive })))).pipe(result);
3184
3193
  if (isFailure(setups))
3185
3194
  return unavailable(setups.failure.message);
3186
3195
  const setup = materializeKitSetup(harness, [...setups.success, kitmanSkillEntry], agent.brief.listedSkills ?? []);
@@ -3210,7 +3219,7 @@ var Proto = {
3210
3219
  };
3211
3220
  }
3212
3221
  };
3213
- var make = (value) => map8(unbounded({
3222
+ var make = (value) => map9(unbounded({
3214
3223
  replay: 1
3215
3224
  }), (pubsub) => {
3216
3225
  const self = Object.create(Proto);
@@ -3281,7 +3290,7 @@ var projectOf = (config, workspace) => {
3281
3290
  const project = isJsonObject(projects[workspace]) ? projects[workspace] : {};
3282
3291
  return { projects, project };
3283
3292
  };
3284
- var isTrusted = (file, workspace) => map8(readConfig(file), (config) => isSome(config) && isSettled(config.value, workspace));
3293
+ var isTrusted = (file, workspace) => map9(readConfig(file), (config) => isSome(config) && isSettled(config.value, workspace));
3285
3294
  var holdConfigLock = (file) => gen(function* () {
3286
3295
  const fs = yield* FileSystem;
3287
3296
  const lock = `${file}.lock`;
@@ -3481,7 +3490,7 @@ class ContainerError extends TaggedError("ContainerError") {
3481
3490
  class SecretProxyUnreachable extends TaggedError("SecretProxyUnreachable") {
3482
3491
  }
3483
3492
  var imagePull = { timeout: "30 minutes" };
3484
- var dockerContainerRunner = map8(ChildProcessSpawner, (spawner) => {
3493
+ var dockerContainerRunner = map9(ChildProcessSpawner, (spawner) => {
3485
3494
  const docker = (args, options = {}) => runCommand2("docker", args, options).pipe(mapError2((error) => new ContainerError({ message: error.message })), provideService(ChildProcessSpawner, spawner));
3486
3495
  const labelArgs = (labels) => labels.flatMap(([key, value]) => ["--label", `${key}=${value}`]);
3487
3496
  const ids = (output) => output.split(`
@@ -3775,19 +3784,19 @@ var openSession = (file) => gen(function* () {
3775
3784
  }
3776
3785
  return { handle, size: Number(opened.size) };
3777
3786
  });
3778
- var readAt = (handle, position, length) => map8(tryPromise(() => handle.read(new Uint8Array(length), 0, length, position)), ({ buffer, bytesRead }) => buffer.subarray(0, bytesRead));
3787
+ var readAt = (handle, position, length) => map9(tryPromise(() => handle.read(new Uint8Array(length), 0, length, position)), ({ buffer, bytesRead }) => buffer.subarray(0, bytesRead));
3779
3788
  var readSessionRange = (file, position, length) => gen(function* () {
3780
3789
  const { handle, size } = yield* openSession(file);
3781
3790
  return yield* readAt(handle, position, Math.max(0, Math.min(length, size - position)));
3782
3791
  }).pipe(scoped);
3783
- var sessionFileSize = (file) => map8(openSession(file), ({ size }) => size).pipe(scoped);
3792
+ var sessionFileSize = (file) => map9(openSession(file), ({ size }) => size).pipe(scoped);
3784
3793
  var maxSubagentFiles = 1024;
3785
3794
  var subagentFiles = (file) => gen(function* () {
3786
3795
  const fs = yield* FileSystem;
3787
3796
  if (file.subagents === undefined)
3788
3797
  return [];
3789
3798
  const found = yield* sessionFiles(file.subagents, 0, file.confinedTo);
3790
- return yield* forEach(found.slice(0, maxSubagentFiles), (path) => fs.stat(path).pipe(map8((info) => {
3799
+ return yield* forEach(found.slice(0, maxSubagentFiles), (path) => fs.stat(path).pipe(map9((info) => {
3791
3800
  const modifiedAt = getOrUndefined(info.mtime)?.getTime();
3792
3801
  return { path, size: Number(info.size), ...modifiedAt === undefined ? undefined : { modifiedAt } };
3793
3802
  }), orElseSucceed(() => ({ path, size: 0 }))));
@@ -3821,7 +3830,7 @@ var packConfined = (file, root) => gen(function* () {
3821
3830
  }
3822
3831
  return packed;
3823
3832
  }).pipe(scoped);
3824
- var packSession = (file) => file.confinedTo === undefined ? flatMap3(FileSystem, (fs) => fs.readFile(file.path)).pipe(flatMap3((content) => tryPromise(() => gzipped(content))), map8((content) => new Uint8Array(content))) : packConfined(file, file.confinedTo);
3833
+ var packSession = (file) => file.confinedTo === undefined ? flatMap3(FileSystem, (fs) => fs.readFile(file.path)).pipe(flatMap3((content) => tryPromise(() => gzipped(content))), map9((content) => new Uint8Array(content))) : packConfined(file, file.confinedTo);
3825
3834
  var restoreSession = (adapter, place) => gen(function* () {
3826
3835
  const fs = yield* FileSystem;
3827
3836
  const location = adapter.session?.location;
@@ -3941,16 +3950,16 @@ var stepProcessEnvironment = (runnerId, attemptId, outer = process.env) => ({
3941
3950
  var lists = (value, id) => value.split(listSeparator).includes(id);
3942
3951
  var signalProcess = (pid, signal) => ignore(try_2(() => process.kill(pid, signal)));
3943
3952
  var signalled = (pid) => try_2(() => process.kill(pid, 0)).pipe(as(true), catch_((error) => succeed6(hasProperty(error.cause, "code") && error.cause.code === "EPERM")));
3944
- var procCommand = (fs, pid) => map8(fs.readFile(`/proc/${pid}/cmdline`).pipe(orElseSucceed(() => new Uint8Array)), commandLine);
3945
- var procProcessTable = map8(FileSystem, (fs) => ({
3953
+ var procCommand = (fs, pid) => map9(fs.readFile(`/proc/${pid}/cmdline`).pipe(orElseSucceed(() => new Uint8Array)), commandLine);
3954
+ var procProcessTable = map9(FileSystem, (fs) => ({
3946
3955
  marked: ({ name, value }) => gen(function* () {
3947
3956
  const prefix = `${name}=`;
3948
3957
  const pids = (yield* fs.readDirectory("/proc").pipe(orElseSucceed(() => []))).filter((pid) => /^\d+$/.test(pid));
3949
- const found = yield* forEach(pids, (pid) => fs.readFile(`/proc/${pid}/environ`).pipe(flatMap3((environ) => environEntries(environ).some((entry) => entry.startsWith(prefix) && lists(entry.slice(prefix.length), value)) ? map8(procCommand(fs, Number(pid)), (command) => [{ pid: Number(pid), command }]) : succeed6([])), orElseSucceed(() => [])), { concurrency: 16 });
3958
+ const found = yield* forEach(pids, (pid) => fs.readFile(`/proc/${pid}/environ`).pipe(flatMap3((environ) => environEntries(environ).some((entry) => entry.startsWith(prefix) && lists(entry.slice(prefix.length), value)) ? map9(procCommand(fs, Number(pid)), (command) => [{ pid: Number(pid), command }]) : succeed6([])), orElseSucceed(() => [])), { concurrency: 16 });
3950
3959
  return found.flat();
3951
3960
  }),
3952
3961
  signal: signalProcess,
3953
- alive: (pid) => fs.readFileString(`/proc/${pid}/stat`).pipe(map8((stat) => !/^[ZX]/.test(stat.slice(stat.lastIndexOf(")") + 2))), orElseSucceed(() => false))
3962
+ alive: (pid) => fs.readFileString(`/proc/${pid}/stat`).pipe(map9((stat) => !/^[ZX]/.test(stat.slice(stat.lastIndexOf(")") + 2))), orElseSucceed(() => false))
3954
3963
  }));
3955
3964
  var environEntries = (environ) => new TextDecoder().decode(environ).split("\x00");
3956
3965
  var commandLine = (cmdline) => new TextDecoder().decode(cmdline).split("\x00").filter((part) => part !== "").join(" ");
@@ -3959,10 +3968,10 @@ var psRows = (listed) => listed.split(`
3959
3968
  const matched = /^\s*(\d+)\s+(.*)$/.exec(line);
3960
3969
  return matched === null ? [] : [{ pid: Number(matched[1]), text: matched[2] ?? "" }];
3961
3970
  });
3962
- var psProcessTable = map8(ChildProcessSpawner, (spawner) => {
3971
+ var psProcessTable = map9(ChildProcessSpawner, (spawner) => {
3963
3972
  const ps = (args) => runCommand2("ps", [...args, "-ww", "-U", String(process.getuid?.() ?? ""), "-o", "pid=,command="], {
3964
3973
  timeout: "30 seconds"
3965
- }).pipe(provideService(ChildProcessSpawner, spawner), map8(psRows));
3974
+ }).pipe(provideService(ChildProcessSpawner, spawner), map9(psRows));
3966
3975
  return {
3967
3976
  marked: ({ name, value }) => gen(function* () {
3968
3977
  const entry = ` ${name}=`;
@@ -3988,7 +3997,7 @@ var psProcessTable = map8(ChildProcessSpawner, (spawner) => {
3988
3997
  var systemProcessTable = process.platform === "linux" ? procProcessTable : psProcessTable;
3989
3998
  var unitPart = (id) => id.replaceAll(/[^A-Za-z0-9-]/g, (char) => `_${char.charCodeAt(0).toString(16)}`);
3990
3999
  var unitPrefix = (runnerId, attemptId) => `kitman-step-${unitPart(runnerId)}.${attemptId === undefined ? "" : `${unitPart(attemptId)}.`}`;
3991
- var unitSuffix = SecureRandom.pipe(flatMap3((random) => random.uuidV4()), map8((uuid) => uuid.slice(0, 8)), provide3(layerWebCrypto));
4000
+ var unitSuffix = SecureRandom.pipe(flatMap3((random) => random.uuidV4()), map9((uuid) => uuid.slice(0, 8)), provide3(layerWebCrypto));
3992
4001
  var busVariables = ["XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS"];
3993
4002
  var systemdScopes = gen(function* () {
3994
4003
  if (process.platform !== "linux")
@@ -4008,7 +4017,7 @@ var systemdScopes = gen(function* () {
4008
4017
  `).filter((pid) => /^\d+$/.test(pid))).map(Number);
4009
4018
  });
4010
4019
  return {
4011
- contain: (runnerId, attemptId, argv) => map8(unitSuffix, (suffix) => {
4020
+ contain: (runnerId, attemptId, argv) => map9(unitSuffix, (suffix) => {
4012
4021
  const unit = `${unitPrefix(runnerId, attemptId)}${suffix}.scope`;
4013
4022
  const scoped = [
4014
4023
  "systemd-run",
@@ -4035,7 +4044,7 @@ var systemdScopes = gen(function* () {
4035
4044
  ])).split(`
4036
4045
  `).flatMap((line) => line.trim().split(/\s+/)[0] ?? []).filter((unit) => unit.endsWith(".scope"));
4037
4046
  const pids = yield* forEach(units, (unit) => flatMap3(systemd("systemctl", ["--user", "show", "--property=ControlGroup", "--value", unit]), (cgroup) => cgroup.trim() === "" ? succeed6([]) : cgroupProcesses(cgroup.trim())));
4038
- return yield* forEach([...new Set(pids.flat())], (pid) => map8(procCommand(fs, pid), (command) => ({ pid, command })));
4047
+ return yield* forEach([...new Set(pids.flat())], (pid) => map9(procCommand(fs, pid), (command) => ({ pid, command })));
4039
4048
  }).pipe(orElseSucceed(() => []))
4040
4049
  };
4041
4050
  });
@@ -4045,7 +4054,7 @@ var makeStepProcesses = (table, options = {}) => {
4045
4054
  const { scopes } = options;
4046
4055
  const unreaped = new Map;
4047
4056
  const pollMs = options.pollMs ?? 50;
4048
- const finding = (marker, scoped) => map8(all3([table.marked(marker), scoped]), ([marked, inScopes]) => {
4057
+ const finding = (marker, scoped) => map9(all3([table.marked(marker), scoped]), ([marked, inScopes]) => {
4049
4058
  const found = new Map([...marked, ...inScopes].map((candidate) => [candidate.pid, candidate]));
4050
4059
  found.delete(process.pid);
4051
4060
  return [...found.values()];
@@ -4133,7 +4142,7 @@ var stepProcessesUncontained = (input) => {
4133
4142
 
4134
4143
  class StepProcesses extends Service2()("StepProcesses") {
4135
4144
  }
4136
- var stepProcessesLayer = effect(StepProcesses, map8(systemProcessTable, (table) => makeStepProcesses(table)));
4145
+ var stepProcessesLayer = effect(StepProcesses, map9(systemProcessTable, (table) => makeStepProcesses(table)));
4137
4146
  var systemStepProcessesLayer = effect(StepProcesses, gen(function* () {
4138
4147
  const table = yield* systemProcessTable;
4139
4148
  return makeStepProcesses(table, { scopes: yield* systemdScopes });
@@ -4244,9 +4253,9 @@ var lastingStop = (input) => gen(function* () {
4244
4253
  const watch = gen(function* () {
4245
4254
  while (true) {
4246
4255
  const stopped = yield* raceAllFirst([
4247
- map8(until(input.seen, (last) => last.end !== undefined || last.turn > input.promptTurn && !["blocked", "working", "error"].includes(last.status ?? "")), (seen) => signalled2(seen.end === undefined ? "turn_ended" : "terminal_ended")(seen)),
4248
- map8(lastingStatus(input.seen, "blocked", input.blockedGraceMs), signalled2("blocked")),
4249
- map8(lastingStatus(input.seen, "error", input.idleGraceMs), signalled2("error"))
4256
+ map9(until(input.seen, (last) => last.end !== undefined || last.turn > input.promptTurn && !["blocked", "working", "error"].includes(last.status ?? "")), (seen) => signalled2(seen.end === undefined ? "turn_ended" : "terminal_ended")(seen)),
4257
+ map9(lastingStatus(input.seen, "blocked", input.blockedGraceMs), signalled2("blocked")),
4258
+ map9(lastingStatus(input.seen, "error", input.idleGraceMs), signalled2("error"))
4250
4259
  ]);
4251
4260
  if (stopped.signal !== "turn_ended" || (yield* input.outputSubmitted))
4252
4261
  return stopped;
@@ -4455,7 +4464,7 @@ var runAttempt = (request, options) => gen(function* () {
4455
4464
  env: {},
4456
4465
  command: ["sh", "-c", 'p=$(command -v -- "$1") && [ -f "$p" ] && [ -x "$p" ]', "sh", command],
4457
4466
  timeout: "30 seconds"
4458
- }).pipe(map8((result) => result.exitCode === 0), mapError2(() => unavailable)));
4467
+ }).pipe(map9((result) => result.exitCode === 0), mapError2(() => unavailable)));
4459
4468
  const env = { ...policy.environment, ...marker };
4460
4469
  return { argv: dockerExecArgv({ container, workspace, env, argv: harnessArgv }), env, registry };
4461
4470
  }
@@ -4516,7 +4525,7 @@ var runAttempt = (request, options) => gen(function* () {
4516
4525
  });
4517
4526
  let accepted = false;
4518
4527
  const outputSubmitted = suspend3(() => accepted ? succeed6(true) : request.settled.pipe(orElseSucceed(() => false), tap2((settled) => sync2(() => accepted ||= settled))));
4519
- const readScreen = map8(option2(call((connection) => connection.read(address))), (screen) => isSome(screen) ? redactCredentials(screen.value).trim() : "");
4528
+ const readScreen = map9(option2(call((connection) => connection.read(address))), (screen) => isSome(screen) ? redactCredentials(screen.value).trim() : "");
4520
4529
  const judge = (last) => gen(function* () {
4521
4530
  if (yield* outputSubmitted)
4522
4531
  return { status: "settled" };
@@ -4560,7 +4569,7 @@ var runAttempt = (request, options) => gen(function* () {
4560
4569
  const brief = firstMessage(request.launch, workspace, launch.systemBrief === true);
4561
4570
  const readyTurn = ready.value.turn;
4562
4571
  const deliver = (tries) => gen(function* () {
4563
- const sent = yield* result(call((connection) => map8(connection.send(address, brief), (reply) => ({ turn: reply.turn, lost: false })), () => succeed6({ turn: readyTurn, lost: true })));
4572
+ const sent = yield* result(call((connection) => map9(connection.send(address, brief), (reply) => ({ turn: reply.turn, lost: false })), () => succeed6({ turn: readyTurn, lost: true })));
4564
4573
  if (isFailure(sent) || sent.success.lost || tries <= 1)
4565
4574
  return sent;
4566
4575
  const taken = yield* until(seen, stirredSince(sent.success.turn)).pipe(timeoutOption(options.briefAckMs));
@@ -4650,7 +4659,7 @@ var herdrCoreAgentBackendLayer = (options) => effect(AgentBackend, gen(function*
4650
4659
  });
4651
4660
  }));
4652
4661
  // packages/agent-runtime/src/sandbox-host.ts
4653
- var installed = (probe, command, label) => map8(probe("sh", ["-c", `command -v ${command}`]), (found) => found ? [] : [`${label} is not installed`]);
4662
+ var installed = (probe, command, label) => map9(probe("sh", ["-c", `command -v ${command}`]), (found) => found ? [] : [`${label} is not installed`]);
4654
4663
  var srtMissing = (probe, platform) => gen(function* () {
4655
4664
  if (platform === "darwin")
4656
4665
  return [
@@ -4672,7 +4681,7 @@ var srtMissing = (probe, platform) => gen(function* () {
4672
4681
  "unprivileged user namespaces are not allowed (on Ubuntu: sysctl kernel.apparmor_restrict_unprivileged_userns=0)"
4673
4682
  ];
4674
4683
  });
4675
- var dockerMissing = (probe, image) => map8(probe("docker", ["info"]), (reachable) => [
4684
+ var dockerMissing = (probe, image) => map9(probe("docker", ["info"]), (reachable) => [
4676
4685
  ...reachable ? [] : ["the docker daemon is not reachable"],
4677
4686
  ...image === undefined ? ["its settings name no Docker image"] : /@sha256:[a-f0-9]{64}$/.test(image) ? [] : ["its Docker image is not pinned by digest (image@sha256:...)"]
4678
4687
  ]);
@@ -4691,7 +4700,7 @@ var probeSandboxHost = (probe, platform = process.platform, options = {}) => gen
4691
4700
  ]
4692
4701
  };
4693
4702
  });
4694
- var commandHostProbe = map8(ChildProcessSpawner, (spawner) => (command, args) => runCommand2(command, args, { timeout: "10 seconds" }).pipe(as(true), orElseSucceed(() => false), provideService(ChildProcessSpawner, spawner)));
4703
+ var commandHostProbe = map9(ChildProcessSpawner, (spawner) => (command, args) => runCommand2(command, args, { timeout: "10 seconds" }).pipe(as(true), orElseSucceed(() => false), provideService(ChildProcessSpawner, spawner)));
4695
4704
  // packages/oversight/src/domain/intent.ts
4696
4705
  var ConstraintKind = Literals(["rule", "semantic"]);
4697
4706
  var ConstraintSeverity = Literals(["block", "warn"]);
@@ -4869,14 +4878,14 @@ var diffFlags = ["--no-color", "--no-ext-diff", "--no-textconv", "--no-renames",
4869
4878
  var catchUpReport = (worktree, input) => gen(function* () {
4870
4879
  const git = (...args) => runCommand2("git", ["-C", worktree, ...args]);
4871
4880
  const target = `origin/${input.target}`;
4872
- const names = (from, to) => map8(git("diff", "--name-only", "-z", "--no-renames", from, to), (out) => out.split("\x00").filter(Boolean));
4873
- const ownDiff = (base, head, path) => map8(git("diff", ...diffFlags, base, head, "--", `:(literal,top)${path}`), normalizedDiff);
4881
+ const names = (from, to) => map9(git("diff", "--name-only", "-z", "--no-renames", from, to), (out) => out.split("\x00").filter(Boolean));
4882
+ const ownDiff = (base, head, path) => map9(git("diff", ...diffFlags, base, head, "--", `:(literal,top)${path}`), normalizedDiff);
4874
4883
  const before = (yield* git("merge-base", input.from, target)).trim();
4875
4884
  const after = (yield* git("merge-base", input.head, target)).trim();
4876
4885
  const settled = input.automerged === undefined ? [] : (yield* names(input.automerged, input.merged)).filter((path) => !input.conflicted.includes(path));
4877
4886
  const rewritten = [...new Set([...settled, ...yield* names(input.merged, input.head)])].sort();
4878
4887
  const paths = [...new Set([...yield* names(before, input.from), ...yield* names(after, input.head)])].sort();
4879
- const changed = yield* filter3(paths.slice(0, catchUpPathLimit), (path) => map8(all3([ownDiff(before, input.from, path), ownDiff(after, input.head, path)]), ([was, is]) => was !== is), { concurrency: 8 });
4888
+ const changed = yield* filter3(paths.slice(0, catchUpPathLimit), (path) => map9(all3([ownDiff(before, input.from, path), ownDiff(after, input.head, path)]), ([was, is]) => was !== is), { concurrency: 8 });
4880
4889
  const lists = [input.conflicted, rewritten, paths];
4881
4890
  return {
4882
4891
  from: input.from,
@@ -4888,6 +4897,430 @@ var catchUpReport = (worktree, input) => gen(function* () {
4888
4897
  };
4889
4898
  });
4890
4899
 
4900
+ // packages/agent-runtime/src/merged-change.ts
4901
+ var commitsOf = (git, ...args) => map9(git("log", "-z", "--format=%H%n%P%n%ct%n%at%n%an%n%ae%n%B", ...args), (out) => out.split("\x00").filter(Boolean).map((record) => {
4902
+ const [sha = "", parents = "", committed, authored, name = "", email = "", ...message] = record.split(`
4903
+ `);
4904
+ const author = `${name}
4905
+ ${email}
4906
+ ${authored}`;
4907
+ return {
4908
+ sha,
4909
+ parents: parents.split(" ").filter(Boolean),
4910
+ committed: Number(committed),
4911
+ authored: Number(authored),
4912
+ author,
4913
+ identity: `${author}
4914
+ ${message.join(`
4915
+ `).trim()}`
4916
+ };
4917
+ }));
4918
+ var messageOf = (git, commit) => map9(git("log", "-1", "--format=%B", commit), (out) => out.trim());
4919
+ var subjectOf = (git, commit) => map9(git("log", "-1", "--format=%s", commit), (out) => out.trim());
4920
+ var treeOf = (git, revision) => map9(git("rev-parse", "--verify", `${revision}^{tree}`), (out) => out.trim());
4921
+ var readCommit = (git, commit, fetchCommit) => gen(function* () {
4922
+ const read = map9(exit(git("rev-parse", "--quiet", "--verify", `${commit}^{commit}`)), (exit) => isSuccess2(exit) ? exit.value.trim() : undefined);
4923
+ const known = yield* read;
4924
+ if (known !== undefined)
4925
+ return known;
4926
+ yield* fetchCommit(commit);
4927
+ return yield* read;
4928
+ });
4929
+ var isAncestor = (git, ancestor, of) => map9(exit(git("merge-base", "--is-ancestor", ancestor, of)), isSuccess2);
4930
+ var mergedTree = (git, ours, theirs) => git("merge-tree", "--write-tree", "--no-messages", ours, theirs).pipe(map9((out) => out.trim()), catchTag("CommandFailed", (failed) => /^exit code 1(?::|$)/u.test(failed.reason) ? undefined_ : fail7(failed)));
4931
+ var mergedTreeOver = (git, base, ours, theirs) => gen(function* () {
4932
+ const commitOf = (revision, ...parent) => map9(git("commit-tree", `${revision}^{tree}`, ...parent, "-m", "side"), (out) => out.trim());
4933
+ const root = yield* commitOf(base);
4934
+ return yield* mergedTree(git, yield* commitOf(ours, "-p", root), yield* commitOf(theirs, "-p", root));
4935
+ });
4936
+ var isSquashOf = (git, input) => gen(function* () {
4937
+ const { tip, uncopied } = input;
4938
+ if (uncopied.some((commit) => commit.author === tip.author) && (tip.authored !== tip.committed || input.mayBeReworded))
4939
+ return false;
4940
+ if ((yield* mergedTree(git, tip.sha, input.head)) !== (yield* treeOf(git, tip.sha)))
4941
+ return false;
4942
+ let held = input.targetSide;
4943
+ let broughtIn = false;
4944
+ for (const { sha, parents } of uncopied) {
4945
+ const [parent] = parents;
4946
+ if (parent === undefined)
4947
+ return false;
4948
+ if ((yield* treeOf(git, sha)) === (yield* treeOf(git, parent)))
4949
+ continue;
4950
+ const next = yield* mergedTreeOver(git, parent, held, sha);
4951
+ if (next === (yield* treeOf(git, held)))
4952
+ return false;
4953
+ held = next ?? held;
4954
+ broughtIn = true;
4955
+ }
4956
+ return broughtIn;
4957
+ });
4958
+ var changeSpan = (git, change, fetchCommit) => gen(function* () {
4959
+ const tip = yield* readCommit(git, change.revision, fetchCommit);
4960
+ if (tip === undefined)
4961
+ return { refused: `Kitman cannot read the merge revision ${change.revision}, so it cannot apply it` };
4962
+ const head = change.head === undefined ? undefined : yield* readCommit(git, change.head, fetchCommit);
4963
+ if (head === undefined)
4964
+ return {
4965
+ refused: `Kitman cannot read the head ${change.head ?? "of the ChangeRequest"}, so it cannot tell how it was merged`
4966
+ };
4967
+ const [tipCommit] = yield* commitsOf(git, "-1", tip);
4968
+ const [targetSide, ...mergedSides] = tipCommit?.parents ?? [];
4969
+ if (tipCommit === undefined || targetSide === undefined)
4970
+ return { refused: `The merge revision ${tip} is a root commit, which has no change to apply` };
4971
+ if (head === tip || (yield* isAncestor(git, head, targetSide)))
4972
+ return {
4973
+ refused: `The ChangeRequest was merged by fast-forward as ${tip}, so nothing on its target says where its change starts`
4974
+ };
4975
+ const tipAlone = { base: targetSide, tip, head, commits: [tip] };
4976
+ if (mergedSides.length > 0)
4977
+ return tipAlone;
4978
+ const headCommits = yield* commitsOf(git, "--reverse", "--no-merges", `${tip}..${head}`);
4979
+ const sinceHead = yield* commitsOf(git, "--first-parent", `${head}..${tip}`);
4980
+ const reachedTarget = yield* commitsOf(git, `${head}..${tip}`);
4981
+ const copiesOf = (commit) => reachedTarget.filter((target) => target.identity === commit.identity);
4982
+ const picked = (commit) => commit !== undefined && copiesOf(commit).some((copy) => copy.committed < commit.committed);
4983
+ const replays = [];
4984
+ let next = headCommits.length - 1;
4985
+ for (const copy of sinceHead) {
4986
+ while (headCommits[next]?.identity !== copy.identity && picked(headCommits[next]))
4987
+ next -= 1;
4988
+ const original = headCommits[next];
4989
+ if (original?.identity !== copy.identity)
4990
+ break;
4991
+ replays.push({ copy, original });
4992
+ next -= 1;
4993
+ }
4994
+ if (replays.length > 0) {
4995
+ if (replays.some(({ copy, original }) => copy.committed < original.committed))
4996
+ return {
4997
+ refused: `The merge revision ${tip} replays commits of the head ${head} that were committed before their copies on the head, as when the head's clock was ahead of the forge's or the head picked them from the target, so Kitman cannot tell which commits are the change`
4998
+ };
4999
+ if (next >= 0)
5000
+ return {
5001
+ refused: `The merge revision ${tip} replays commits of the head ${head}, but not all of the head's own commits in order, so Kitman cannot tell which commits are the change`
5002
+ };
5003
+ const replayed = replays.map(({ copy }) => copy).toReversed();
5004
+ const span = {
5005
+ base: (yield* git("rev-parse", `${replayed[0]?.sha ?? tip}^`)).trim(),
5006
+ tip,
5007
+ head,
5008
+ commits: replayed.map((commit) => commit.sha)
5009
+ };
5010
+ return span;
5011
+ }
5012
+ const copied = headCommits.filter((commit) => copiesOf(commit).length > 0);
5013
+ if (copied.length === 0)
5014
+ return tipAlone;
5015
+ if (headCommits.some((commit) => commit.committed > tipCommit.committed))
5016
+ return {
5017
+ refused: `The target holds copies of the own commits of the head ${head} below the merge revision ${tip}, and the head was committed after it, as when its clock was ahead of the forge's, so Kitman cannot tell which commits are the change`
5018
+ };
5019
+ const uncopied = headCommits.filter((commit) => !copied.includes(commit));
5020
+ const copiedLater = copied.some((commit) => copiesOf(commit).every((copy) => copy.committed > commit.committed));
5021
+ if (copiedLater || !(yield* isSquashOf(git, {
5022
+ tip: tipCommit,
5023
+ targetSide,
5024
+ head,
5025
+ uncopied,
5026
+ mayBeReworded: uncopied.length === 1 && uncopied[0] === headCommits.at(-1) && copied.some((commit) => !picked(commit))
5027
+ })))
5028
+ return {
5029
+ refused: `The target holds copies of the own commits of the head ${head} below the merge revision ${tip}, as when the head is older than the one merged or the target picked them before a squash, so Kitman cannot tell which commits are the change`
5030
+ };
5031
+ return tipAlone;
5032
+ });
5033
+ var authorOf = (git, span) => gen(function* () {
5034
+ const authors = new Set(yield* forEach(span.commits, (commit) => map9(git("log", "-1", "--format=%an <%ae>", commit), (out) => out.trim())));
5035
+ const [author] = authors;
5036
+ if (authors.size !== 1 || author === undefined)
5037
+ return [];
5038
+ return ["--author", author, "--date", (yield* git("log", "-1", "--format=%aI", span.tip)).trim()];
5039
+ });
5040
+ var appliedMessage = (git, span, revert) => gen(function* () {
5041
+ const first = span.commits[0] ?? span.tip;
5042
+ if (span.commits.length === 1)
5043
+ return revert ? `Revert "${yield* subjectOf(git, span.tip)}"
5044
+
5045
+ This reverts commit ${span.tip}.` : `${yield* messageOf(git, span.tip)}
5046
+
5047
+ (cherry picked from commit ${span.tip})`;
5048
+ const subjects = yield* forEach(span.commits, (commit) => subjectOf(git, commit));
5049
+ const listed = subjects.map((subject) => `- ${subject}`).join(`
5050
+ `);
5051
+ return revert ? `Revert ${span.commits.length} commits up to ${span.tip}
5052
+
5053
+ ${listed}
5054
+
5055
+ This reverts commits ${first}^..${span.tip}.` : `Apply ${span.commits.length} commits up to ${span.tip}
5056
+
5057
+ ${listed}
5058
+
5059
+ (cherry picked from commits ${first}^..${span.tip})`;
5060
+ });
5061
+ var cEscapes = new Map([
5062
+ ["a", 7],
5063
+ ["b", 8],
5064
+ ["t", 9],
5065
+ ["n", 10],
5066
+ ["v", 11],
5067
+ ["f", 12],
5068
+ ["r", 13]
5069
+ ]);
5070
+ var pathNamed = (named) => {
5071
+ if (!named.startsWith('"'))
5072
+ return named;
5073
+ const bytes = [];
5074
+ for (let at = 1;at < named.length && named[at] !== '"'; at += 1) {
5075
+ const char = String.fromCodePoint(named.codePointAt(at) ?? 0);
5076
+ const octal = char === "\\" ? /^[0-7]{3}/u.exec(named.slice(at + 1))?.[0] : undefined;
5077
+ if (octal !== undefined) {
5078
+ bytes.push(Number.parseInt(octal, 8));
5079
+ at += 3;
5080
+ } else if (char === "\\") {
5081
+ at += 1;
5082
+ const escaped = named[at] ?? "";
5083
+ bytes.push(cEscapes.get(escaped) ?? escaped.charCodeAt(0));
5084
+ } else {
5085
+ bytes.push(...new TextEncoder().encode(char));
5086
+ at += char.length - 1;
5087
+ }
5088
+ }
5089
+ return String.fromCharCode(...bytes);
5090
+ };
5091
+ var argumentFor = (path) => {
5092
+ try {
5093
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(path, (char) => char.charCodeAt(0)));
5094
+ } catch {
5095
+ return;
5096
+ }
5097
+ };
5098
+ var sidePath = (named, prefix) => {
5099
+ const path = named.startsWith('"') ? pathNamed(named) : named.replace(/\t$/u, "");
5100
+ return path.startsWith(prefix) ? path.slice(prefix.length) : undefined;
5101
+ };
5102
+ var fileDiffs = (out) => {
5103
+ const files = [];
5104
+ let file;
5105
+ let hunk;
5106
+ for (const line of out.split(`
5107
+ `)) {
5108
+ if (line.startsWith("diff --git ")) {
5109
+ const both = line.slice("diff --git ".length);
5110
+ const half = both.slice(2, 2 + (both.length - 5) / 2);
5111
+ const quoted = both.slice(3, 3 + (both.length - 9) / 2);
5112
+ const same = both === `a/${half} b/${half}` ? half : both === `"a/${quoted}" "b/${quoted}"` ? pathNamed(`"${quoted}"`) : undefined;
5113
+ file = { from: same, to: same, deleted: false, hunks: [] };
5114
+ files.push(file);
5115
+ hunk = undefined;
5116
+ } else if (file === undefined)
5117
+ continue;
5118
+ else if (hunk !== undefined && line.startsWith("-"))
5119
+ hunk.removed.push(line.slice(1));
5120
+ else if (hunk !== undefined && line.startsWith("+"))
5121
+ hunk.added.push(line.slice(1));
5122
+ else if (line.startsWith("@@ ")) {
5123
+ const [, from = "0", count = "1", to] = /^@@ -(\d+)(?:,(\d+))? \+\d+(,\d+)? @@/u.exec(line) ?? [];
5124
+ hunk = { removedOnly: to === ",0", from: Number(from), count: Number(count), removed: [], added: [] };
5125
+ file.hunks.push(hunk);
5126
+ } else if (hunk !== undefined)
5127
+ continue;
5128
+ else if (line.startsWith("deleted file mode"))
5129
+ file.deleted = true;
5130
+ else if (line.startsWith("rename from "))
5131
+ file.from = pathNamed(line.slice("rename from ".length));
5132
+ else if (line.startsWith("rename to "))
5133
+ file.to = pathNamed(line.slice("rename to ".length));
5134
+ else if (line.startsWith("--- "))
5135
+ file.from = sidePath(line.slice("--- ".length), "a/");
5136
+ else if (line.startsWith("+++ "))
5137
+ file.to = sidePath(line.slice("+++ ".length), "b/");
5138
+ }
5139
+ return files;
5140
+ };
5141
+ var diff = (git, ...args) => git("-c", "core.quotePath=true", "diff", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", "-U0", ...args);
5142
+ var addedLines = (git, span, only) => map9(forEach(only?.map((part) => [`${part}^`, part]) ?? [[span.base, span.tip]], ([from, to]) => diff(git, "--no-renames", from, to)), (outs) => {
5143
+ const lines = new Map;
5144
+ for (const file of outs.flatMap(fileDiffs))
5145
+ if (file.to !== undefined)
5146
+ lines.set(file.to, new Set([...lines.get(file.to) ?? [], ...file.hunks.flatMap((hunk) => hunk.added)]));
5147
+ return lines;
5148
+ });
5149
+ var linesWrittenBy = (git, revision, path, ranges) => map9(git("blame", "--porcelain", ...ranges.flatMap((hunk) => ["-L", `${hunk.from},+${hunk.count}`]), revision, "--", path), (out) => new Set(out.split(`
5150
+ `).flatMap((line) => /^([0-9a-f]{40,64}) \d+ \d+/u.exec(line)?.[1] ?? [])));
5151
+ var removesPartOf = (git, added, changeCommits, parent, commit) => gen(function* () {
5152
+ let removes = false;
5153
+ for (const file of fileDiffs(yield* diff(git, "-M", parent, commit))) {
5154
+ const lines = file.from === undefined ? undefined : added.get(file.from);
5155
+ if (file.from === undefined || lines === undefined)
5156
+ continue;
5157
+ if (file.deleted || file.to !== file.from) {
5158
+ added.delete(file.from);
5159
+ if (!file.deleted && file.to !== undefined)
5160
+ added.set(file.to, lines);
5161
+ }
5162
+ if (removes || file.deleted) {
5163
+ removes = true;
5164
+ continue;
5165
+ }
5166
+ const removals = file.hunks.filter((hunk) => hunk.removedOnly && hunk.removed.some((line) => lines.has(line)));
5167
+ if (removals.length === 0)
5168
+ continue;
5169
+ const path = argumentFor(file.from);
5170
+ removes = path === undefined || [...yield* linesWrittenBy(git, parent, path, removals)].some((writer) => changeCommits.has(writer));
5171
+ }
5172
+ return removes;
5173
+ });
5174
+ var holdsAny = (git, commits, revision) => gen(function* () {
5175
+ for (const commit of commits)
5176
+ if (yield* isAncestor(git, commit, revision))
5177
+ return true;
5178
+ return false;
5179
+ });
5180
+ var holdsEach = (git, arrivals, revision) => gen(function* () {
5181
+ for (const by of arrivals.values())
5182
+ if (!(yield* holdsAny(git, by, revision)))
5183
+ return false;
5184
+ return true;
5185
+ });
5186
+ var namedPicks = /\(cherry picked from commits? ([0-9a-f]{40,64})(?:\^\.\.([0-9a-f]{40,64}))?\)/gu;
5187
+ var namedReverts = /This reverts commits? ([0-9a-f]{40,64})(?:\^\.\.([0-9a-f]{40,64}))?/gu;
5188
+ var heldBy = (git, span, whole, branch, only) => gen(function* () {
5189
+ const range = yield* commitsOf(git, "--no-merges", `${span.base}..${span.tip}`);
5190
+ const [tip] = yield* commitsOf(git, "-1", span.tip);
5191
+ const all = range.length === 0 ? [span.tip] : range.map((commit) => commit.sha);
5192
+ const parts = only === undefined ? all : all.filter((part) => only.includes(part));
5193
+ const missing = new Set((yield* git("rev-list", `${span.base}..${span.tip}`, `^${branch}`)).split(`
5194
+ `));
5195
+ const held = new Set((yield* isAncestor(git, span.head, branch)) ? parts : parts.filter((part) => !missing.has(part)));
5196
+ const effects = new Map;
5197
+ const changeCommits = new Set([...parts, span.tip]);
5198
+ let carried = false;
5199
+ const put = (by, named, now) => {
5200
+ const changed = named.filter((part) => parts.includes(part));
5201
+ if (changed.length === 0)
5202
+ return;
5203
+ carried = true;
5204
+ if (now)
5205
+ changeCommits.add(by);
5206
+ effects.set(by, { parts: [...effects.get(by)?.parts ?? [], ...changed], held: now });
5207
+ for (const part of changed) {
5208
+ if (now) {
5209
+ held.add(part);
5210
+ arrivals.get(part)?.push(by);
5211
+ } else
5212
+ held.delete(part);
5213
+ }
5214
+ };
5215
+ const partsNamed = (sha, end) => {
5216
+ if (end !== undefined)
5217
+ return end === span.tip ? parts : [];
5218
+ return parts.includes(sha) ? [sha] : sha === span.tip ? parts : [];
5219
+ };
5220
+ const samePatch = new Set(held.size > 0 ? [] : (yield* git("rev-list", "--cherry-mark", "--right-only", "--no-merges", `${whole}...${branch}`, `^${span.base}`)).split(`
5221
+ `).flatMap((line) => line.startsWith("=") ? [line.slice(1)] : []));
5222
+ const headOwn = new Set((yield* git("rev-list", `${span.tip}..${span.head}`)).split(`
5223
+ `).filter(Boolean));
5224
+ for (const own of headOwn)
5225
+ changeCommits.add(own);
5226
+ const firstParents = new Set((yield* git("rev-list", "--first-parent", `${span.tip}..${branch}`)).split(`
5227
+ `));
5228
+ const arrivals = new Map(parts.map((part) => [part, held.has(part) ? [part] : []]));
5229
+ let present = false;
5230
+ let added;
5231
+ let partlyRemoved = false;
5232
+ for (const commit of yield* commitsOf(git, "--reverse", `${span.tip}..${branch}`)) {
5233
+ carried = false;
5234
+ const wholeCopy = samePatch.has(commit.sha) || span.commits.length === 1 && commit.identity === tip?.identity;
5235
+ const copied = wholeCopy ? parts : range.flatMap((part) => part.identity === commit.identity ? [part.sha] : []);
5236
+ put(commit.sha, copied, true);
5237
+ for (const [, sha = "", end] of commit.identity.matchAll(namedPicks)) {
5238
+ const named = partsNamed(sha, end);
5239
+ const effect = effects.get(sha);
5240
+ if (named.length > 0)
5241
+ put(commit.sha, named, true);
5242
+ else if (effect !== undefined)
5243
+ put(commit.sha, effect.parts, effect.held);
5244
+ }
5245
+ for (const [, sha = "", end] of commit.identity.matchAll(namedReverts)) {
5246
+ const named = partsNamed(sha, end);
5247
+ const effect = effects.get(sha);
5248
+ if (named.length > 0)
5249
+ put(commit.sha, named, false);
5250
+ else if (effect !== undefined)
5251
+ put(commit.sha, effect.parts, !effect.held);
5252
+ }
5253
+ if (held.size !== parts.length)
5254
+ continue;
5255
+ const [parent] = commit.parents;
5256
+ if (carried) {
5257
+ partlyRemoved = false;
5258
+ added = undefined;
5259
+ } else if (parent !== undefined && firstParents.has(commit.sha) && !headOwn.has(commit.sha)) {
5260
+ const before = present || (yield* holdsEach(git, arrivals, parent));
5261
+ if (!before && !(yield* holdsEach(git, arrivals, commit.sha)))
5262
+ continue;
5263
+ present = true;
5264
+ if (before) {
5265
+ added ??= yield* addedLines(git, span, only);
5266
+ if (yield* removesPartOf(git, added, changeCommits, parent, commit.sha))
5267
+ partlyRemoved = true;
5268
+ continue;
5269
+ }
5270
+ let side;
5271
+ for (const other of commit.parents.slice(1))
5272
+ if (side === undefined && (yield* holdsEach(git, arrivals, other)))
5273
+ side = other;
5274
+ if (side === undefined) {
5275
+ const bySide = new Map;
5276
+ for (const [part, by] of arrivals) {
5277
+ let holder;
5278
+ for (const other of commit.parents)
5279
+ if (holder === undefined && (yield* holdsAny(git, by, other)))
5280
+ holder = other;
5281
+ if (holder !== undefined)
5282
+ bySide.set(holder, [...bySide.get(holder) ?? [], part]);
5283
+ }
5284
+ added = new Map;
5285
+ for (const [holder, held] of bySide) {
5286
+ const sideHeld = yield* heldBy(git, span, whole, holder, held);
5287
+ for (const own of sideHeld.changeCommits)
5288
+ changeCommits.add(own);
5289
+ const sideAdded = sideHeld.added ?? (yield* addedLines(git, span, held));
5290
+ if (!sideHeld.all || (yield* removesPartOf(git, sideAdded, changeCommits, holder, commit.sha)))
5291
+ partlyRemoved = true;
5292
+ for (const [path, lines] of sideAdded)
5293
+ added.set(path, new Set([...added.get(path) ?? [], ...lines]));
5294
+ }
5295
+ continue;
5296
+ }
5297
+ const sideHeld = yield* heldBy(git, span, whole, side, only);
5298
+ for (const own of sideHeld.changeCommits)
5299
+ changeCommits.add(own);
5300
+ added = sideHeld.added ?? (yield* addedLines(git, span, only));
5301
+ if (!sideHeld.all || (yield* removesPartOf(git, added, changeCommits, side, commit.sha)))
5302
+ partlyRemoved = true;
5303
+ }
5304
+ }
5305
+ return { all: held.size === parts.length && !partlyRemoved, some: held.size > 0, added, changeCommits };
5306
+ });
5307
+ var needsNothing = (git, input) => gen(function* () {
5308
+ const { span, branch, clean } = input;
5309
+ const held = yield* heldBy(git, span, input.whole, branch);
5310
+ if (input.revert) {
5311
+ if (held.some)
5312
+ return false;
5313
+ if (!clean)
5314
+ return true;
5315
+ const removed = yield* git("diff", "--cached", "--numstat", "--no-renames", "--diff-filter=a", "HEAD");
5316
+ return removed.split(`
5317
+ `).every((line) => line === "" || line.split("\t")[1] === "0");
5318
+ }
5319
+ if (!held.all)
5320
+ return false;
5321
+ return (yield* mergedTreeOver(git, span.tip, branch, span.base)) === undefined;
5322
+ });
5323
+
4891
5324
  // node_modules/.bun/effect@4.1.2/node_modules/effect/dist/internal/matcher.js
4892
5325
  var TypeId2 = "~effect/Match/Matcher";
4893
5326
  var TypeMatcherProto = {
@@ -5888,7 +6321,7 @@ var transcriptRelay = (input) => {
5888
6321
  passOver(last);
5889
6322
  batchLimit = batchSize;
5890
6323
  };
5891
- const givesUp = (error, lastChance) => map8(currentTimeMillis, (now) => {
6324
+ const givesUp = (error, lastChance) => map9(currentTimeMillis, (now) => {
5892
6325
  if (lastChance || sendRefusal(error) === "refused")
5893
6326
  return true;
5894
6327
  failingSince ??= now;
@@ -6059,7 +6492,7 @@ var transcriptRelay = (input) => {
6059
6492
  });
6060
6493
  return {
6061
6494
  record,
6062
- stalledFor: (millis) => map8(currentTimeMillis, (now) => asking.size === 0 && progressAt !== undefined && now - progressAt >= millis),
6495
+ stalledFor: (millis) => map9(currentTimeMillis, (now) => asking.size === 0 && progressAt !== undefined && now - progressAt >= millis),
6063
6496
  asking: sync2(() => asking.size > 0),
6064
6497
  loginLost: sync2(() => loginLost),
6065
6498
  refusal: sync2(() => refusal),
@@ -6164,7 +6597,7 @@ var repositoryClone = (rootDir, repoBindingId) => `${rootDir}/repos/${repoBindin
6164
6597
  var runCheckouts = (rootDir, credentials) => {
6165
6598
  const runsDir = `${rootDir}/runs`;
6166
6599
  const reposDir = `${rootDir}/repos`;
6167
- const remote = (repoBinding) => map8(credentials === undefined ? undefined_ : credentials(repoBinding.id).pipe(catch_((error) => as(logWarning("runner_git_credential_unavailable", error.message), undefined))), (credential) => gitRemote(repoBinding, credential));
6600
+ const remote = (repoBinding) => map9(credentials === undefined ? undefined_ : credentials(repoBinding.id).pipe(catch_((error) => as(logWarning("runner_git_credential_unavailable", error.message), undefined))), (credential) => gitRemote(repoBinding, credential));
6168
6601
  const cloned = (repoBinding) => gen(function* () {
6169
6602
  const fs = yield* FileSystem;
6170
6603
  const forbidden = findForbiddenRepoBindingSecretPath(repoBinding);
@@ -6191,9 +6624,9 @@ var runCheckouts = (rootDir, credentials) => {
6191
6624
  });
6192
6625
  const fetch = (directory, env) => runCommand2("git", ["-C", directory, ...stallLimit, "fetch", "--prune", "origin"], { ...transfer, env });
6193
6626
  const inCloneOf = (repoBinding) => inClone(repositoryClone(rootDir, repoBinding.id));
6194
- const clone = (repoBinding) => inCloneOf(repoBinding)(map8(cloned(repoBinding), ({ directory }) => directory));
6195
- const transferEnv = (repoBinding) => repoBinding === undefined ? succeed6({}) : map8(remote(repoBinding), ({ env }) => env);
6196
- const holds = (directory, revision) => revision === undefined || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(revision) ? succeed6(false) : map8(exit(runCommand2("git", ["-C", directory, "cat-file", "-e", `${revision}^{commit}`])), isSuccess2);
6627
+ const clone = (repoBinding) => inCloneOf(repoBinding)(map9(cloned(repoBinding), ({ directory }) => directory));
6628
+ const transferEnv = (repoBinding) => repoBinding === undefined ? succeed6({}) : map9(remote(repoBinding), ({ env }) => env);
6629
+ const holds = (directory, revision) => revision === undefined || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(revision) ? succeed6(false) : map9(exit(runCommand2("git", ["-C", directory, "cat-file", "-e", `${revision}^{commit}`])), isSuccess2);
6197
6630
  const checkout = (work, repoBinding, checkpoint) => gen(function* () {
6198
6631
  const fs = yield* FileSystem;
6199
6632
  const path = yield* Path;
@@ -6236,7 +6669,7 @@ var runCheckouts = (rootDir, credentials) => {
6236
6669
  const directory = `${rootDir}/scratch/${work.id}`;
6237
6670
  return yield* acquireRelease(as(fs.makeDirectory(directory, { recursive: true }), directory), () => ignore(fs.remove(directory, { recursive: true, force: true })));
6238
6671
  });
6239
- const reaches = (repoBinding) => flatMap3(remote(repoBinding), ({ url, env }) => map8(exit(runCommand2("git", [...stallLimit, "ls-remote", url, "HEAD"], { timeout: "1 minute", env })), isSuccess2));
6672
+ const reaches = (repoBinding) => flatMap3(remote(repoBinding), ({ url, env }) => map9(exit(runCommand2("git", [...stallLimit, "ls-remote", url, "HEAD"], { timeout: "1 minute", env })), isSuccess2));
6240
6673
  return {
6241
6674
  clone,
6242
6675
  transferEnv,
@@ -6265,7 +6698,7 @@ var clearSettledCheckpoints = (rpc, checkouts) => gen(function* () {
6265
6698
  var deleteRef = (checkouts, repoBinding, ref) => gen(function* () {
6266
6699
  const repository = yield* checkouts.clone(repoBinding);
6267
6700
  const env = yield* checkouts.transferEnv(repoBinding);
6268
- const onOrigin = map8(runCommand2("git", ["-C", repository, "ls-remote", "origin", ref], { env }), (listed) => listed.trim() !== "");
6701
+ const onOrigin = map9(runCommand2("git", ["-C", repository, "ls-remote", "origin", ref], { env }), (listed) => listed.trim() !== "");
6269
6702
  if (yield* onOrigin)
6270
6703
  yield* runCommand2("git", ["-C", repository, ...stallLimit, "push", "origin", "--delete", ref], {
6271
6704
  ...transfer,
@@ -6304,7 +6737,7 @@ var runChange = (worktree, runBase) => gen(function* () {
6304
6737
  const git = (...args) => runCommand2("git", ["-C", worktree, ...args]);
6305
6738
  const base = (yield* git("merge-base", "HEAD", runBase)).trim();
6306
6739
  const changedPaths = (yield* git("diff", "--name-only", "-z", "--no-renames", base, "HEAD")).split("\x00").filter((path) => path !== "");
6307
- const files = yield* forEach(changedPaths.slice(0, EvidenceLimits.files).filter((path) => !looksSecret(path)), (path) => map8(git("diff", "--no-color", "--no-renames", base, "HEAD", "--", `:(literal)${path}`), (diff) => ({
6740
+ const files = yield* forEach(changedPaths.slice(0, EvidenceLimits.files).filter((path) => !looksSecret(path)), (path) => map9(git("diff", "--no-color", "--no-renames", base, "HEAD", "--", `:(literal)${path}`), (diff) => ({
6308
6741
  path,
6309
6742
  diff
6310
6743
  })));
@@ -6323,7 +6756,7 @@ var keepSession = (rpc, lease, content) => gen(function* () {
6323
6756
  yield* fs.writeFile(path, content);
6324
6757
  const files = {
6325
6758
  createRunFile: ({ byteSize, sha256 }) => rpc.createCheckpointFile({ lease, byteSize, sha256 }),
6326
- runFileParts: (request) => map8(rpc.checkpointFileParts({ lease, ...request, partNumbers: [...request.partNumbers] }), ({ parts }) => parts),
6759
+ runFileParts: (request) => map9(rpc.checkpointFileParts({ lease, ...request, partNumbers: [...request.partNumbers] }), ({ parts }) => parts),
6327
6760
  completeRunFile: ({ parts, ...request }) => rpc.completeCheckpointFile({ lease, ...request, ...parts === undefined ? undefined : { parts: [...parts] } })
6328
6761
  };
6329
6762
  const kept = yield* uploadRunFile(files, { step: "", name: "session.gz", path });
@@ -6370,8 +6803,39 @@ var stageAll = (worktree, git) => gen(function* () {
6370
6803
  }
6371
6804
  yield* git("add", "--all", "--", ".", ...leftovers.map((name) => `:(exclude,top)${name}`));
6372
6805
  });
6373
- var conflictMarker = "^(<<<<<<<|>>>>>>>)( |$)";
6374
- var markedPaths = (git, paths, ...from) => git("grep", ...from, "-l", "-z", "-E", conflictMarker, "--", ...paths.map((path) => `:(literal,top)${path}`)).pipe(catchIf((error) => error.reason === "exit code 1", () => succeed6("")), map8((out) => out.split("\x00").filter(Boolean)));
6806
+ var pathsByMarkerSize = (worktree, paths) => gen(function* () {
6807
+ const fs = yield* FileSystem;
6808
+ const index = (yield* runCommand2("git", [
6809
+ "-C",
6810
+ worktree,
6811
+ "rev-parse",
6812
+ "--path-format=absolute",
6813
+ "--git-path",
6814
+ "index"
6815
+ ])).trim();
6816
+ const headIndex = `${index}.kitman-head`;
6817
+ const git = (...args) => runCommand2("git", ["-C", worktree, ...args], { env: { GIT_INDEX_FILE: headIndex } });
6818
+ const out = yield* ensuring2(andThen2(git("read-tree", "HEAD"), git("check-attr", "--cached", "-z", "conflict-marker-size", "--", ...paths)), ignore(fs.remove(headIndex)));
6819
+ const fields = out.split("\x00");
6820
+ const bySize = new Map;
6821
+ for (let at = 0;at + 2 < fields.length; at += 3) {
6822
+ const [path = "", , value = ""] = fields.slice(at, at + 3);
6823
+ const parsed = Number.parseInt(value, 10);
6824
+ const size = parsed > 0 ? parsed : 7;
6825
+ bySize.set(size, [...bySize.get(size) ?? [], path]);
6826
+ }
6827
+ return bySize;
6828
+ });
6829
+ var markedPaths = (worktree, git, paths, ...from) => gen(function* () {
6830
+ const bySize = yield* pathsByMarkerSize(worktree, paths);
6831
+ const found = yield* forEach([...bySize], ([size, sized]) => {
6832
+ const marker = `^(${"<".repeat(size)}<?|${">".repeat(size)}>?)( |$)`;
6833
+ return git("grep", ...from, "-l", "-z", "-E", marker, "--", ...sized.map((path) => `:(literal,top)${path}`)).pipe(catchIf((error) => error.reason === "exit code 1", () => succeed6("")));
6834
+ });
6835
+ return found.flatMap((out) => out.split("\x00").filter(Boolean));
6836
+ });
6837
+ var nothingStaged = (git) => map9(exit(git("diff", "--cached", "--quiet", "HEAD")), isSuccess2);
6838
+ var backToHead = (git) => andThen2(git("reset", "--hard", "--quiet", "HEAD"), git("clean", "-d", "--force", "--quiet"));
6375
6839
  var list = (paths) => paths.join(", ");
6376
6840
  var unmarkedConflicts = (worktree, conflicted, marked) => gen(function* () {
6377
6841
  const stages = new Map;
@@ -6408,9 +6872,10 @@ var automergedTree = (worktree, conflicted) => gen(function* () {
6408
6872
  const scratchIndex = `${index}.kitman-automerged`;
6409
6873
  const git = (...args) => runCommand2("git", ["-C", worktree, ...args], { env: { GIT_INDEX_FILE: scratchIndex } });
6410
6874
  yield* fs.copyFile(index, scratchIndex);
6411
- return yield* ensuring2(andThen2(git("update-index", "--force-remove", "--", ...conflicted), map8(git("write-tree"), (tree) => tree.trim())), ignore(fs.remove(scratchIndex)));
6875
+ return yield* ensuring2(andThen2(git("update-index", "--force-remove", "--", ...conflicted), map9(git("write-tree"), (tree) => tree.trim())), ignore(fs.remove(scratchIndex)));
6412
6876
  });
6413
- var mergeTarget = (worktree, target) => gen(function* () {
6877
+ var afterMergeLine = (command, targetCommit) => `\`${command.command} ${targetCommit}\`${command.workingDirectory === undefined ? "" : ` in \`${command.workingDirectory}\``}`;
6878
+ var mergeTarget = (worktree, target, afterMerge) => gen(function* () {
6414
6879
  const git = (...args) => runCommand2("git", ["-C", worktree, ...gitIdentity, ...args]);
6415
6880
  const before = yield* git("rev-parse", "HEAD");
6416
6881
  const targetCommit = (yield* git("rev-parse", "--verify", `origin/${target}^{commit}`)).trim();
@@ -6429,7 +6894,7 @@ var mergeTarget = (worktree, target) => gen(function* () {
6429
6894
  const conflicted = (yield* git("diff", "--name-only", "-z", "--diff-filter=U")).split("\x00").filter(Boolean);
6430
6895
  if (conflicted.length === 0)
6431
6896
  return yield* failCause3(merged.cause);
6432
- const marked = yield* markedPaths(git, conflicted);
6897
+ const marked = yield* markedPaths(worktree, git, conflicted);
6433
6898
  const unmarked = yield* unmarkedConflicts(worktree, conflicted, marked);
6434
6899
  const conflicts = [...marked.length === 0 ? [] : [`${list(marked)}: it holds conflict markers`], ...unmarked];
6435
6900
  return {
@@ -6440,11 +6905,82 @@ var mergeTarget = (worktree, target) => gen(function* () {
6440
6905
  note: [
6441
6906
  `${subject}: it conflicts, and the merge stays open until you answer.`,
6442
6907
  ...conflicts.map((conflict) => `- ${conflict}.`),
6443
- "Answer merged and Kitman commits these files as you leave them, a file you deleted as deleted; answer conflict and Kitman aborts the merge."
6908
+ "Answer merged and Kitman commits these files as you leave them, a file you deleted as deleted; answer conflict and Kitman aborts the merge.",
6909
+ ...afterMerge === undefined ? [] : [
6910
+ `Once they are settled, run the repository's after-merge command, ${afterMergeLine(afterMerge, targetCommit)}, before you answer merged.`
6911
+ ]
6912
+ ].join(`
6913
+ `)
6914
+ };
6915
+ });
6916
+ var applyChange = (worktree, change, fetchCommit) => gen(function* () {
6917
+ const git = (...args) => runCommand2("git", ["-C", worktree, ...gitIdentity, ...args]);
6918
+ const revert = change.revert === true;
6919
+ const span = yield* changeSpan(git, change, fetchCommit);
6920
+ if ("refused" in span)
6921
+ return { kind: "refused", reason: span.refused };
6922
+ const before = (yield* git("rev-parse", "HEAD")).trim();
6923
+ const already = { kind: "already", applied: { status: "already" } };
6924
+ const message = yield* appliedMessage(git, span, revert);
6925
+ const author = revert ? [] : yield* authorOf(git, span);
6926
+ const whole = (yield* git("commit-tree", `${span.tip}^{tree}`, "-p", span.base, "-m", message)).trim();
6927
+ const applied = yield* exit(git(revert ? "revert" : "cherry-pick", "--no-commit", whole));
6928
+ const subject = `Kitman's ${revert ? "revert" : "cherry-pick"} of ${span.tip}`;
6929
+ const clean = isSuccess2(applied);
6930
+ const conflicted = (yield* git("diff", "--name-only", "-z", "--diff-filter=U")).split("\x00").filter(Boolean);
6931
+ if (!clean && conflicted.length === 0)
6932
+ return yield* failCause3(applied.cause);
6933
+ if (clean && (yield* nothingStaged(git)) || (yield* needsNothing(git, { span, whole, branch: before, revert, clean }))) {
6934
+ yield* backToHead(git);
6935
+ return already;
6936
+ }
6937
+ if (clean) {
6938
+ yield* git("commit", "--quiet", "--no-verify", ...author, "-m", message);
6939
+ const revision = (yield* git("rev-parse", "HEAD")).trim();
6940
+ return {
6941
+ kind: "applied",
6942
+ applied: { status: "applied", revision, clean: true }
6943
+ };
6944
+ }
6945
+ const marked = yield* markedPaths(worktree, git, conflicted);
6946
+ const unmarked = yield* unmarkedConflicts(worktree, conflicted, marked);
6947
+ const conflicts = [...marked.length === 0 ? [] : [`${list(marked)}: it holds conflict markers`], ...unmarked];
6948
+ return {
6949
+ kind: "conflict",
6950
+ conflicted,
6951
+ message,
6952
+ author,
6953
+ note: [
6954
+ `${subject}: it conflicts, and stays uncommitted until you answer.`,
6955
+ ...conflicts.map((conflict) => `- ${conflict}.`),
6956
+ "Answer applied and Kitman commits these files as you leave them, a file you deleted as deleted; answer conflict and Kitman puts the branch back as it was."
6444
6957
  ].join(`
6445
6958
  `)
6446
6959
  };
6447
6960
  });
6961
+ var concludeApply = (worktree, opened, answeredApplied) => gen(function* () {
6962
+ const git = (...args) => runCommand2("git", ["-C", worktree, ...gitIdentity, ...args]);
6963
+ const drop = backToHead(git);
6964
+ if (!answeredApplied) {
6965
+ yield* drop;
6966
+ return { kind: "dropped" };
6967
+ }
6968
+ yield* stageAll(worktree, git);
6969
+ const marked = yield* markedPaths(worktree, git, opened.conflicted, "--cached");
6970
+ if (marked.length > 0) {
6971
+ yield* drop;
6972
+ return {
6973
+ kind: "failed",
6974
+ reason: `The agent answered applied but left conflict markers in ${list(marked)}, so Kitman put the branch back as it was`
6975
+ };
6976
+ }
6977
+ if (yield* nothingStaged(git)) {
6978
+ yield* drop;
6979
+ return { kind: "already" };
6980
+ }
6981
+ yield* git("commit", "--quiet", "--no-verify", ...opened.author, "-m", opened.message);
6982
+ return { kind: "applied", revision: (yield* git("rev-parse", "HEAD")).trim() };
6983
+ });
6448
6984
  var concludeMerge = (worktree, conflicted, answeredMerged) => gen(function* () {
6449
6985
  const git = (...args) => runCommand2("git", ["-C", worktree, ...gitIdentity, ...args]);
6450
6986
  if (isFailure2(yield* exit(git("rev-parse", "--quiet", "--verify", "MERGE_HEAD"))))
@@ -6455,7 +6991,7 @@ var concludeMerge = (worktree, conflicted, answeredMerged) => gen(function* () {
6455
6991
  return;
6456
6992
  }
6457
6993
  yield* stageAll(worktree, git);
6458
- const marked = yield* markedPaths(git, conflicted, "--cached");
6994
+ const marked = yield* markedPaths(worktree, git, conflicted, "--cached");
6459
6995
  if (marked.length === 0) {
6460
6996
  yield* git("commit", "--no-edit");
6461
6997
  return;
@@ -6463,6 +6999,25 @@ var concludeMerge = (worktree, conflicted, answeredMerged) => gen(function* () {
6463
6999
  yield* abort;
6464
7000
  return `The agent answered merged but left conflict markers in ${list(marked)}, so Kitman aborted the merge`;
6465
7001
  });
7002
+ var afterMergeOutputLimit = 4000;
7003
+ var runAfterMerge = (work, worktree, targetCommit, command, run) => gen(function* () {
7004
+ const ran = run === undefined ? { exitCode: undefined, output: "This Runner cannot run it.", unstarted: true } : yield* run(work, worktree, command, [targetCommit]).pipe(catch_((error) => succeed6({ exitCode: undefined, output: error.message, unstarted: true })));
7005
+ if (ran.exitCode === 0)
7006
+ return;
7007
+ const git = (...gitArgs) => runCommand2("git", ["-C", worktree, ...gitArgs]);
7008
+ yield* git("reset", "--hard", "--quiet", "HEAD");
7009
+ yield* git("clean", "-d", "--force", "--quiet");
7010
+ const ended = "unstarted" in ran ? "it could not run" : ran.exitCode === undefined ? "it did not finish" : `it exited with ${ran.exitCode}`;
7011
+ const output = redactCredentials(ran.output.trimEnd()).slice(-afterMergeOutputLimit);
7012
+ return [
7013
+ `Kitman then ran the repository's after-merge command, ${afterMergeLine(command, targetCommit)}, and ${ended}, so Kitman put back what it changed. Its output ended:`,
7014
+ "```",
7015
+ output,
7016
+ "```",
7017
+ "Do what it could not, and leave the result in the workspace: Kitman commits it."
7018
+ ].join(`
7019
+ `);
7020
+ });
6466
7021
  var pushCheckpoint = (worktree, ref, previousTree, env) => gen(function* () {
6467
7022
  const fs = yield* FileSystem;
6468
7023
  const index = (yield* runCommand2("git", [
@@ -6499,13 +7054,19 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6499
7054
  const repoBinding = work.checkout === "none" ? undefined : work.repoBinding;
6500
7055
  const writable = work.checkout === "write" && repoBinding !== undefined;
6501
7056
  const merging = writable ? work.mergeTarget : undefined;
7057
+ const applying = writable ? work.applyChange : undefined;
6502
7058
  const adapter = harnessAdapter(work.brief.harness);
6503
7059
  const home = input.home ?? homedir3();
6504
7060
  const point = input.checkpoints === undefined ? undefined : yield* input.checkpoints.resume(work).pipe(catch_((error) => as(logWarning("runner_checkpoint_unavailable", error.message), undefined)));
6505
- const saved = point?.ref === undefined || point.revision === undefined || merging !== undefined ? undefined : { ref: point.ref, revision: point.revision };
7061
+ const saved = point?.ref === undefined || point.revision === undefined || merging !== undefined || applying !== undefined ? undefined : { ref: point.ref, revision: point.revision };
6506
7062
  const restored = repoBinding === undefined || saved === undefined ? undefined : yield* checkouts.checkout(work, repoBinding, saved).pipe(catch_((error) => as(logWarning("runner_checkpoint_not_restored", error.message), undefined)));
6507
7063
  const worktree = restored ?? (repoBinding === undefined ? yield* checkouts.scratch(work) : yield* checkouts.checkout(work, repoBinding));
6508
- const merge = merging === undefined ? undefined : yield* mergeTarget(worktree, merging);
7064
+ const merge = merging === undefined ? undefined : yield* mergeTarget(worktree, merging, work.afterMerge);
7065
+ const fetchCommit = (commit) => flatMap3(checkouts.transferEnv(repoBinding), (env) => runCommand2("git", ["-C", worktree, ...stallLimit, "fetch", "--quiet", "origin", commit], { ...transfer, env })).pipe(ignore);
7066
+ const applied = applying === undefined ? undefined : yield* applyChange(worktree, applying, fetchCommit);
7067
+ if (applied?.kind === "refused")
7068
+ return { status: "failed", failureSummary: applied.reason };
7069
+ let appliedChange = applied !== undefined && "applied" in applied ? applied.applied : undefined;
6509
7070
  const deliver = (branch, spent) => gen(function* () {
6510
7071
  const mergeCommit = merge === undefined ? undefined : (yield* runCommand2("git", ["-C", worktree, "rev-parse", "HEAD"])).trim();
6511
7072
  const revision = yield* pushWork(worktree, branch, work.stepKey, sharedBranch(work), yield* checkouts.transferEnv(repoBinding));
@@ -6525,13 +7086,19 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6525
7086
  ...catchUp === undefined ? undefined : { catchUp },
6526
7087
  ...merge === undefined ? undefined : { syncedTarget: merge.target },
6527
7088
  ...merge?.clean === undefined ? undefined : { cleanSync: merge.clean },
7089
+ ...appliedChange === undefined ? undefined : { appliedChange },
6528
7090
  ...spent
6529
7091
  };
6530
7092
  return completed;
6531
7093
  });
6532
- if (merge?.clean === "up_to_date" && work.branch !== undefined)
7094
+ const afterMergeFailed = merge?.clean === "merged" && work.afterMerge !== undefined ? yield* runAfterMerge(work, worktree, merge.target, work.afterMerge, input.runAfterMerge) : undefined;
7095
+ if (appliedChange !== undefined && work.branch !== undefined)
7096
+ return yield* deliver(work.branch);
7097
+ if (merge?.clean !== undefined && afterMergeFailed === undefined && work.branch !== undefined)
6533
7098
  return yield* deliver(work.branch);
6534
- const notes = [...work.resumeNotes ?? [], ...merge === undefined ? [] : [merge.note]];
7099
+ const mergeNote = merge === undefined ? [] : [afterMergeFailed === undefined ? merge.note : `${merge.note}
7100
+ ${afterMergeFailed}`];
7101
+ const notes = [...work.resumeNotes ?? [], ...mergeNote, ...applied?.kind === "conflict" ? [applied.note] : []];
6535
7102
  const configDir = yield* tempDirectoryScoped(yield* FileSystem, { prefix: "kitman-harness-" }).pipe(orDie);
6536
7103
  const backend = work.sandbox ?? (isFunction(input.sandbox) ? input.sandbox(work) : input.sandbox);
6537
7104
  const writableSessions = adapter === undefined ? undefined : worktreeSessionDirectory(adapter, home, worktree);
@@ -6644,7 +7211,7 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6644
7211
  ...refusal.until === undefined ? undefined : { until: refusal.until },
6645
7212
  ...backend === "docker" ? { scope: "step" } : undefined
6646
7213
  });
6647
- const outputSubmitted = input.heartbeat(work).pipe(option2, map8((state) => isSome(state) && state.value.outputSubmitted === true));
7214
+ const outputSubmitted = input.heartbeat(work).pipe(option2, map9((state) => isSome(state) && state.value.outputSubmitted === true));
6648
7215
  const providerRefused = relay === undefined ? never : gen(function* () {
6649
7216
  for (;; ) {
6650
7217
  yield* sleep("1 second");
@@ -6753,6 +7320,13 @@ var stepAttempt = (input, resending) => (work) => gen(function* () {
6753
7320
  const unmerged = merge === undefined ? undefined : yield* concludeMerge(worktree, merge.conflicted, state.outputMerged === true);
6754
7321
  if (unmerged !== undefined)
6755
7322
  return { status: "failed", failureSummary: unmerged, ...spent };
7323
+ const concluded = applied?.kind === "conflict" ? yield* concludeApply(worktree, applied, state.outputMerged === true) : undefined;
7324
+ if (concluded?.kind === "failed")
7325
+ return { status: "failed", failureSummary: concluded.reason, ...spent };
7326
+ if (concluded?.kind === "already")
7327
+ appliedChange = { status: "already" };
7328
+ if (concluded?.kind === "applied")
7329
+ appliedChange = { status: "applied", revision: concluded.revision, clean: false };
6756
7330
  return yield* deliver(work.branch, spent);
6757
7331
  }).pipe(scoped);
6758
7332
  var agentStepExecutor = (input) => stepAttempt(input, new Map);
@@ -6832,11 +7406,12 @@ function runnerStepAttemptFromAgentStep(work) {
6832
7406
 
6833
7407
  // packages/agent-runtime/src/sandbox-command.ts
6834
7408
  var runSandboxCommand = (input) => scoped(gen(function* () {
6835
- const { command } = input;
7409
+ const { command, secretRegistry } = input;
6836
7410
  const env = { ...input.policy.environment, ...command.env };
6837
7411
  if (input.backend === "srt") {
6838
- const { settingsFile } = yield* writeSrtSettings2(input.policy, input.unixSockets);
6839
- return yield* runProcess2(srtArgv2(input.srtCommand ?? pinnedSrtCommand2(), settingsFile, command.argv), {
7412
+ const { settingsFile } = yield* writeSrtSettings2(secretRegistry === undefined ? input.policy : { ...input.policy, readDeniedPaths: [...input.policy.readDeniedPaths, secretRegistry.directory] }, input.unixSockets);
7413
+ const argv = secretRegistry === undefined ? srtArgv2(input.srtCommand ?? pinnedSrtCommand2(), settingsFile, command.argv) : srtStepArgv2(input.srtStepCommand ?? pinnedSrtStepCommand2(), settingsFile, secretRegistry.file, command.argv);
7414
+ return yield* runProcess2(argv, {
6840
7415
  cwd: command.cwd,
6841
7416
  env,
6842
7417
  timeout: command.timeout,
@@ -6846,6 +7421,11 @@ var runSandboxCommand = (input) => scoped(gen(function* () {
6846
7421
  });
6847
7422
  }
6848
7423
  const configDir = yield* tempDirectoryScoped(yield* FileSystem, { prefix: "kitman-sandbox-" });
7424
+ const secretProxy = secretRegistry === undefined ? undefined : yield* startDockerSecretProxy({
7425
+ registryFile: secretRegistry.file,
7426
+ socket: dockerSecretProxySocket(secretRegistry.directory),
7427
+ network: input.policy.network
7428
+ });
6849
7429
  const { container } = yield* startDockerSandbox({
6850
7430
  docker: input.docker,
6851
7431
  runnerId: input.runnerId,
@@ -6854,7 +7434,8 @@ var runSandboxCommand = (input) => scoped(gen(function* () {
6854
7434
  workspace: command.cwd,
6855
7435
  configDir,
6856
7436
  ...input.readOnlyPaths === undefined ? undefined : { readOnlyPaths: input.readOnlyPaths },
6857
- ...input.services === undefined ? undefined : { services: input.services }
7437
+ ...input.services === undefined ? undefined : { services: input.services },
7438
+ ...secretProxy === undefined ? undefined : { secretProxy }
6858
7439
  });
6859
7440
  return yield* input.docker.containers.exec({
6860
7441
  container,
@@ -7447,7 +8028,7 @@ function composeAgentEnvironmentSyncPlan(targets) {
7447
8028
  }
7448
8029
  var updateHarness = (argv) => gen(function* () {
7449
8030
  const run = yield* CommandRunner2;
7450
- const failure = yield* run(argv).pipe(map8((result) => result.exitCode === 0 ? undefined : result.output.trim().split(`
8031
+ const failure = yield* run(argv).pipe(map9((result) => result.exitCode === 0 ? undefined : result.output.trim().split(`
7451
8032
  `).at(-1) ?? `exit code ${result.exitCode}`), catch_((error) => succeed6(error.message)));
7452
8033
  return failure === undefined ? [] : [`Kitman could not update ${argv[0]} with \`${argv.join(" ")}\`: ${failure}`];
7453
8034
  });
@@ -7460,10 +8041,10 @@ var applyAgentEnvironmentPlans = fnUntraced(function* (plan) {
7460
8041
  const updateWarnings = yield* forEach(plan.targets, (target) => target.harnessUpdater === undefined ? succeed6([]) : updateHarness(target.harnessUpdater));
7461
8042
  for (const target of plan.targets)
7462
8043
  yield* applyAgentEnvironmentConfigSync(target.harnessConfig).pipe(mapError2((cause) => new AgentEnvironmentPlanApplyError({ phase: "harness_config", cause })));
7463
- const targets = yield* forEach(plan.targets, (target, index) => map8(target.skills.codexHookTrust === undefined ? succeed6([]) : trustCodexPluginHooks({
8044
+ const targets = yield* forEach(plan.targets, (target, index) => map9(target.skills.codexHookTrust === undefined ? succeed6([]) : trustCodexPluginHooks({
7464
8045
  ...target.skills.codexHookTrust,
7465
8046
  plugins: target.skills.materializedPlugins.map((plugin) => plugin.name)
7466
- }), (trustWarnings) => [...updateWarnings[index] ?? [], ...trustWarnings]).pipe(map8((warnings) => ({
8047
+ }), (trustWarnings) => [...updateWarnings[index] ?? [], ...trustWarnings]).pipe(map9((warnings) => ({
7467
8048
  ...target,
7468
8049
  skills: { ...target.skills, warnings: [...target.skills.warnings, ...warnings.map((message) => ({ message }))] },
7469
8050
  warnings: [...target.warnings, ...warnings]
@@ -7551,7 +8132,7 @@ var programProcessExecutor = (input) => (work) => gen(function* () {
7551
8132
  storageOrigin: work.storageOrigin,
7552
8133
  network: work.network
7553
8134
  });
7554
- const inherited = (yield* forEach(inheritedEnv, (name) => map8(optionalEnv(name), (value) => value === undefined ? [] : [[name, value]]))).flat();
8135
+ const inherited = (yield* forEach(inheritedEnv, (name) => map9(optionalEnv(name), (value) => value === undefined ? [] : [[name, value]]))).flat();
7555
8136
  const programEnv = {
7556
8137
  BUN_BE_BUN: "1",
7557
8138
  KITMAN_LOOP_ID: program.loopId,
@@ -7642,9 +8223,9 @@ var statusOfExit = (exitCode, output) => {
7642
8223
  return "failed";
7643
8224
  }
7644
8225
  };
7645
- var executableAt = (checkout, revision) => map8(runCommand2("git", ["-C", checkout, "ls-tree", "--end-of-options", revision, "--", deployScript]), (listed) => listed.startsWith("100755 "));
8226
+ var executableAt = (checkout, revision) => map9(runCommand2("git", ["-C", checkout, "ls-tree", "--end-of-options", revision, "--", deployScript]), (listed) => listed.startsWith("100755 "));
7646
8227
  var tagCommit = (checkout, tagRef) => exit(runCommand2("git", ["-C", checkout, "rev-parse", "--verify", "--quiet", "--end-of-options", `${tagRef}^{commit}`]));
7647
- var headOf = (checkout) => map8(all3([
8228
+ var headOf = (checkout) => map9(all3([
7648
8229
  runCommand2("git", ["-C", checkout, "rev-parse", "HEAD"]),
7649
8230
  runCommand2("git", ["-C", checkout, "rev-parse", "HEAD^{tree}"])
7650
8231
  ]), ([revision, tree]) => ({ revision: revision.trim(), tree: tree.trim(), checks: [] }));
@@ -7701,6 +8282,148 @@ var deployTag = (work, deploy, checkouts, mayRun, timeout = deployTimeout) => ge
7701
8282
  return { ranAt: yield* headOf(checkout), deployed };
7702
8283
  });
7703
8284
 
8285
+ // packages/agent-runtime/src/tag-versions.ts
8286
+ var bumps = ["major", "minor", "patch"];
8287
+ var semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
8288
+ var compareVersions = (a, b) => Bun.semver.order(a, b);
8289
+ var versionOf = (tag, prefix) => {
8290
+ if (!tag.name.startsWith(prefix))
8291
+ return;
8292
+ const version = tag.name.slice(prefix.length);
8293
+ const parsed = semver.exec(version);
8294
+ if (parsed === null)
8295
+ return;
8296
+ return {
8297
+ tag,
8298
+ prefix,
8299
+ version,
8300
+ core: [Number(parsed[1]), Number(parsed[2]), Number(parsed[3])],
8301
+ prerelease: parsed[4]
8302
+ };
8303
+ };
8304
+ var latest = (versions) => versions.reduce((best, version) => best === undefined || compareVersions(version.version, best.version) > 0 ? version : best, undefined);
8305
+ var bumped = ([major, minor, patch] = [0, 0, 0], bump) => {
8306
+ switch (bump) {
8307
+ case "major":
8308
+ return `${major + 1}.0.0`;
8309
+ case "minor":
8310
+ return `${major}.${minor + 1}.0`;
8311
+ case "patch":
8312
+ return `${major}.${minor}.${patch + 1}`;
8313
+ }
8314
+ };
8315
+ var regexSpecial = /[.*+?^$()|[\]{}\\]/gu;
8316
+ var highestNumbered = (tags, stem) => {
8317
+ const numbered = new RegExp(`^${stem.replaceAll(regexSpecial, "\\$&")}(0|[1-9]\\d*)$`, "u");
8318
+ return tags.reduce((highest, tag) => {
8319
+ const number = numbered.exec(tag.name)?.[1];
8320
+ return number === undefined || highest !== undefined && highest >= Number(number) ? highest : Number(number);
8321
+ }, undefined);
8322
+ };
8323
+ var latestCalver = (tags, format, prefix) => tags.reduce((best, tag) => {
8324
+ if (!tag.name.startsWith(prefix))
8325
+ return best;
8326
+ const version = tag.name.slice(prefix.length);
8327
+ const numbers = calverNumbers(format, version);
8328
+ return numbers === undefined || best !== undefined && compareCalver(numbers, best.numbers) <= 0 ? best : { tag, version, numbers };
8329
+ }, undefined);
8330
+ var tagVersions = (revision, tags, spec) => {
8331
+ const prefixes = spec.prefix === undefined ? ["", "v"] : [spec.prefix];
8332
+ const versions = tags.flatMap((tag) => prefixes.flatMap((prefix) => {
8333
+ const version = versionOf(tag, prefix);
8334
+ return version === undefined ? [] : [version];
8335
+ }));
8336
+ const releases = versions.filter((version) => version.prerelease === undefined);
8337
+ const previous = latest(releases.filter((version) => version.tag.ancestor));
8338
+ const prefix = spec.prefix ?? previous?.prefix ?? latest(versions)?.prefix ?? "";
8339
+ const next = {};
8340
+ const taken = {};
8341
+ for (const bump of bumps) {
8342
+ const version = bumped(previous?.core, bump);
8343
+ const released = releases.find((release) => compareVersions(release.version, version) === 0);
8344
+ if (released !== undefined) {
8345
+ taken[bump] = released.tag.name;
8346
+ continue;
8347
+ }
8348
+ if (spec.prerelease === undefined) {
8349
+ next[bump] = `${prefix}${version}`;
8350
+ continue;
8351
+ }
8352
+ const stem = `${version}-${spec.prerelease}.`;
8353
+ const highest = Math.max(0, ...prefixes.map((counted) => highestNumbered(tags, `${counted}${stem}`) ?? 0));
8354
+ next[bump] = `${prefix}${stem}${highest + 1}`;
8355
+ }
8356
+ const seriesPrefix = spec.prefix ?? "";
8357
+ const calver = spec.calver;
8358
+ const before = calver === undefined ? previous : latestCalver(tags.filter((tag) => tag.ancestor), calver, seriesPrefix);
8359
+ const containedIn = calver === undefined ? latest(releases.filter((version) => version.tag.descendant === true)) : latestCalver(tags.filter((tag) => tag.descendant === true), calver, seriesPrefix);
8360
+ return {
8361
+ revision,
8362
+ ...before === undefined ? undefined : { previous: { tag: before.tag.name, version: before.version, revision: before.tag.commit } },
8363
+ ...containedIn === undefined ? undefined : {
8364
+ containedIn: { tag: containedIn.tag.name, version: containedIn.version, revision: containedIn.tag.commit }
8365
+ },
8366
+ ...spec.calver === undefined ? { next, ...Object.keys(taken).length === 0 ? undefined : { taken } } : { next: {} },
8367
+ ...spec.series === undefined ? undefined : {
8368
+ series: spec.series.map((series) => {
8369
+ const highest = highestNumbered(tags, `${seriesPrefix}${series}`);
8370
+ return highest === undefined ? { series } : { series, highest };
8371
+ })
8372
+ }
8373
+ };
8374
+ };
8375
+ var lines = (output) => output.split(`
8376
+ `).filter((line) => line !== "");
8377
+ var readTagVersions = (checkout, spec) => gen(function* () {
8378
+ const git = (...args) => runCommand2("git", ["-C", checkout, ...args]);
8379
+ const revision = (yield* git("rev-parse", "--verify", "--quiet", "--end-of-options", `${spec.revision}^{commit}`)).trim();
8380
+ const listed = lines(yield* git("for-each-ref", "--format=%(refname:strip=2) %(objectname) %(*objectname)", "refs/tags"));
8381
+ const reached = new Set(lines(yield* git("tag", "--merged", revision)));
8382
+ const containing = new Set(lines(yield* git("tag", "--contains", revision)));
8383
+ const tags = listed.flatMap((line) => {
8384
+ const [name, object, peeled] = line.split(" ");
8385
+ if (name === undefined || object === undefined)
8386
+ return [];
8387
+ const commit = peeled === undefined || peeled === "" ? object : peeled;
8388
+ return [{ name, commit, ancestor: reached.has(name), descendant: containing.has(name) && commit !== revision }];
8389
+ });
8390
+ return tagVersions(revision, tags, spec);
8391
+ });
8392
+
8393
+ // packages/agent-runtime/src/commit-history.ts
8394
+ class HistoryUnread extends TaggedError("HistoryUnread") {
8395
+ }
8396
+ var readCommitHistory = (checkout, spec, commitMax = compareCommitMax) => gen(function* () {
8397
+ const git = (...args) => map9(runCommand2("git", ["-C", checkout, ...args]), (out) => out.trim());
8398
+ const commitOf = (revision) => git("rev-parse", "--verify", "--quiet", "--end-of-options", `${revision}^{commit}`).pipe(mapError2(() => new HistoryUnread({ message: `\`${revision}\` names no commit` })));
8399
+ const base = yield* commitOf(spec.base);
8400
+ const head = yield* commitOf(spec.head);
8401
+ const mergeBase = yield* git("merge-base", base, head).pipe(mapError2(() => new HistoryUnread({ message: `\`${spec.base}\` and \`${spec.head}\` share no history` })));
8402
+ const differing = Number(yield* git("rev-list", "--count", `${base}...${head}`));
8403
+ if (differing > commitMax)
8404
+ return yield* new HistoryUnread({
8405
+ message: `\`${spec.base}\` and \`${spec.head}\` differ by ${differing.toLocaleString("en-US")} commits, more than the ${commitMax.toLocaleString("en-US")} a comparison reads`
8406
+ });
8407
+ const listed = (...args) => map9(git("rev-list", ...args), (out) => out === "" ? [] : out.split(`
8408
+ `));
8409
+ const messages = (range) => map9(git("log", "--topo-order", `--max-count=${commitMessageMax.count}`, "--format=%B%x00", range), (out) => out.split("\x00").map((message) => message.trim().slice(0, commitMessageMax.length)).slice(0, -1));
8410
+ const side = (from, to) => gen(function* () {
8411
+ const range = `${from}..${to}`;
8412
+ return {
8413
+ commits: yield* listed("--topo-order", range),
8414
+ firstParent: yield* listed("--first-parent", range),
8415
+ messages: yield* messages(range)
8416
+ };
8417
+ });
8418
+ return {
8419
+ base,
8420
+ head,
8421
+ mergeBase,
8422
+ ahead: yield* side(base, head),
8423
+ behind: yield* side(head, base)
8424
+ };
8425
+ });
8426
+
7704
8427
  // packages/agent-runtime/src/half-close-relay.ts
7705
8428
  import { once } from "events";
7706
8429
  import { connect as connect2, createServer as createServer2 } from "net";
@@ -7848,8 +8571,18 @@ var checkSandboxPolicy = (work, sandbox, checkout, cache, filesDir, postgresHost
7848
8571
  environment: srtCacheEnvironment2(cache)
7849
8572
  });
7850
8573
  var checkGitEnvironment = { GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0" };
7851
- var checkRunner = (work, sandbox, cache, inherited) => (checkout) => ({ command, cwd, filesDir, onOutput, postgres, docker }) => {
7852
- const env = { ...checkGitEnvironment, KITMAN_RUN_FILES_DIR: filesDir };
8574
+ var checkRunner = (work, sandbox, cache, inherited) => (checkout) => ({
8575
+ command,
8576
+ cwd,
8577
+ filesDir,
8578
+ env: added,
8579
+ timeout = checkTimeout,
8580
+ secretRegistry,
8581
+ onOutput,
8582
+ postgres,
8583
+ docker
8584
+ }) => {
8585
+ const env = { ...added, ...checkGitEnvironment, KITMAN_RUN_FILES_DIR: filesDir };
7853
8586
  const output = onOutput === undefined ? undefined : { onOutput };
7854
8587
  if (sandbox === undefined || sandbox.backend === undefined) {
7855
8588
  return runShell2(command, {
@@ -7860,7 +8593,7 @@ var checkRunner = (work, sandbox, cache, inherited) => (checkout) => ({ command,
7860
8593
  ...env,
7861
8594
  ...postgres === undefined ? undefined : { POSTGRES_URL: checkPostgresUrl(postgres, "127.0.0.1", postgres.hostPort) }
7862
8595
  },
7863
- timeout: checkTimeout,
8596
+ timeout,
7864
8597
  ...output
7865
8598
  });
7866
8599
  }
@@ -7878,7 +8611,7 @@ var checkRunner = (work, sandbox, cache, inherited) => (checkout) => ({ command,
7878
8611
  ...route.url === undefined ? undefined : { POSTGRES_URL: route.url },
7879
8612
  ...daemon.env
7880
8613
  },
7881
- timeout: checkTimeout,
8614
+ timeout,
7882
8615
  ...output
7883
8616
  };
7884
8617
  return sandbox.backend === "srt" ? runSandboxCommand({
@@ -7886,7 +8619,9 @@ var checkRunner = (work, sandbox, cache, inherited) => (checkout) => ({ command,
7886
8619
  policy,
7887
8620
  command: { ...sandboxCommand, env: { ...inherited, ...sandboxCommand.env }, extendEnv: false },
7888
8621
  unixSockets: [...route.unixSockets, ...daemon.unixSockets],
7889
- ...sandbox.srtCommand === undefined ? undefined : { srtCommand: sandbox.srtCommand }
8622
+ ...sandbox.srtCommand === undefined ? undefined : { srtCommand: sandbox.srtCommand },
8623
+ ...sandbox.srtStepCommand === undefined ? undefined : { srtStepCommand: sandbox.srtStepCommand },
8624
+ ...secretRegistry === undefined ? undefined : { secretRegistry }
7890
8625
  }) : runSandboxCommand({
7891
8626
  backend: "docker",
7892
8627
  docker: sandbox.docker,
@@ -7895,7 +8630,8 @@ var checkRunner = (work, sandbox, cache, inherited) => (checkout) => ({ command,
7895
8630
  readOnlyPaths: [repositoryClone(sandbox.runner.workRoot, work.repoBinding.id)],
7896
8631
  policy,
7897
8632
  command: sandboxCommand,
7898
- services: [...route.services, ...daemon.services]
8633
+ services: [...route.services, ...daemon.services],
8634
+ ...secretRegistry === undefined ? undefined : { secretRegistry }
7899
8635
  });
7900
8636
  };
7901
8637
  var regularFiles = (dir) => gen(function* () {
@@ -7915,7 +8651,7 @@ var redactedCopy = (from, to) => gen(function* () {
7915
8651
  var checkFileKeeper = (work, runFiles, storage) => {
7916
8652
  const files = rpcRunFiles(runFiles, programLease(work));
7917
8653
  let left = checkFilesPerVerification;
7918
- const keep = (name, path) => uploadRunFile(files, { step: work.stepKey, name, path }).pipe(provideService(HttpClient, storage), map8((file) => file.status === "available" ? [file.id] : []), catch_((error) => as(logWarning("check_run_file_not_kept", `${name}: ${error.message}`), [])));
8654
+ const keep = (name, path) => uploadRunFile(files, { step: work.stepKey, name, path }).pipe(provideService(HttpClient, storage), map9((file) => file.status === "available" ? [file.id] : []), catch_((error) => as(logWarning("check_run_file_not_kept", `${name}: ${error.message}`), [])));
7919
8655
  return (input) => gen(function* () {
7920
8656
  const path = yield* Path;
7921
8657
  const log = `${input.output}.log`;
@@ -7930,7 +8666,7 @@ var checkedTests = (filesDir, printed) => gen(function* () {
7930
8666
  const fs = yield* FileSystem;
7931
8667
  const path = yield* Path;
7932
8668
  const names = (yield* regularFiles(filesDir)).filter(isTestReportName);
7933
- const reports = yield* forEach(names, (name) => fs.readFileString(path.join(filesDir, name)).pipe(map8((text) => [text]), orElseSucceed(() => [])));
8669
+ const reports = yield* forEach(names, (name) => fs.readFileString(path.join(filesDir, name)).pipe(map9((text) => [text]), orElseSucceed(() => [])));
7934
8670
  return { tests: checkTests(reports.flat(), printed), statuses: testOutcomes(reports.flat()) };
7935
8671
  }).pipe(orElseSucceed(() => ({ tests: checkTests([], printed), statuses: testOutcomes([]) })));
7936
8672
 
@@ -8073,7 +8809,7 @@ var unresolvedDependencies = (worktree) => gen(function* () {
8073
8809
  }).pipe(orElseSucceed(() => {
8074
8810
  return;
8075
8811
  }));
8076
- const manifestAt = (dir) => fs.readFileString(path.join(dir, "package.json")).pipe(map8((text) => getOrUndefined(decodeJsonStringOption(text))), orElseSucceed(() => {
8812
+ const manifestAt = (dir) => fs.readFileString(path.join(dir, "package.json")).pipe(map9((text) => getOrUndefined(decodeJsonStringOption(text))), orElseSucceed(() => {
8077
8813
  return;
8078
8814
  }));
8079
8815
  const unresolved = [];
@@ -8360,7 +9096,7 @@ var measureRevisions = (work, measure, checkouts, runIn) => gen(function* () {
8360
9096
  }
8361
9097
  return {
8362
9098
  measured: {
8363
- head: { revision: work.revision, tree: yield* treeOf(head), checks: [] },
9099
+ head: { revision: work.revision, tree: yield* treeOf2(head), checks: [] },
8364
9100
  measurement: {
8365
9101
  base: taken.base,
8366
9102
  head: taken.head,
@@ -8417,7 +9153,7 @@ var resolveRevisions = (work, revisions, checkouts) => gen(function* () {
8417
9153
  evidence: {
8418
9154
  head: {
8419
9155
  revision: (yield* runCommand2("git", ["-C", checkout, "rev-parse", "HEAD"])).trim(),
8420
- tree: yield* treeOf(checkout),
9156
+ tree: yield* treeOf2(checkout),
8421
9157
  checks: []
8422
9158
  },
8423
9159
  resolved: { commits }
@@ -8425,7 +9161,240 @@ var resolveRevisions = (work, revisions, checkouts) => gen(function* () {
8425
9161
  };
8426
9162
  return resolved;
8427
9163
  });
8428
- var treeOf = (worktree) => map8(runCommand2("git", ["-C", worktree, "rev-parse", "HEAD^{tree}"]), (tree) => tree.trim());
9164
+ var checkoutWithTags = (work, checkouts) => gen(function* () {
9165
+ const checkout = yield* checkouts.checkout({ runId: work.runId, id: work.id, baseRevision: work.revision }, work.repoBinding);
9166
+ yield* runCommand2("git", ["-C", checkout, "fetch", "--quiet", "--force", "--prune", "origin", "+refs/tags/*:refs/tags/*"], {
9167
+ env: yield* checkouts.transferEnv(work.repoBinding),
9168
+ timeout: "5 minutes"
9169
+ });
9170
+ const completed = (evidence) => gen(function* () {
9171
+ const outcome = {
9172
+ status: "completed",
9173
+ evidence: {
9174
+ head: {
9175
+ revision: (yield* runCommand2("git", ["-C", checkout, "rev-parse", "HEAD"])).trim(),
9176
+ tree: yield* treeOf2(checkout),
9177
+ checks: []
9178
+ },
9179
+ ...evidence
9180
+ }
9181
+ };
9182
+ return outcome;
9183
+ });
9184
+ return { checkout, completed };
9185
+ });
9186
+ var readVersions = (work, spec, checkouts) => gen(function* () {
9187
+ const { checkout, completed } = yield* checkoutWithTags(work, checkouts);
9188
+ const read = yield* exit(readTagVersions(checkout, { ...spec, revision: spec.revision ?? work.revision }));
9189
+ if (isFailure2(read)) {
9190
+ const unread = {
9191
+ status: "failed",
9192
+ failureSummary: `\`${spec.revision ?? work.revision}\` names no commit in ${work.repoBinding.id}'s clone, or its tags could not be read`
9193
+ };
9194
+ return unread;
9195
+ }
9196
+ return yield* completed({ versions: read.value });
9197
+ });
9198
+ var compareRevisions = (work, spec, checkouts) => gen(function* () {
9199
+ const { checkout, completed } = yield* checkoutWithTags(work, checkouts);
9200
+ const read = yield* readCommitHistory(checkout, spec).pipe(map9((history) => ({ history })), catchTag("HistoryUnread", (error) => succeed6({ unread: error.message })));
9201
+ if ("unread" in read) {
9202
+ const unread = {
9203
+ status: "failed",
9204
+ failureSummary: `Cannot compare \`${spec.base}\` with \`${spec.head}\` in ${work.repoBinding.id}'s clone: ${read.unread}`
9205
+ };
9206
+ return unread;
9207
+ }
9208
+ return yield* completed({ history: read.history });
9209
+ });
9210
+ var redactionMarker = "[REDACTED:secret]";
9211
+ var longestFirst = (values) => values.filter((value) => value.length > 0).sort((left, right) => right.length - left.length);
9212
+ var replacingSecrets = (values) => {
9213
+ const ordered = longestFirst(values);
9214
+ return (text) => ordered.reduce((redacted, value) => redacted.replaceAll(value, redactionMarker), text);
9215
+ };
9216
+ var redactedWith = (values) => {
9217
+ const replaced = replacingSecrets(values);
9218
+ return (text) => redactCredentials(replaced(text));
9219
+ };
9220
+ var redactingSecrets = (values) => {
9221
+ const replaced = replacingSecrets(values);
9222
+ const held = Math.max(0, (longestFirst(values)[0]?.length ?? 0) - 1);
9223
+ return (stream) => stream.pipe(mapAccum(() => "", (carry, chunk) => {
9224
+ const text = replaced(carry + chunk);
9225
+ const cut = Math.max(0, text.length - held);
9226
+ return [text.slice(cut), cut === 0 ? [] : [text.slice(0, cut)]];
9227
+ }, { onHalt: (carry) => carry === "" ? [] : [carry] }));
9228
+ };
9229
+ var commandScript = (command, args) => ({
9230
+ script: [command, ...args.map((_, index) => `"$KITMAN_COMMAND_ARG_${index + 1}"`)].join(" "),
9231
+ env: Object.fromEntries(args.map((arg, index) => [`KITMAN_COMMAND_ARG_${index + 1}`, arg]))
9232
+ });
9233
+
9234
+ class AfterMergeUnrun extends TaggedError("AfterMergeUnrun") {
9235
+ }
9236
+ var untrackedFiles = (worktree) => map9(runCommand2("git", ["-C", worktree, "ls-files", "-z", "--others", "--exclude-standard"]), (listed) => listed.split("\x00").filter(Boolean));
9237
+ var removeUntracked = (worktree, files) => forEach(chunksOf(files, 200), (some) => runCommand2("git", [
9238
+ "-C",
9239
+ worktree,
9240
+ "clean",
9241
+ "--force",
9242
+ "--force",
9243
+ "-d",
9244
+ "--quiet",
9245
+ "--",
9246
+ ...some.map((file) => `:(literal,top)${file}`)
9247
+ ]), { discard: true });
9248
+ var afterMergeRunner = (sandbox) => (work, worktree, command, args) => gen(function* () {
9249
+ const { repoBinding } = work;
9250
+ if (repoBinding === undefined)
9251
+ return yield* new AfterMergeUnrun({ message: "The Step has no repository" });
9252
+ if (sandbox !== undefined && sandbox.backend === undefined)
9253
+ return yield* new AfterMergeUnrun({ message: "A shared Runner runs commands only in `srt` or `docker`." });
9254
+ const fs = yield* FileSystem;
9255
+ const path = yield* Path;
9256
+ const cache = yield* tempDirectoryScoped(fs, { prefix: "kitman-after-merge-cache-" });
9257
+ const filesDir = yield* tempDirectoryScoped(fs, { prefix: "kitman-after-merge-files-" });
9258
+ const inherited = yield* inheritedEnvironment2(srtInheritedEnv2);
9259
+ const run = checkRunner({
9260
+ id: work.id,
9261
+ repoBinding,
9262
+ ...work.storageOrigin === undefined ? undefined : { storageOrigin: work.storageOrigin },
9263
+ ...work.hosts === undefined ? undefined : { hosts: work.hosts }
9264
+ }, sandbox, cache, inherited)(worktree);
9265
+ yield* installIn(worktree, run);
9266
+ yield* runCommand2("git", ["-C", worktree, "reset", "--hard", "--quiet", "HEAD"]);
9267
+ const installed = yield* untrackedFiles(worktree);
9268
+ const { script, env } = commandScript(command.command, args);
9269
+ const ran = yield* run({
9270
+ command: script,
9271
+ cwd: path.join(worktree, command.workingDirectory ?? "."),
9272
+ filesDir,
9273
+ env,
9274
+ timeout: millis(commandTimeoutMillisDefault)
9275
+ });
9276
+ const left = new Set(yield* untrackedFiles(worktree));
9277
+ yield* removeUntracked(worktree, installed.filter((file) => left.has(file)));
9278
+ return ran;
9279
+ }).pipe(scoped, mapError2((error) => error instanceof AfterMergeUnrun ? error : new AfterMergeUnrun({ message: error.message })));
9280
+ var interpreterInlineOptions = new Map([
9281
+ ...["sh", "bash", "zsh", "dash"].map((shell) => [shell, ["-c"]]),
9282
+ ...["node", "bun", "deno", "tsx"].map((runtime) => [
9283
+ runtime,
9284
+ ["-e", "--eval", "-p", "--print"]
9285
+ ]),
9286
+ ...["python", "python3"].map((python) => [python, ["-c", "-m"]]),
9287
+ ...["ruby", "perl"].map((interpreter) => [interpreter, ["-e", "-E"]])
9288
+ ]);
9289
+ var commandFile = (command) => {
9290
+ const words = command.trim().split(/\s+/u);
9291
+ const start = words.findIndex((word) => !/^[A-Za-z_][A-Za-z0-9_]*=/u.test(word));
9292
+ const [program, ...args] = start === -1 ? [] : words.slice(start);
9293
+ if (program === undefined || program === "")
9294
+ return;
9295
+ if (program.includes("/"))
9296
+ return program;
9297
+ const inline = interpreterInlineOptions.get(program);
9298
+ if (inline === undefined)
9299
+ return;
9300
+ const operands = (program === "bun" || program === "deno") && args[0] === "run" ? args.slice(1) : args;
9301
+ const operand = operands.find((word) => inline.includes(word) || !word.startsWith("-"));
9302
+ return operand === undefined || inline.includes(operand) || !/[/.]/u.test(operand) ? undefined : operand;
9303
+ };
9304
+ var watchRevocations = (work, command, registry, revocations) => {
9305
+ const held = Object.entries(command.secretDestinations ?? {}).flatMap(([name, destination]) => command.secretValues?.[name] === undefined ? [] : [{ name, version: destination.version }]);
9306
+ return forkScoped(forever(sleep(revocations.every).pipe(andThen2(revocations.revoked(work, held)), flatMap3(registry.revoke), tap2((revoked) => revoked.length === 0 ? void_3 : logWarning("secret_references_revoked", revoked.join(", "))), catch_((error) => logWarning("secret_revocation_unchecked", error.message)))));
9307
+ };
9308
+ var commandRan = (ran) => ran;
9309
+ var commandFileFound = (command, checkout) => gen(function* () {
9310
+ const fs = yield* FileSystem;
9311
+ const path = yield* Path;
9312
+ const file = commandFile(command.command);
9313
+ if (file === undefined)
9314
+ return true;
9315
+ return yield* fs.exists(path.resolve(path.join(checkout, command.workingDirectory ?? "."), file)).pipe(orElseSucceed(() => false));
9316
+ });
9317
+ var notStarted = (run) => (error) => succeed6({ failed: redactCredentials(`${run} could not be set up to run: ${error.message}`) });
9318
+ var runApprovedCommand = (work, command, checkout, sandboxed, run, runFiles, revocations) => gen(function* () {
9319
+ const fs = yield* FileSystem;
9320
+ const path = yield* Path;
9321
+ const secretValues = command.secretValues ?? {};
9322
+ const prepared = yield* gen(function* () {
9323
+ const cwd = path.join(checkout, command.workingDirectory ?? ".");
9324
+ if (!(yield* commandFileFound(command, checkout)))
9325
+ return commandRan({ result: { status: "missing" } });
9326
+ const bound = yield* result(requireSecretHosts(secretValues, command.secretDestinations));
9327
+ if (isFailure(bound))
9328
+ return commandRan({ failed: bound.failure.summary });
9329
+ const referenced = sandboxed ? secretReferences(secretValues, command.secretDestinations ?? {}) : undefined;
9330
+ const registry = referenced === undefined || Object.keys(referenced.registry).length === 0 ? undefined : yield* stepSecretRegistry(path.join(yield* tempDirectoryScoped(fs, { prefix: "kitman-command-secrets-" }), "registry"), referenced.registry, referenced.references);
9331
+ if (registry !== undefined && revocations !== undefined)
9332
+ yield* watchRevocations(work, command, registry, revocations);
9333
+ const filesDir = yield* tempDirectoryScoped(fs, { prefix: "kitman-command-files-" });
9334
+ const output = path.join(yield* tempDirectoryScoped(fs, { prefix: "kitman-command-output-" }), "output");
9335
+ return {
9336
+ cwd,
9337
+ filesDir,
9338
+ output,
9339
+ sink: yield* fs.open(output, { flag: "w" }),
9340
+ secretEnv: referenced?.references ?? secretValues,
9341
+ ...registry === undefined ? undefined : { secretRegistry: { file: registry.file, directory: registry.directory } }
9342
+ };
9343
+ }).pipe(catch_(notStarted(command.run)));
9344
+ if ("result" in prepared || "failed" in prepared)
9345
+ return prepared;
9346
+ const { cwd, filesDir, output, sink, secretEnv, secretRegistry } = prepared;
9347
+ const redact = redactedWith(Object.values(secretValues));
9348
+ const { script, env } = commandScript(command.command, command.args ?? []);
9349
+ const timeoutMillis = command.timeoutMillis ?? commandTimeoutMillisDefault;
9350
+ const startedAt = yield* currentTimeMillis;
9351
+ const ran = yield* run({
9352
+ command: script,
9353
+ cwd,
9354
+ filesDir,
9355
+ env: { ...command.env, ...secretEnv, ...env },
9356
+ timeout: millis(timeoutMillis),
9357
+ ...secretRegistry === undefined ? undefined : { secretRegistry },
9358
+ onOutput: (chunk) => sink.writeAll(chunk)
9359
+ });
9360
+ const durationMs = (yield* currentTimeMillis) - startedAt;
9361
+ const logFileId = runFiles === undefined ? undefined : yield* keepCommandLog(work, runFiles, output, Object.values(secretValues));
9362
+ if (ran.exitCode === undefined)
9363
+ return commandRan({
9364
+ failed: `${command.run} did not exit within ${format2(millis(timeoutMillis))}`
9365
+ });
9366
+ const redacted = redact(ran.output);
9367
+ return commandRan({
9368
+ result: {
9369
+ status: "exited",
9370
+ exitCode: ran.exitCode,
9371
+ lastLine: (redacted.trimEnd().split(`
9372
+ `).at(-1) ?? "").slice(-commandTextLimit),
9373
+ outputTail: redacted.slice(-commandTextLimit),
9374
+ durationMs,
9375
+ ...logFileId === undefined ? undefined : { logFileId }
9376
+ }
9377
+ });
9378
+ }).pipe(scoped);
9379
+ var keepCommandLog = (work, runFiles, output, secretValues) => gen(function* () {
9380
+ const fs = yield* FileSystem;
9381
+ const log = `${output}.log`;
9382
+ yield* fs.stream(output).pipe(decodeText, redactingSecrets(secretValues), splitLines, map2((line) => `${redactCredentials(line)}
9383
+ `), encodeText, run(fs.sink(log)));
9384
+ const file = yield* uploadRunFile(rpcRunFiles(runFiles.client, programLease(work)), {
9385
+ step: work.stepKey,
9386
+ name: `${work.stepKey}.log`,
9387
+ path: log
9388
+ }).pipe(provideService(HttpClient, runFiles.storage));
9389
+ return file.status === "available" ? file.id : undefined;
9390
+ }).pipe(catch_((error) => as(logWarning("command_log_not_kept", `${work.stepKey}: ${error.message}`), undefined)));
9391
+ var pushCommandChange = (checkouts, work, worktree, branch) => gen(function* () {
9392
+ const changed = (yield* runCommand2("git", ["-C", worktree, "status", "--porcelain"])).trim() !== "";
9393
+ if (!changed)
9394
+ return;
9395
+ return yield* pushWork(worktree, branch, work.stepKey, true, yield* checkouts.transferEnv(work.repoBinding));
9396
+ });
9397
+ var treeOf2 = (worktree) => map9(runCommand2("git", ["-C", worktree, "rev-parse", "HEAD^{tree}"]), (tree) => tree.trim());
8429
9398
  var verificationExecutor = (input) => (work) => gen(function* () {
8430
9399
  if (input.sandbox !== undefined && input.sandbox.backend === undefined)
8431
9400
  return {
@@ -8437,6 +9406,10 @@ var verificationExecutor = (input) => (work) => gen(function* () {
8437
9406
  const checkouts = runCheckouts(input.rootDir, input.gitCredentials);
8438
9407
  if (work.resolve !== undefined)
8439
9408
  return yield* resolveRevisions(work, work.resolve.revisions, checkouts);
9409
+ if (work.versions !== undefined)
9410
+ return yield* readVersions(work, work.versions, checkouts);
9411
+ if (work.compare !== undefined)
9412
+ return yield* compareRevisions(work, work.compare, checkouts);
8440
9413
  if (work.deploy !== undefined) {
8441
9414
  const ran = yield* deployTag(work, work.deploy, checkouts, input.runsDeployScripts === true && work.deploy.runsScript === true, input.deployTimeout);
8442
9415
  if ("failed" in ran)
@@ -8446,6 +9419,39 @@ var verificationExecutor = (input) => (work) => gen(function* () {
8446
9419
  evidence: "found" in ran ? { head: ran.ranAt, deployScriptFound: true } : { head: ran.ranAt, deployed: ran.deployed }
8447
9420
  };
8448
9421
  }
9422
+ if (work.command !== undefined) {
9423
+ const { command } = work;
9424
+ const checkedOut = yield* checkouts.checkout({ runId: work.runId, id: work.id, baseRevision: work.revision }, work.repoBinding).pipe(flatMap3((head) => map9(all3([runCommand2("git", ["-C", head, "rev-parse", "HEAD"]), treeOf2(head)]), ([revision, tree]) => ({ head, ranAt: { revision: revision.trim(), tree, checks: [] } }))), map9((checkout) => ({ checkout })), catch_(notStarted(command.run)));
9425
+ if ("failed" in checkedOut)
9426
+ return { status: "failed", failureSummary: checkedOut.failed };
9427
+ const { head, ranAt } = checkedOut.checkout;
9428
+ if (command.findsOnly === true)
9429
+ return {
9430
+ status: "completed",
9431
+ evidence: (yield* commandFileFound(command, head)) ? { head: ranAt, deployScriptFound: true } : { head: ranAt, commanded: { status: "missing" } }
9432
+ };
9433
+ const sandboxed = input.sandbox?.backend !== undefined;
9434
+ const revocations = input.revokedSecrets === undefined ? undefined : { revoked: input.revokedSecrets, every: input.revocationEvery ?? "30 seconds" };
9435
+ const commanded = yield* runApprovedCommand(work, command, head, sandboxed, runIn(head), input.runFiles, revocations);
9436
+ if ("failed" in commanded)
9437
+ return { status: "failed", failureSummary: commanded.failed };
9438
+ const pushed = command.branch === undefined || commanded.result.status !== "exited" || commanded.result.exitCode !== 0 ? undefined : yield* result(pushCommandChange(checkouts, work, head, command.branch));
9439
+ if (pushed !== undefined && isFailure(pushed))
9440
+ return {
9441
+ status: "failed",
9442
+ failureSummary: redactCredentials(`What ${command.run} changed could not be pushed to ${command.branch}: ${pushed.failure.message}`)
9443
+ };
9444
+ const boundary = pushed?.success === undefined || command.runBase === undefined ? undefined : yield* runChange(head, command.runBase).pipe(catch_((error) => as(logWarning("runner_boundary_unread", error.message), undefined)));
9445
+ return {
9446
+ status: "completed",
9447
+ evidence: {
9448
+ head: ranAt,
9449
+ commanded: commanded.result,
9450
+ ...pushed?.success === undefined ? undefined : { pushed: pushed.success },
9451
+ ...boundary === undefined ? undefined : { boundary }
9452
+ }
9453
+ };
9454
+ }
8449
9455
  if (work.measure !== undefined) {
8450
9456
  const measured = yield* measureRevisions(work, work.measure, checkouts, runIn);
8451
9457
  const outcome = "failed" in measured ? { status: "failed", failureSummary: measured.failed } : { status: "completed", evidence: measured.measured };
@@ -8463,8 +9469,8 @@ var verificationExecutor = (input) => (work) => gen(function* () {
8463
9469
  const baseline = pipelineOnly ? head : yield* baselineAt(work.baseline).pipe(catch_(() => baselineAt()));
8464
9470
  if (work.checks.some((check) => check.pipeline === true))
8465
9471
  yield* ownRepository(head, repositoryClone(input.rootDir, work.repoBinding.id), work.repoBinding.defaultTargetBranch);
8466
- const headTree = yield* treeOf(head);
8467
- const baselineTree = yield* treeOf(baseline);
9472
+ const headTree = yield* treeOf2(head);
9473
+ const baselineTree = yield* treeOf2(baseline);
8468
9474
  const trees = headTree === baselineTree ? [headTree] : [headTree, baselineTree];
8469
9475
  const known = yield* input.known(work, trees);
8470
9476
  const sandbox = input.sandbox;
@@ -8527,12 +9533,17 @@ var verificationExecutor = (input) => (work) => gen(function* () {
8527
9533
  }).pipe(catchTags({
8528
9534
  InstallFailed: (error) => succeed6({ status: "failed", failureSummary: error.message }),
8529
9535
  ServicesUnavailable: (error) => succeed6({ status: "failed", failureSummary: error.message })
8530
- }), scoped);
9536
+ }), catch_((error) => work.command === undefined ? fail7(error) : succeed6({
9537
+ status: "failed",
9538
+ failureSummary: redactCommandError(work.command, error.message)
9539
+ })), scoped);
9540
+ var redactCommandError = (command, message) => redactedWith(Object.values(command.secretValues ?? {}))(`${command.run} failed on its Runner: ${message}`);
8531
9541
  var rpcKnownEvidence = (rpc) => (work, trees) => rpc.knownEvidence({ lease: programLease(work), trees: [...trees] });
8532
9542
 
8533
9543
  // packages/agent-runtime/src/index.ts
8534
9544
  var AgentRuntimePackageName = "@kitman/agent-runtime";
8535
9545
  export {
9546
+ AfterMergeUnrun,
8536
9547
  AgentBackend,
8537
9548
  AgentBackendRefusal,
8538
9549
  AgentEnvironmentConfigSyncError,
@@ -8569,6 +9580,7 @@ export {
8569
9580
  StepAttemptLabel,
8570
9581
  StepProcesses,
8571
9582
  afterFreshService,
9583
+ afterMergeRunner,
8572
9584
  agentStepExecutionLimit,
8573
9585
  agentStepExecutor,
8574
9586
  agentStepSandboxPolicy,
@@ -8591,7 +9603,9 @@ export {
8591
9603
  checkRegistryCacheVolume,
8592
9604
  checkRegistryMirrorArgs,
8593
9605
  clearSettledCheckpoints,
9606
+ commandFile,
8594
9607
  commandHostProbe,
9608
+ commandScript,
8595
9609
  compiled2 as compiled,
8596
9610
  composeAgentEnvironmentSyncPlan,
8597
9611
  controlFailureKind,
@@ -8656,7 +9670,10 @@ export {
8656
9670
  providerKeyHosts,
8657
9671
  psProcessTable,
8658
9672
  publishedPort,
9673
+ pushWork,
8659
9674
  readManifestSkillPaths2 as readManifestSkillPaths,
9675
+ redactedWith,
9676
+ redactingSecrets,
8660
9677
  refuseAgentRequest,
8661
9678
  removeCheckDocker,
8662
9679
  removeCheckPostgres,
@@ -8670,6 +9687,7 @@ export {
8670
9687
  resolveHarnessLaunch,
8671
9688
  rpcKnownEvidence,
8672
9689
  rpcStepCheckpoints,
9690
+ runChange,
8673
9691
  runCheckouts,
8674
9692
  runCommand2 as runCommand,
8675
9693
  runProcess2 as runProcess,