@compivia/runner-platform 0.0.35 → 0.0.36

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 (2) hide show
  1. package/dist/bin.mjs +1309 -254
  2. package/package.json +2 -2
package/dist/bin.mjs CHANGED
@@ -2276,7 +2276,7 @@ var require_websocket = __commonJS({
2276
2276
  var http = __require("http");
2277
2277
  var net = __require("net");
2278
2278
  var tls = __require("tls");
2279
- var { randomBytes: randomBytes2, createHash: createHash6 } = __require("crypto");
2279
+ var { randomBytes: randomBytes2, createHash: createHash7 } = __require("crypto");
2280
2280
  var { Duplex, Readable } = __require("stream");
2281
2281
  var { URL: URL2 } = __require("url");
2282
2282
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -2957,7 +2957,7 @@ var require_websocket = __commonJS({
2957
2957
  abortHandshake(websocket, socket, "Invalid Upgrade header");
2958
2958
  return;
2959
2959
  }
2960
- const digest = createHash6("sha1").update(key + GUID).digest("base64");
2960
+ const digest = createHash7("sha1").update(key + GUID).digest("base64");
2961
2961
  if (res.headers["sec-websocket-accept"] !== digest) {
2962
2962
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2963
2963
  return;
@@ -3326,7 +3326,7 @@ var require_websocket_server = __commonJS({
3326
3326
  var EventEmitter = __require("events");
3327
3327
  var http = __require("http");
3328
3328
  var { Duplex } = __require("stream");
3329
- var { createHash: createHash6 } = __require("crypto");
3329
+ var { createHash: createHash7 } = __require("crypto");
3330
3330
  var extension2 = require_extension();
3331
3331
  var PerMessageDeflate2 = require_permessage_deflate();
3332
3332
  var subprotocol2 = require_subprotocol();
@@ -3633,7 +3633,7 @@ var require_websocket_server = __commonJS({
3633
3633
  );
3634
3634
  }
3635
3635
  if (this._state > RUNNING) return abortHandshake(socket, 503);
3636
- const digest = createHash6("sha1").update(key + GUID).digest("base64");
3636
+ const digest = createHash7("sha1").update(key + GUID).digest("base64");
3637
3637
  const headers = [
3638
3638
  "HTTP/1.1 101 Switching Protocols",
3639
3639
  "Upgrade: websocket",
@@ -6151,6 +6151,7 @@ function serialize(value, level, depth) {
6151
6151
  var LEVEL_ORDER = { trace: 0, debug: 1, info: 2, warn: 3, error: 4 };
6152
6152
  var LEVELS = new Set(Object.keys(LEVEL_ORDER));
6153
6153
  var KEY_WORKTREE_ID = "worktree_id";
6154
+ var KEY_ENV_KEY_COUNT = "env_key_count";
6154
6155
  var PROTECTED_KEYS = /* @__PURE__ */ new Set(["ts", "level", "msg", "component"]);
6155
6156
  function resolveLogLevel(raw) {
6156
6157
  if (raw === void 0) return "info";
@@ -6407,11 +6408,13 @@ function validateHelloAck(payload) {
6407
6408
  const { protocolVersion, engineEpoch, ackedSeq } = record;
6408
6409
  if (!isCounter(protocolVersion, 1) || !isCounter(engineEpoch, 1) || !isCounter(ackedSeq, 0)) return null;
6409
6410
  if (typeof record.engineVersion !== "string" || record.engineVersion === "") return null;
6411
+ const { fingerprintSalt } = record;
6410
6412
  return {
6411
6413
  protocolVersion,
6412
6414
  engineVersion: record.engineVersion,
6413
6415
  engineEpoch,
6414
- ackedSeq
6416
+ ackedSeq,
6417
+ ...typeof fingerprintSalt === "string" && fingerprintSalt !== "" && fingerprintSalt.length <= 128 ? { fingerprintSalt } : {}
6415
6418
  };
6416
6419
  }
6417
6420
  function isCounter(value, min) {
@@ -7762,18 +7765,18 @@ function logSafe(logger, level, msg, fields) {
7762
7765
  var REPOSITORY_PATTERN = /^[^/\s]+\/[^/\s]+$/;
7763
7766
  function repoCommandHandlers(service, hooks, logger = noopLogger) {
7764
7767
  const mutate = hooks?.mutate ?? ((operation) => operation());
7765
- const invalid = (field) => {
7768
+ const invalid2 = (field) => {
7766
7769
  logSafe(logger, "warn", "repo command rejected: bad params", { field, reason: "bad_params" });
7767
7770
  throw new CommandRejection("invalid", { reason: "bad_params" });
7768
7771
  };
7769
7772
  const repositoryParam = (params) => {
7770
7773
  const value = params["repository"];
7771
- if (typeof value !== "string" || !REPOSITORY_PATTERN.test(value)) return invalid("repository");
7774
+ if (typeof value !== "string" || !REPOSITORY_PATTERN.test(value)) return invalid2("repository");
7772
7775
  return value;
7773
7776
  };
7774
7777
  const pathParam = (params) => {
7775
7778
  const value = params["path"];
7776
- if (typeof value !== "string" || value === "" || !isAbsolute(value)) return invalid("path");
7779
+ if (typeof value !== "string" || value === "" || !isAbsolute(value)) return invalid2("path");
7777
7780
  return value;
7778
7781
  };
7779
7782
  return {
@@ -7916,7 +7919,7 @@ function isTurnCursor(value) {
7916
7919
  return value.fingerprint === null || typeof value.fingerprint === "string";
7917
7920
  }
7918
7921
  function agentCommandHandlers(service, logger = noopLogger) {
7919
- const invalid = (reason, fields = {}, msg = "agent command rejected: invalid params") => {
7922
+ const invalid2 = (reason, fields = {}, msg = "agent command rejected: invalid params") => {
7920
7923
  logSafe2(logger, "warn", msg, { reason, ...fields });
7921
7924
  return new CommandRejection("invalid", { reason });
7922
7925
  };
@@ -7930,13 +7933,13 @@ function agentCommandHandlers(service, logger = noopLogger) {
7930
7933
  "agent.final": async (params) => {
7931
7934
  const value = isRecord(params) ? params : {};
7932
7935
  if (typeof value.harness !== "string" || typeof value.sessionId !== "string") {
7933
- throw invalid("final_params_required", {
7936
+ throw invalid2("final_params_required", {
7934
7937
  harness_present: typeof value.harness === "string",
7935
7938
  session_id_present: typeof value.sessionId === "string"
7936
7939
  }, "agent.final rejected: invalid params");
7937
7940
  }
7938
7941
  if (value.turnCursor !== void 0 && !isTurnCursor(value.turnCursor)) {
7939
- throw invalid("invalid_turn_cursor", {}, "agent.final rejected: invalid turn cursor");
7942
+ throw invalid2("invalid_turn_cursor", {}, "agent.final rejected: invalid turn cursor");
7940
7943
  }
7941
7944
  const turnCursor = value.turnCursor;
7942
7945
  return service.final({
@@ -7948,7 +7951,7 @@ function agentCommandHandlers(service, logger = noopLogger) {
7948
7951
  "agent.session": async (params) => {
7949
7952
  const value = isRecord(params) ? params : {};
7950
7953
  if (typeof value.harness !== "string" || typeof value.sessionId !== "string") {
7951
- throw invalid("session_params_required");
7954
+ throw invalid2("session_params_required");
7952
7955
  }
7953
7956
  return service.lastModelRequestAt({ harness: value.harness, sessionId: value.sessionId });
7954
7957
  }
@@ -8206,6 +8209,7 @@ function logSafe5(logger, level, msg, fields) {
8206
8209
  var execFileAsync2 = promisify2(execFile2);
8207
8210
  var PS_PROBE_TIMEOUT_MS = 5e3;
8208
8211
  var PS_PROBE_MAX_OUTPUT_BYTES = 8 * 1024;
8212
+ var PS_PROBE_SIGNAL_ATTEMPTS = 3;
8209
8213
  async function runProbeProcess(cmd, args) {
8210
8214
  const child = spawn(cmd, args, { detached: true, stdio: ["ignore", "pipe", "pipe"] });
8211
8215
  child.unref();
@@ -8222,8 +8226,10 @@ async function runProbeProcess(cmd, args) {
8222
8226
  stderr = appendCapped(stderr, chunk);
8223
8227
  });
8224
8228
  let spawnError;
8229
+ let endedBy;
8225
8230
  const code = await new Promise((resolve11) => {
8226
8231
  const timer = setTimeout(() => {
8232
+ endedBy = "timeout";
8227
8233
  child.kill("SIGKILL");
8228
8234
  resolve11(null);
8229
8235
  }, PS_PROBE_TIMEOUT_MS);
@@ -8235,9 +8241,12 @@ async function runProbeProcess(cmd, args) {
8235
8241
  spawnError = error;
8236
8242
  done(null);
8237
8243
  });
8238
- child.once("close", (exitCode, signal) => done(signal !== null ? null : exitCode));
8244
+ child.once("close", (exitCode, signal) => {
8245
+ if (signal !== null && endedBy === void 0) endedBy = `signal ${signal}`;
8246
+ done(signal !== null ? null : exitCode);
8247
+ });
8239
8248
  });
8240
- return { code, stdout, stderr, ...spawnError === void 0 ? {} : { spawnError } };
8249
+ return { code, stdout, stderr, ...endedBy === void 0 ? {} : { endedBy }, ...spawnError === void 0 ? {} : { spawnError } };
8241
8250
  }
8242
8251
  var toolCache = /* @__PURE__ */ new Map();
8243
8252
  async function resolveToolCached(name, candidates, logger) {
@@ -8260,12 +8269,17 @@ async function probePs(pid, logger) {
8260
8269
  if (!ps) {
8261
8270
  throw new Error("required tool 'ps' not found");
8262
8271
  }
8263
- const run = await runProbeProcess(ps, ["-o", "pid=,pgid=,etime=,stat=,comm=", "-p", String(pid)]);
8272
+ const args = ["-o", "pid=,pgid=,etime=,stat=,comm=", "-p", String(pid)];
8273
+ let run = await runProbeProcess(ps, args);
8274
+ for (let attempt = 1; attempt < PS_PROBE_SIGNAL_ATTEMPTS && run.endedBy?.startsWith("signal ") === true; attempt += 1) {
8275
+ logSafe5(logger, "debug", "ps probe killed by a signal, retrying", { pid, attempt, reason: run.endedBy });
8276
+ run = await runProbeProcess(ps, args);
8277
+ }
8264
8278
  if (run.code === 1) return null;
8265
8279
  if (run.code !== 0) {
8266
8280
  const detail = run.stderr.split("\n").find((line) => line.trim() !== "") ?? "";
8267
8281
  throw new Error(
8268
- `ps probe for pid ${pid} did not complete (code=${String(run.code)})${detail === "" ? "" : `: ${detail}`}`,
8282
+ `ps probe for pid ${pid} did not complete (code=${String(run.code)}${run.endedBy === void 0 ? "" : `, ended by ${run.endedBy}`})${detail === "" ? "" : `: ${detail}`}`,
8269
8283
  run.spawnError === void 0 ? void 0 : { cause: run.spawnError }
8270
8284
  );
8271
8285
  }
@@ -11276,6 +11290,7 @@ async function recoverAgents(deps) {
11276
11290
  if (reservation.phase === "reserved" || agent === null || wrapper === null) {
11277
11291
  blocked += 1;
11278
11292
  deps.logger.error("agent.reservation_blocked_stale", {
11293
+ operation: "agent_recovery.reservation",
11279
11294
  run_id: reservation.runId,
11280
11295
  phase: reservation.phase,
11281
11296
  owner_pid: reservation.owner.pid,
@@ -12752,6 +12767,90 @@ var HarnessDetectError = class extends Error {
12752
12767
  meta;
12753
12768
  };
12754
12769
 
12770
+ // ../../core/packages/runner-core/src/inventory/config-source.ts
12771
+ import { basename as basename8 } from "node:path";
12772
+ import { readFileSync, statSync as statSync5 } from "node:fs";
12773
+ var CONFIG_SOURCE_MAX_VARS = 32;
12774
+ var INSTANCE_ENV_MAX_BYTES = 65536;
12775
+ var INSTANCE_ENV_MAX_KEYS = 256;
12776
+ var NATIVE_CONFIG_MAX_BYTES = 65536;
12777
+ var PROVIDER_ENV_SUFFIXES = ["_API_KEY", "_AUTH_TOKEN", "_OAUTH_TOKEN", "_BASE_URL", "_MODEL"];
12778
+ var NON_PROVIDER_ENV_DENY = /* @__PURE__ */ new Set(["GH_TOKEN", "GITHUB_TOKEN", "COMPIVIA_RUNNER_CREDENTIALS", "COMPIVIA_DASHBOARD_TOKEN"]);
12779
+ var VAR_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
12780
+ var WIRE_PATH_SEGMENT = /^[A-Za-z0-9._-]*[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
12781
+ function nativeClaudeConfigSource(input) {
12782
+ if (input.configDir !== void 0 && input.configDir.includes("{{")) return null;
12783
+ const absolute = input.configDir !== void 0 ? `${input.configDir}/settings.json` : `${input.homeDir}/.claude/settings.json`;
12784
+ const relative3 = relativeUnderHome(absolute, input.homeDir);
12785
+ if (relative3 === null || relative3.length > 256 || !relative3.split("/").every((segment) => WIRE_PATH_SEGMENT.test(segment))) return null;
12786
+ let parsed;
12787
+ try {
12788
+ if (statSync5(absolute).size > NATIVE_CONFIG_MAX_BYTES) return null;
12789
+ parsed = JSON.parse(readFileSync(absolute, "utf8"));
12790
+ } catch {
12791
+ return null;
12792
+ }
12793
+ const env = parsed?.env;
12794
+ if (env === null || typeof env !== "object" || Array.isArray(env)) return null;
12795
+ const vars = Object.keys(env).filter((name) => VAR_NAME_PATTERN.test(name)).sort().slice(0, CONFIG_SOURCE_MAX_VARS);
12796
+ if (vars.length === 0) return null;
12797
+ return { kind: "native_file", file: `~/${relative3}`, section: "env", vars };
12798
+ }
12799
+ function readEnvFileVarNames(path) {
12800
+ if (!isInstancePath(path)) return null;
12801
+ let raw;
12802
+ try {
12803
+ if (statSync5(path).size > INSTANCE_ENV_MAX_BYTES) return null;
12804
+ raw = readFileSync(path, "utf8");
12805
+ } catch {
12806
+ return null;
12807
+ }
12808
+ const names = /* @__PURE__ */ new Set();
12809
+ for (const line of raw.split("\n")) {
12810
+ const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
12811
+ if (match === null || match[1] === void 0) continue;
12812
+ names.add(match[1]);
12813
+ if (names.size > INSTANCE_ENV_MAX_KEYS) return null;
12814
+ }
12815
+ if (names.size === 0) return null;
12816
+ return [...names].sort().slice(0, CONFIG_SOURCE_MAX_VARS);
12817
+ }
12818
+ function providerEnvVarNames(env) {
12819
+ const names = Object.keys(env).filter((name) => PROVIDER_ENV_SUFFIXES.some((suffix) => name.endsWith(suffix)) && !NON_PROVIDER_ENV_DENY.has(name) && !name.startsWith("COMPIVIA_"));
12820
+ return [...new Set(names)].sort().slice(0, CONFIG_SOURCE_MAX_VARS);
12821
+ }
12822
+ function resolveAmbientConfigSource(input) {
12823
+ if (input.instanceEnvFile !== void 0) {
12824
+ const vars = readEnvFileVarNames(input.instanceEnvFile);
12825
+ const file = vars !== null ? instanceDisplayPath(input.instanceEnvFile) : null;
12826
+ if (vars !== null && file !== null) return { kind: "instance_env_file", file, vars };
12827
+ }
12828
+ if (input.processEnv !== void 0) {
12829
+ const vars = providerEnvVarNames(input.processEnv);
12830
+ if (vars.length > 0) return { kind: "process_env", vars };
12831
+ }
12832
+ return { kind: "none" };
12833
+ }
12834
+ function resolveAgentConfigSource(input) {
12835
+ const native = nativeClaudeConfigSource(input);
12836
+ if (native !== null) return native;
12837
+ return resolveAmbientConfigSource(input);
12838
+ }
12839
+ function relativeUnderHome(absolute, homeDir) {
12840
+ const prefix = homeDir.endsWith("/") ? homeDir : `${homeDir}/`;
12841
+ if (!absolute.startsWith(prefix)) return null;
12842
+ return absolute.slice(prefix.length);
12843
+ }
12844
+ function isInstancePath(path) {
12845
+ return basename8(path) === "env" && path.split("/").includes("instances");
12846
+ }
12847
+ function instanceDisplayPath(path) {
12848
+ const parts = path.split("/");
12849
+ const start = parts.lastIndexOf("instances");
12850
+ if (start === -1) return null;
12851
+ return `instances/${parts.slice(start + 1).join("/")}`;
12852
+ }
12853
+
12755
12854
  // ../../core/packages/runner-core/src/inventory/clone-scan.ts
12756
12855
  import { lstat as lstat2, readdir } from "node:fs/promises";
12757
12856
  import { join as join3, resolve as resolve3 } from "node:path";
@@ -13486,11 +13585,13 @@ var ProbedHarnessDetector = class {
13486
13585
  this.runner = runner;
13487
13586
  this.timeoutMs = opts?.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
13488
13587
  this.logger = opts?.logger ?? noopLogger;
13588
+ if (opts?.probeEnv !== void 0) this.probeEnv = opts.probeEnv;
13489
13589
  }
13490
13590
  config;
13491
13591
  runner;
13492
13592
  timeoutMs;
13493
13593
  logger;
13594
+ probeEnv;
13494
13595
  async detect() {
13495
13596
  const startedAt = Date.now();
13496
13597
  let versionResult;
@@ -13499,6 +13600,7 @@ var ProbedHarnessDetector = class {
13499
13600
  versionArgs: this.config.versionArgs,
13500
13601
  runner: this.runner,
13501
13602
  timeoutMs: this.timeoutMs,
13603
+ ...this.probeEnv !== void 0 ? { env: this.probeEnv } : {},
13502
13604
  onResult: (result) => {
13503
13605
  versionResult = result;
13504
13606
  }
@@ -13520,6 +13622,7 @@ var ProbedHarnessDetector = class {
13520
13622
  args: this.config.signinProbe.args,
13521
13623
  runner: this.runner,
13522
13624
  timeoutMs: this.timeoutMs,
13625
+ ...this.probeEnv !== void 0 ? { env: this.probeEnv } : {},
13523
13626
  onResult: (result) => {
13524
13627
  signinResult = result;
13525
13628
  }
@@ -13541,6 +13644,9 @@ var ProbedHarnessDetector = class {
13541
13644
  }
13542
13645
  };
13543
13646
 
13647
+ // ../../core/packages/runner-core/src/harness/detect-claude.ts
13648
+ import { homedir } from "node:os";
13649
+
13544
13650
  // ../../core/packages/runner-core/src/harness/detect-shared.ts
13545
13651
  var INTERNAL_DEADLINE_MS = 5e3;
13546
13652
  async function withDeadline(meta, op) {
@@ -13570,9 +13676,10 @@ function machineEnvValue(launchEnv, key) {
13570
13676
  if (value === void 0) return { kind: "absent" };
13571
13677
  return value.includes("{{") ? { kind: "placeholder" } : { kind: "static", value };
13572
13678
  }
13573
- function buildAgentInventory(input, status, models, version) {
13679
+ function buildAgentInventory(input, status, models, version, configSource) {
13574
13680
  const agent = { id: input.id, name: input.name ?? input.id, status, models: [...models] };
13575
13681
  if (version !== void 0) agent.version = version;
13682
+ if (configSource !== void 0) agent.configSource = configSource;
13576
13683
  return agent;
13577
13684
  }
13578
13685
 
@@ -13599,7 +13706,13 @@ async function claudeAgentInventory(input) {
13599
13706
  throw new HarnessDetectError({ id: input.id, stage: "auth", reason: "invocation_context_required" });
13600
13707
  }
13601
13708
  const status = signinProbe !== void 0 ? await signinProbeStatus({ command: input.command, args: signinProbe.args, runner: input.runner, timeoutMs, env }) : await nativeAuthStatus(input, env, timeoutMs);
13602
- return buildAgentInventory({ id: input.id, name: input.name }, status, input.overrides?.models ?? [], version.version);
13709
+ const configSource = resolveAgentConfigSource({
13710
+ homeDir: input.homeDir ?? homedir(),
13711
+ ...input.configDir !== void 0 ? { configDir: input.configDir } : {},
13712
+ ...input.instanceEnvFile !== void 0 ? { instanceEnvFile: input.instanceEnvFile } : {},
13713
+ ...input.processEnv !== void 0 ? { processEnv: input.processEnv } : {}
13714
+ });
13715
+ return buildAgentInventory({ id: input.id, name: input.name }, status, input.overrides?.models ?? [], version.version, configSource);
13603
13716
  }
13604
13717
  async function nativeAuthStatus(input, env, timeoutMs) {
13605
13718
  const run = await input.runner.run({
@@ -13670,7 +13783,7 @@ var CodexHarnessDetector = class {
13670
13783
 
13671
13784
  // ../../core/packages/runner-core/src/harness/detect-pi.ts
13672
13785
  import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
13673
- import { homedir } from "node:os";
13786
+ import { homedir as homedir2 } from "node:os";
13674
13787
  import { join as join6 } from "node:path";
13675
13788
  var ENV_AGENT_DIR = "PI_CODING_AGENT_DIR";
13676
13789
  var BUILTIN_ENV_KEYS = {
@@ -13763,7 +13876,7 @@ function agentDirOf(input) {
13763
13876
  if (fromEnv.includes("{{")) throw invocationContextRequired(input.id);
13764
13877
  return fromEnv;
13765
13878
  }
13766
- return join6(input.homeDir ?? homedir(), ".pi", "agent");
13879
+ return join6(input.homeDir ?? homedir2(), ".pi", "agent");
13767
13880
  }
13768
13881
  function invocationContextRequired(id) {
13769
13882
  return new HarnessDetectError({ id, stage: "auth", reason: "invocation_context_required" });
@@ -13966,8 +14079,8 @@ var PiHarnessDetector = class {
13966
14079
 
13967
14080
  // ../../core/packages/runner-core/src/harness/claude.ts
13968
14081
  import { readdir as readdir2, stat as stat6 } from "node:fs/promises";
13969
- import { writeFileSync } from "node:fs";
13970
- import { homedir as homedir2 } from "node:os";
14082
+ import { existsSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
14083
+ import { homedir as homedir3 } from "node:os";
13971
14084
  import { join as join7 } from "node:path";
13972
14085
 
13973
14086
  // ../../core/packages/runner-core/src/harness/transcript-read.ts
@@ -14787,6 +14900,8 @@ var ClaudeHarnessAdapter = class {
14787
14900
  /** Machine-launch.env (пути скриптов, CLAUDE_CONFIG_DIR, изоляция);
14788
14901
  * подстановки применяются при запуске. */
14789
14902
  launchEnv;
14903
+ /** #873: env-файл экземпляра — нижний слой detect- и autonomy-проб. */
14904
+ agentEnv;
14790
14905
  // Вынос разбора транскриптов из event loop (#141 §4.3); не задан —
14791
14906
  // in-process.
14792
14907
  executor;
@@ -14805,10 +14920,11 @@ var ClaudeHarnessAdapter = class {
14805
14920
  constructor(opts) {
14806
14921
  this.id = opts.id;
14807
14922
  this.command = opts.command;
14808
- this.homeDir = opts.homeDir ?? homedir2();
14923
+ this.homeDir = opts.homeDir ?? homedir3();
14809
14924
  this.configDir = opts.configDir ?? opts.launchEnv?.CLAUDE_CONFIG_DIR;
14810
14925
  this.prependArgs = opts.prependArgs ?? [];
14811
14926
  this.launchEnv = opts.launchEnv ?? {};
14927
+ if (opts.agentEnv !== void 0) this.agentEnv = opts.agentEnv;
14812
14928
  if (opts.executor !== void 0) this.executor = opts.executor;
14813
14929
  this.probeRunner = opts.runner;
14814
14930
  this.probeOverrides = opts.probeOverrides;
@@ -14829,8 +14945,10 @@ var ClaudeHarnessAdapter = class {
14829
14945
  runner: this.probeRunner ?? new ExecCommandRunner({ logger: this.probeLogger ?? noopLogger }),
14830
14946
  logger: this.logger ?? this.probeLogger ?? noopLogger,
14831
14947
  ...this.probeOverrides !== void 0 ? { overrides: this.probeOverrides } : {},
14832
- probeEnv: staticProbeEnv(this.launchEnv),
14948
+ // #873: карта экземпляра под статическим launch.env.
14949
+ probeEnv: { ...this.agentEnv ?? {}, ...staticProbeEnv(this.launchEnv) },
14833
14950
  launchEnv: this.launchEnv,
14951
+ homeDir: this.homeDir,
14834
14952
  ...this.configDir !== void 0 ? { configDir: this.configDir } : {}
14835
14953
  });
14836
14954
  }
@@ -15062,6 +15180,7 @@ var ClaudeHarnessAdapter = class {
15062
15180
  PATH: process.env.PATH ?? "",
15063
15181
  HOME: process.env.HOME ?? ""
15064
15182
  };
15183
+ for (const [key, value] of Object.entries(this.agentEnv ?? {})) env[key] = value;
15065
15184
  for (const [key, value] of Object.entries(this.launchEnv)) env[key] = substituteTokens(value, substitutions);
15066
15185
  const logFile = join7(sandboxDir, "probe.log");
15067
15186
  let identity;
@@ -15118,9 +15237,17 @@ var ClaudeHarnessAdapter = class {
15118
15237
  }
15119
15238
  /** Статические факты автономности (#661 §4.2): режим из машинных аргументов
15120
15239
  * и детерминированный вердикт по таблице спеки; процессов не спавнит.
15121
- * Режим не задан или вердикта нет — решает autonomy-проба. */
15240
+ * Режим не задан или вердикта нет — решает autonomy-проба.
15241
+ * Онбординг (#872): `~/.claude.json` без `hasCompletedOnboarding: true` —
15242
+ * постоянный вердикт `onboarding_required`, сильнее режимов разрешений. */
15122
15243
  autonomy() {
15123
15244
  const mode = permissionModeOf(this.prependArgs);
15245
+ if (readOnboardingFlag(this.homeDir) === false) {
15246
+ return {
15247
+ ...mode !== void 0 ? { permissionMode: mode } : {},
15248
+ verdict: { status: "needs_setup", reason: "onboarding_required" }
15249
+ };
15250
+ }
15124
15251
  if (mode === void 0) return {};
15125
15252
  const facts = { permissionMode: mode };
15126
15253
  if (mode === "plan") facts.verdict = { status: "needs_setup", reason: "permission_mode_readonly" };
@@ -15134,6 +15261,26 @@ var ClaudeHarnessAdapter = class {
15134
15261
  return facts;
15135
15262
  }
15136
15263
  };
15264
+ function readOnboardingFlag(homeDir) {
15265
+ try {
15266
+ if (!existsSync(homeDir)) return null;
15267
+ } catch {
15268
+ return null;
15269
+ }
15270
+ const file = join7(homeDir, ".claude.json");
15271
+ let raw;
15272
+ try {
15273
+ if (!existsSync(file)) return existsSync(homeDir) ? false : null;
15274
+ raw = readFileSync2(file, "utf8");
15275
+ } catch (error) {
15276
+ return error.code === "ENOENT" ? false : null;
15277
+ }
15278
+ try {
15279
+ return JSON.parse(raw).hasCompletedOnboarding === true;
15280
+ } catch {
15281
+ return null;
15282
+ }
15283
+ }
15137
15284
 
15138
15285
  // ../../core/packages/runner-core/src/harness/jsonl.ts
15139
15286
  import { lstat as lstat5, mkdir, stat as stat7, symlink } from "node:fs/promises";
@@ -15144,6 +15291,8 @@ var JsonlHarnessAdapter = class {
15144
15291
  sessionsRoot;
15145
15292
  launchArgs;
15146
15293
  launchEnv;
15294
+ /** #873: env-файл экземпляра — нижний слой detect-пробы. */
15295
+ agentEnv;
15147
15296
  // Вынос разбора транскриптов из event loop (#141 §4.3); не задан —
15148
15297
  // in-process.
15149
15298
  executor;
@@ -15160,6 +15309,7 @@ var JsonlHarnessAdapter = class {
15160
15309
  this.sessionsRoot = opts.sessionsRoot;
15161
15310
  this.launchArgs = opts.launchArgs ?? [];
15162
15311
  this.launchEnv = opts.launchEnv ?? {};
15312
+ if (opts.agentEnv !== void 0) this.agentEnv = opts.agentEnv;
15163
15313
  if (opts.executor !== void 0) this.executor = opts.executor;
15164
15314
  this.probeRunner = opts.runner;
15165
15315
  this.probeOverrides = opts.probeOverrides;
@@ -15171,7 +15321,7 @@ var JsonlHarnessAdapter = class {
15171
15321
  * generic-основе. ExecCommandRunner — ленивый дефолт изолированного
15172
15322
  * использования; композиция передаёт общий runner. */
15173
15323
  detect() {
15174
- const probeEnv = staticProbeEnv(this.launchEnv);
15324
+ const probeEnv = { ...this.agentEnv ?? {}, ...staticProbeEnv(this.launchEnv) };
15175
15325
  const logger = this.probeLogger ?? noopLogger;
15176
15326
  const runner = this.probeRunner ?? new ExecCommandRunner({ logger });
15177
15327
  const optional = {
@@ -15215,7 +15365,9 @@ var JsonlHarnessAdapter = class {
15215
15365
  ...overrides?.signinProbe !== void 0 ? { signinProbe: overrides.signinProbe } : {},
15216
15366
  ...overrides?.models !== void 0 ? { models: overrides.models } : {}
15217
15367
  },
15218
- runner
15368
+ runner,
15369
+ // C0/A0: generic-ветка базовой ветки не передавала env вовсе.
15370
+ { ...this.agentEnv !== void 0 && Object.keys(this.agentEnv).length > 0 ? { probeEnv } : {} }
15219
15371
  );
15220
15372
  return detector.detect();
15221
15373
  }
@@ -15247,10 +15399,10 @@ var JsonlHarnessAdapter = class {
15247
15399
  prepare = async () => {
15248
15400
  await mkdir(this.sessionsRoot, { recursive: true });
15249
15401
  await mkdir(dirname(writerPath), { recursive: true });
15250
- const logSymlink = (link3, target) => {
15402
+ const logSymlink = (link4, target) => {
15251
15403
  (this.probeLogger ?? noopLogger).debug("transcript symlink created", {
15252
15404
  invocation_id: input.invocationId,
15253
- link_path: link3,
15405
+ link_path: link4,
15254
15406
  target_path: target,
15255
15407
  operation: "symlink"
15256
15408
  });
@@ -15425,9 +15577,11 @@ function harnessAdaptersOf(harnesses, deps) {
15425
15577
  id: harness.id,
15426
15578
  command: harness.command,
15427
15579
  ...configDir !== void 0 ? { configDir } : {},
15580
+ ...deps.homeDir !== void 0 ? { homeDir: deps.homeDir } : {},
15428
15581
  ...harness.launch?.args !== void 0 ? { prependArgs: harness.launch.args } : {},
15429
15582
  ...harness.launch?.env !== void 0 ? { launchEnv: harness.launch.env } : {},
15430
15583
  ...probeOpts,
15584
+ ...deps.agentEnv !== void 0 ? { agentEnv: deps.agentEnv } : {},
15431
15585
  logger: deps.logger
15432
15586
  }));
15433
15587
  } else if (harness.launch?.sessionsRoot !== void 0) {
@@ -15437,7 +15591,8 @@ function harnessAdaptersOf(harnesses, deps) {
15437
15591
  sessionsRoot: harness.launch.sessionsRoot,
15438
15592
  ...harness.launch.args !== void 0 ? { launchArgs: harness.launch.args } : {},
15439
15593
  ...harness.launch.env !== void 0 ? { launchEnv: harness.launch.env } : {},
15440
- ...probeOpts
15594
+ ...probeOpts,
15595
+ ...deps.agentEnv !== void 0 ? { agentEnv: deps.agentEnv } : {}
15441
15596
  }));
15442
15597
  }
15443
15598
  if (!adapters.has(harness.id)) {
@@ -15461,32 +15616,44 @@ function inventoryDetectorFor(harness, adapters, deps) {
15461
15616
  command: harness.command,
15462
15617
  ...harness.name !== void 0 ? { probeName: harness.name } : {},
15463
15618
  ...configDir !== void 0 ? { configDir } : {},
15619
+ ...deps.homeDir !== void 0 ? { homeDir: deps.homeDir } : {},
15464
15620
  ...harness.launch?.args !== void 0 ? { prependArgs: harness.launch.args } : {},
15465
15621
  ...harness.launch?.env !== void 0 ? { launchEnv: harness.launch.env } : {},
15466
15622
  runner: deps.runner,
15467
15623
  ...overridesOpt,
15624
+ ...deps.agentEnv !== void 0 ? { agentEnv: deps.agentEnv } : {},
15468
15625
  probeLogger: deps.logger
15469
15626
  });
15470
15627
  }
15628
+ const probeEnv = { ...deps.agentEnv ?? {}, ...staticProbeEnv(harness.launch?.env) };
15471
15629
  const family = {
15472
15630
  id: harness.id,
15473
15631
  command: harness.command,
15474
15632
  ...harness.name !== void 0 ? { name: harness.name } : {},
15475
15633
  runner: deps.runner,
15476
15634
  ...overridesOpt,
15477
- probeEnv: staticProbeEnv(harness.launch?.env),
15635
+ // #873: карта экземпляра — нижний слой под статическим launch.env.
15636
+ probeEnv,
15478
15637
  launchEnv: harness.launch?.env,
15479
15638
  launchArgs: harness.launch?.args,
15480
15639
  logger: deps.logger
15481
15640
  };
15482
15641
  if (harness.id === HARNESS_AGENTS.codex.id) return new CodexHarnessDetector(family);
15483
15642
  if (harness.id === HARNESS_AGENTS.pi.id) return new PiHarnessDetector(family);
15484
- return new ProbedHarnessDetector(harness, deps.runner, { logger: deps.logger });
15643
+ return new ProbedHarnessDetector(harness, deps.runner, {
15644
+ logger: deps.logger,
15645
+ // C0/A0: без карты generic-проба вообще не получала env — сохраняем
15646
+ // побайтовое поведение базовой ветки; слой включается только после env set.
15647
+ ...deps.agentEnv !== void 0 && Object.keys(deps.agentEnv).length > 0 ? { probeEnv } : {}
15648
+ });
15485
15649
  }
15486
15650
 
15651
+ // ../../core/packages/runner-core/src/harness/detector-set.ts
15652
+ import { statSync as statSync6 } from "node:fs";
15653
+
15487
15654
  // ../../core/packages/runner-core/src/harness/parse-executor.ts
15488
15655
  import { spawn as nodeSpawn } from "node:child_process";
15489
- import { existsSync } from "node:fs";
15656
+ import { existsSync as existsSync2 } from "node:fs";
15490
15657
  import { fileURLToPath as fileURLToPath2 } from "node:url";
15491
15658
  var InProcessExecutor = class {
15492
15659
  async checks(task) {
@@ -15502,7 +15669,7 @@ var InProcessExecutor = class {
15502
15669
  }
15503
15670
  };
15504
15671
  function resolvePoolBootstrap(argv1 = process.argv[1] ?? "") {
15505
- return argv1.endsWith("vite-node.mjs") && existsSync(argv1) ? argv1 : null;
15672
+ return argv1.endsWith("vite-node.mjs") && existsSync2(argv1) ? argv1 : null;
15506
15673
  }
15507
15674
  var POOL_SIZE = 2;
15508
15675
  var QUEUE_LIMIT = 16;
@@ -15745,12 +15912,12 @@ function createDefaultExecutor(logger) {
15745
15912
 
15746
15913
  // ../../core/packages/runner-core/src/plugin/scan.ts
15747
15914
  var import_semver = __toESM(require_semver2(), 1);
15748
- import { existsSync as existsSync3, readdirSync, readFileSync } from "node:fs";
15749
- import { basename as basename8, join as join9 } from "node:path";
15915
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync3 } from "node:fs";
15916
+ import { basename as basename9, join as join9 } from "node:path";
15750
15917
 
15751
15918
  // ../../core/packages/plugin-sdk/src/const.ts
15752
15919
  var SUPPORTED_PLUGIN_API_VERSIONS = [1];
15753
- var CONTRIBUTION_KINDS = ["harness", "reporter"];
15920
+ var CONTRIBUTION_KINDS = ["harness", "reporter", "slug"];
15754
15921
  var CONTRIBUTION_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
15755
15922
  var CONTRIBUTION_KEY_PATTERN = /^[a-z]+:[a-z][a-z0-9-]{0,31}$/;
15756
15923
 
@@ -15796,7 +15963,8 @@ function parseContribution(value, index) {
15796
15963
  if (typeof kind !== "string" || !CONTRIBUTION_KINDS.includes(kind)) {
15797
15964
  throw new PluginManifestError(`${path}.kind: expected one of ${CONTRIBUTION_KINDS.join(", ")}`);
15798
15965
  }
15799
- unknownFields(value, kind === "reporter" ? ["kind", "id", "name", "module", "optionsSchema", "secrets"] : ["kind", "id", "name", "module", "optionsSchema"], path);
15966
+ const allowlist = kind === "harness" ? ["kind", "id", "name", "module", "optionsSchema"] : ["kind", "id", "name", "module", "optionsSchema", "secrets"];
15967
+ unknownFields(value, allowlist, path);
15800
15968
  if (typeof value.id !== "string" || !CONTRIBUTION_ID_PATTERN.test(value.id)) {
15801
15969
  throw new PluginManifestError(`${path}.id: expected a lowercase identifier (max 32 chars)`);
15802
15970
  }
@@ -15816,6 +15984,16 @@ function parseContribution(value, index) {
15816
15984
  ...optionsSchema !== void 0 ? { optionsSchema } : {}
15817
15985
  };
15818
15986
  }
15987
+ if (kind === "slug") {
15988
+ return {
15989
+ kind: "slug",
15990
+ id: value.id,
15991
+ module: value.module,
15992
+ ...value.name !== void 0 ? { name: value.name } : {},
15993
+ ...optionsSchema !== void 0 ? { optionsSchema } : {},
15994
+ ...value.secrets !== void 0 ? { secrets: parseSecrets(value.secrets, `${path}.secrets`) } : {}
15995
+ };
15996
+ }
15819
15997
  return {
15820
15998
  kind: "reporter",
15821
15999
  id: value.id,
@@ -15994,7 +16172,7 @@ function mergePluginSettings(machine, user) {
15994
16172
 
15995
16173
  // ../../core/packages/runner-core/src/plugin/host-manager.ts
15996
16174
  import { spawn as spawn4 } from "node:child_process";
15997
- import { existsSync as existsSync2, mkdirSync } from "node:fs";
16175
+ import { existsSync as existsSync3, mkdirSync } from "node:fs";
15998
16176
  import { fileURLToPath as fileURLToPath3 } from "node:url";
15999
16177
 
16000
16178
  // ../../core/packages/runner-core/src/plugin/protocol.ts
@@ -16070,7 +16248,7 @@ function resolveHostEntryPath() {
16070
16248
  fileURLToPath3(new URL("./host-entry.mjs", import.meta.url)),
16071
16249
  fileURLToPath3(new URL("./plugin/host-entry.mjs", import.meta.url))
16072
16250
  ];
16073
- return candidates.find((candidate) => existsSync2(candidate)) ?? candidates[0];
16251
+ return candidates.find((candidate) => existsSync3(candidate)) ?? candidates[0];
16074
16252
  }
16075
16253
  var PluginHostDownError = class extends Error {
16076
16254
  constructor(reason, message) {
@@ -16230,7 +16408,12 @@ var PluginHostManager = class {
16230
16408
  }
16231
16409
  this.state = "ready";
16232
16410
  this.readyInfo = message.contribution;
16233
- this.send({ type: "init", options: this.specRef.options });
16411
+ this.send({
16412
+ type: "init",
16413
+ options: this.specRef.options,
16414
+ envNames: this.specRef.envNames,
16415
+ ...this.specRef.subscription !== void 0 ? { subscription: this.specRef.subscription } : {}
16416
+ });
16234
16417
  for (const waiter of this.readyWaiters) {
16235
16418
  clearTimeout(waiter.timer);
16236
16419
  waiter.resolve(message.contribution);
@@ -16435,6 +16618,9 @@ var PluginHarnessAdapter = class {
16435
16618
  };
16436
16619
 
16437
16620
  // ../../core/packages/runner-core/src/plugin/scan.ts
16621
+ function scanInstalledPlugins(pluginsRoot) {
16622
+ return activeVersions(scanRoot(pluginsRoot));
16623
+ }
16438
16624
  var MAX_PACKAGE_SEGMENT_DEPTH = 3;
16439
16625
  async function disposePluginHosts(managers) {
16440
16626
  await Promise.all(managers.map((manager) => manager.dispose()));
@@ -16444,7 +16630,7 @@ function buildPluginAdapters(opts) {
16444
16630
  const managers = [];
16445
16631
  if (opts.pluginsRoot === void 0) return { adapters, managers };
16446
16632
  const effective = mergePluginSettings(opts.machinePlugins, opts.userPlugins);
16447
- for (const installed of activeVersions(scanRoot(opts.pluginsRoot))) {
16633
+ for (const installed of scanInstalledPlugins(opts.pluginsRoot)) {
16448
16634
  if ("error" in installed) {
16449
16635
  opts.logger.warn("plugin package skipped", { root: opts.pluginsRoot, dir: installed.dir, reason: installed.error });
16450
16636
  continue;
@@ -16488,7 +16674,7 @@ function activeVersions(installed) {
16488
16674
  continue;
16489
16675
  }
16490
16676
  if (entry.package === "") {
16491
- results.push({ dir: entry.dir, error: "package.json: missing name" });
16677
+ results.push({ dir: entry.dir, error: "package.json: missing name", package: "" });
16492
16678
  continue;
16493
16679
  }
16494
16680
  const current = best.get(entry.package);
@@ -16503,12 +16689,12 @@ function activeVersions(installed) {
16503
16689
  }
16504
16690
  function scanRoot(root) {
16505
16691
  const results = [];
16506
- if (!existsSync3(root)) return results;
16692
+ if (!existsSync4(root)) return results;
16507
16693
  walk(root, 0);
16508
16694
  return results;
16509
16695
  function walk(dir, depth) {
16510
16696
  if (depth > MAX_PACKAGE_SEGMENT_DEPTH + 1) return;
16511
- if (existsSync3(join9(dir, "package.json")) && (0, import_semver.valid)(basename8(dir)) !== null) {
16697
+ if (existsSync4(join9(dir, "package.json")) && (0, import_semver.valid)(basename9(dir)) !== null) {
16512
16698
  results.push(readEntry(dir));
16513
16699
  return;
16514
16700
  }
@@ -16524,16 +16710,18 @@ function scanRoot(root) {
16524
16710
  }
16525
16711
  }
16526
16712
  function readEntry(dir) {
16713
+ let name;
16527
16714
  try {
16528
- const pkg = JSON.parse(readFileSync(join9(dir, "package.json"), "utf8"));
16715
+ const pkg = JSON.parse(readFileSync3(join9(dir, "package.json"), "utf8"));
16716
+ name = typeof pkg.name === "string" ? pkg.name : void 0;
16529
16717
  return {
16530
- package: typeof pkg.name === "string" ? pkg.name : "",
16718
+ package: name ?? "",
16531
16719
  version: typeof pkg.version === "string" ? pkg.version : "",
16532
16720
  dir,
16533
16721
  manifest: parsePluginManifest(pkg)
16534
16722
  };
16535
16723
  } catch (error) {
16536
- return { dir, error: error instanceof Error ? error.message : String(error) };
16724
+ return { dir, error: error instanceof Error ? error.message : String(error), ...name === void 0 ? {} : { package: name } };
16537
16725
  }
16538
16726
  }
16539
16727
  }
@@ -16550,7 +16738,9 @@ function buildHarnessDetectorSet(options) {
16550
16738
  runner: options.runner,
16551
16739
  logger,
16552
16740
  executor,
16553
- host
16741
+ host,
16742
+ ...options.homeDir !== void 0 ? { homeDir: options.homeDir } : {},
16743
+ ...options.agentEnv !== void 0 ? { agentEnv: options.agentEnv } : {}
16554
16744
  });
16555
16745
  const scan = buildPluginAdapters({
16556
16746
  pluginsRoot: options.pluginsRoot,
@@ -16571,21 +16761,53 @@ function buildHarnessDetectorSet(options) {
16571
16761
  adapters.set(id, adapter);
16572
16762
  pluginDetectors.set(id, adapter);
16573
16763
  }
16574
- const detectors = [
16764
+ const rawDetectors = [
16575
16765
  ...options.harnesses.map(
16576
- (harness) => inventoryDetectorFor(harness, adapters, { runner: options.runner, logger })
16766
+ (harness) => inventoryDetectorFor(harness, adapters, {
16767
+ runner: options.runner,
16768
+ logger,
16769
+ ...options.homeDir !== void 0 ? { homeDir: options.homeDir } : {},
16770
+ ...options.agentEnv !== void 0 ? { agentEnv: options.agentEnv } : {}
16771
+ })
16577
16772
  ),
16578
16773
  ...pluginDetectors.values()
16579
16774
  ];
16580
16775
  const detectorIds = [...options.harnesses.map((harness) => harness.id), ...pluginDetectors.keys()];
16776
+ let ambientCache = null;
16777
+ const ambient = () => {
16778
+ let key = "no-file";
16779
+ if (options.instanceEnvFile !== void 0) {
16780
+ try {
16781
+ const stats = statSync6(options.instanceEnvFile);
16782
+ key = `${stats.mtimeMs}:${stats.size}`;
16783
+ } catch {
16784
+ key = "absent";
16785
+ }
16786
+ }
16787
+ if (ambientCache !== null && ambientCache.key === key) return ambientCache.source;
16788
+ const source = resolveAmbientConfigSource({
16789
+ ...options.instanceEnvFile !== void 0 ? { instanceEnvFile: options.instanceEnvFile } : {},
16790
+ processEnv: options.baseEnv
16791
+ });
16792
+ ambientCache = { key, source };
16793
+ return source;
16794
+ };
16795
+ const withAmbient = (inventory) => {
16796
+ const own = inventory.configSource;
16797
+ if (own !== void 0 && own.kind !== "none") return inventory;
16798
+ return { ...inventory, configSource: ambient() };
16799
+ };
16800
+ const wrapped = rawDetectors.map((detector) => ({
16801
+ detect: async () => withAmbient(await detector.detect())
16802
+ }));
16581
16803
  let disposed = false;
16582
16804
  return {
16583
16805
  adapters,
16584
- detectors,
16806
+ detectors: wrapped,
16585
16807
  detectorIds,
16586
16808
  async detect() {
16587
16809
  return Promise.all(
16588
- detectors.map(async (detector, index) => {
16810
+ wrapped.map(async (detector, index) => {
16589
16811
  try {
16590
16812
  return { kind: "agent", agent: await detector.detect() };
16591
16813
  } catch (error) {
@@ -16611,12 +16833,12 @@ function buildHarnessDetectorSet(options) {
16611
16833
  }
16612
16834
 
16613
16835
  // ../../core/packages/runner-core/src/plugin/user-settings.ts
16614
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
16836
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
16615
16837
  function readPluginsSectionFromUser(file) {
16616
- if (file === void 0 || !existsSync4(file)) return void 0;
16838
+ if (file === void 0 || !existsSync5(file)) return void 0;
16617
16839
  let raw;
16618
16840
  try {
16619
- raw = readFileSync2(file, "utf8");
16841
+ raw = readFileSync4(file, "utf8");
16620
16842
  } catch (error) {
16621
16843
  throw new Error(`${file}: unreadable (${error.code ?? (error instanceof Error ? error.name : "unknown")})`);
16622
16844
  }
@@ -16722,6 +16944,65 @@ function parseHarness(value, index) {
16722
16944
  }
16723
16945
  return harness;
16724
16946
  }
16947
+ var REPORTER_ENTRY_FIELDS = ["subscription", "package", "reporter", "intervalMinutes", "timeoutSeconds", "options", "env"];
16948
+ var ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
16949
+ function parseReporterEntry(value, index) {
16950
+ const field = `reporters[${index}]`;
16951
+ if (!isPlainObject5(value)) throw new MachineConfigError(`${field}: expected an object`);
16952
+ for (const key of Object.keys(value)) {
16953
+ if (!REPORTER_ENTRY_FIELDS.includes(key)) {
16954
+ throw new MachineConfigError(`${field}.${key}: unknown field`);
16955
+ }
16956
+ }
16957
+ if (!nonEmptyString(value.subscription)) throw new MachineConfigError(`${field}.subscription: expected a non-empty string`);
16958
+ if (!nonEmptyString(value.package)) throw new MachineConfigError(`${field}.package: expected a non-empty string`);
16959
+ const entry = {
16960
+ subscription: value.subscription,
16961
+ package: value.package,
16962
+ intervalMinutes: 10,
16963
+ timeoutSeconds: 30,
16964
+ options: {},
16965
+ env: []
16966
+ };
16967
+ if (value.reporter !== void 0) {
16968
+ if (!nonEmptyString(value.reporter)) throw new MachineConfigError(`${field}.reporter: expected a non-empty string`);
16969
+ entry.reporter = value.reporter;
16970
+ }
16971
+ for (const [key, min] of [["intervalMinutes", 1], ["timeoutSeconds", 1]]) {
16972
+ const raw = value[key];
16973
+ if (raw === void 0) continue;
16974
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw < min) {
16975
+ throw new MachineConfigError(`${field}.${key}: expected an integer >= ${min}`);
16976
+ }
16977
+ entry[key] = raw;
16978
+ }
16979
+ if (value.options !== void 0) {
16980
+ if (!isPlainObject5(value.options)) throw new MachineConfigError(`${field}.options: expected an object`);
16981
+ entry.options = value.options;
16982
+ }
16983
+ if (value.env !== void 0) {
16984
+ if (!Array.isArray(value.env)) throw new MachineConfigError(`${field}.env: expected an array of env names`);
16985
+ entry.env = value.env.map((name, envIndex) => {
16986
+ if (typeof name !== "string" || !ENV_NAME_PATTERN.test(name)) {
16987
+ throw new MachineConfigError(`${field}.env[${envIndex}]: expected a valid env name`);
16988
+ }
16989
+ return name;
16990
+ });
16991
+ }
16992
+ return entry;
16993
+ }
16994
+ function parseReportersSection(value) {
16995
+ if (!Array.isArray(value)) throw new MachineConfigError("reporters: expected an array");
16996
+ const entries = value.map(parseReporterEntry);
16997
+ const seen = /* @__PURE__ */ new Set();
16998
+ for (const [index, reporter] of entries.entries()) {
16999
+ if (seen.has(reporter.subscription)) {
17000
+ throw new MachineConfigError(`reporters[${index}].subscription: duplicate subscription ${JSON.stringify(reporter.subscription)}`);
17001
+ }
17002
+ seen.add(reporter.subscription);
17003
+ }
17004
+ return entries;
17005
+ }
16725
17006
  async function loadMachineInventoryConfig(path, logger = noopLogger) {
16726
17007
  if (path === void 0) return emptyMachineInventoryConfig();
16727
17008
  let raw;
@@ -16810,6 +17091,9 @@ async function loadMachineInventoryConfig(path, logger = noopLogger) {
16810
17091
  }
16811
17092
  config.plugins = parsed.plugins;
16812
17093
  }
17094
+ if (parsed.reporters !== void 0) {
17095
+ config.reporters = parseReportersSection(parsed.reporters);
17096
+ }
16813
17097
  logger.info("machine config loaded", {
16814
17098
  path,
16815
17099
  harnesses_count: config.harnesses.length,
@@ -16820,8 +17104,198 @@ async function loadMachineInventoryConfig(path, logger = noopLogger) {
16820
17104
  return config;
16821
17105
  }
16822
17106
 
17107
+ // ../../core/packages/runner-core/src/inventory/machine-bootstrap.ts
17108
+ import { existsSync as existsSync6 } from "node:fs";
17109
+ import { chmod as chmod2, link, mkdir as mkdir2, readFile as readFile5, rename, stat as stat8, unlink, writeFile } from "node:fs/promises";
17110
+ import { randomUUID as randomUUID5 } from "node:crypto";
17111
+ import { dirname as dirname2, isAbsolute as isAbsolute6 } from "node:path";
17112
+ var HARNESS_DEFAULT_COMMANDS = {
17113
+ claudeCode: "claude",
17114
+ codex: "codex",
17115
+ pi: "pi"
17116
+ };
17117
+ function starterHarnessEntries() {
17118
+ return Object.keys(HARNESS_AGENTS).map((key) => {
17119
+ const agent = HARNESS_AGENTS[key];
17120
+ const entry = { id: agent.id, name: agent.name, command: HARNESS_DEFAULT_COMMANDS[key] };
17121
+ if (agent.id === HARNESS_AGENTS.claudeCode.id) entry.launch = { args: ["--permission-mode", "auto"] };
17122
+ return entry;
17123
+ });
17124
+ }
17125
+ async function detectStarterHarnesses(options) {
17126
+ const logger = options.logger ?? noopLogger;
17127
+ const entries = starterHarnessEntries();
17128
+ const runner = options.runner ?? new ExecCommandRunner({ logger });
17129
+ const setOptions = {
17130
+ harnesses: entries,
17131
+ runner,
17132
+ instanceDataDir: options.instanceDataDir,
17133
+ baseEnv: options.baseEnv,
17134
+ ...options.pluginsRoot !== void 0 ? { pluginsRoot: options.pluginsRoot } : {},
17135
+ ...options.machinePlugins !== void 0 ? { machinePlugins: options.machinePlugins } : {},
17136
+ ...options.userPlugins !== void 0 ? { userPlugins: options.userPlugins } : {},
17137
+ ...options.homeDir !== void 0 ? { homeDir: options.homeDir } : {},
17138
+ ...options.agentEnv !== void 0 ? { agentEnv: options.agentEnv } : {},
17139
+ ...options.instanceEnvFile !== void 0 ? { instanceEnvFile: options.instanceEnvFile } : {},
17140
+ ...options.logger !== void 0 ? { logger: options.logger } : {},
17141
+ ...options.pluginHostOptions !== void 0 ? { pluginHostOptions: options.pluginHostOptions } : {}
17142
+ };
17143
+ const set = options.detectorSetFactory !== void 0 ? options.detectorSetFactory(setOptions) : buildHarnessDetectorSet(setOptions);
17144
+ let results;
17145
+ try {
17146
+ results = await set.detect();
17147
+ } finally {
17148
+ await set.dispose().catch((disposeError) => {
17149
+ logger.warn("starter detector set dispose failed", { reason: "dispose_failed", err: disposeError });
17150
+ });
17151
+ }
17152
+ return classifyDetectionResults(results, entries, logger);
17153
+ }
17154
+ function classifyDetectionResults(results, entries, logger) {
17155
+ const entryById = new Map(entries.map((entry) => [entry.id, entry]));
17156
+ const detection = { agents: [], pluginHarnesses: [], skipped: [] };
17157
+ for (const result of results) {
17158
+ if (result.kind === "detect_failed") {
17159
+ detection.skipped.push({ id: result.id, skipped: "detect_failed", stage: result.stage, reason: result.reason });
17160
+ logger.warn("starter harness skipped", { harness: result.id, reason: "detect_failed", stage: result.stage });
17161
+ continue;
17162
+ }
17163
+ const entry = entryById.get(result.agent.id);
17164
+ if (entry !== void 0) {
17165
+ if (result.agent.status !== "not_installed") detection.agents.push({ entry, agent: result.agent });
17166
+ else {
17167
+ detection.skipped.push({ id: result.agent.id, skipped: "not_installed" });
17168
+ logger.warn("starter harness skipped", { harness: result.agent.id, reason: "not_installed" });
17169
+ }
17170
+ continue;
17171
+ }
17172
+ if (result.agent.status !== "not_installed") {
17173
+ detection.pluginHarnesses.push({
17174
+ id: result.agent.id,
17175
+ name: result.agent.name,
17176
+ status: result.agent.status,
17177
+ models: result.agent.models,
17178
+ ...result.agent.version !== void 0 ? { version: result.agent.version } : {}
17179
+ });
17180
+ } else {
17181
+ detection.skipped.push({ id: result.agent.id, skipped: "not_installed" });
17182
+ }
17183
+ }
17184
+ return detection;
17185
+ }
17186
+ function buildStarterMachineConfig(detection, params) {
17187
+ const cloneRoots = [...params.cloneRoots];
17188
+ for (const [index, root] of cloneRoots.entries()) {
17189
+ if (!isAbsolute6(root)) throw new MachineConfigError(`cloneRoots[${index}]: expected an absolute path`);
17190
+ }
17191
+ return {
17192
+ slots: { total: Math.max(1, params.slotsTotal ?? 1) },
17193
+ capabilities: [],
17194
+ cloneRoots,
17195
+ harnesses: detection.agents.map(({ entry }) => ({ ...entry }))
17196
+ };
17197
+ }
17198
+ async function writeMachineConfigIfAbsent(path, document) {
17199
+ const dir = dirname2(path);
17200
+ const dirExisted = existsSync6(dir);
17201
+ await mkdir2(dir, { recursive: true });
17202
+ if (!dirExisted) await chmod2(dir, 448);
17203
+ const tmp = `${path}.${randomUUID5()}.tmp`;
17204
+ try {
17205
+ await writeFile(tmp, `${JSON.stringify(document, null, 2)}
17206
+ `, { mode: 384 });
17207
+ try {
17208
+ await link(tmp, path);
17209
+ return { created: true, path };
17210
+ } catch (error) {
17211
+ if (errnoOf(error) === "EEXIST") return { created: false, path };
17212
+ throw error;
17213
+ }
17214
+ } finally {
17215
+ await unlink(tmp).catch(() => void 0);
17216
+ }
17217
+ }
17218
+ function machineConfigEmptySections(config) {
17219
+ return machineConfigWarningTexts(config, "").map((entry) => entry.section);
17220
+ }
17221
+ function machineConfigWarningTexts(config, path) {
17222
+ const texts = [];
17223
+ if (config.slots.total === 0) {
17224
+ texts.push({ section: "slots", text: `no slots are configured in ${path}; set "slots": {"total": N} (N >= 1)` });
17225
+ }
17226
+ if (config.cloneRoots.length === 0) {
17227
+ texts.push({ section: "cloneRoots", text: `no cloneRoots are configured in ${path}; add absolute paths to the "cloneRoots" array` });
17228
+ }
17229
+ if (config.harnesses.length === 0) {
17230
+ texts.push({ section: "harnesses", text: `no harnesses are configured in ${path}; add a "harnesses" entry or run compivia engine create / compivia runner pair` });
17231
+ }
17232
+ return texts;
17233
+ }
17234
+ async function classifyExistingConfigWarnings(path, logger) {
17235
+ try {
17236
+ const existing = await loadMachineInventoryConfig(path, logger);
17237
+ return {
17238
+ config: existing,
17239
+ warnings: machineConfigWarningTexts(existing, path).map((entry) => entry.text)
17240
+ };
17241
+ } catch (error) {
17242
+ logger.warn("machine config not written", {
17243
+ path,
17244
+ reason: error instanceof MachineConfigError ? "invalid_json_left_as_is" : "unreadable_left_as_is",
17245
+ err: error
17246
+ });
17247
+ const text = error instanceof MachineConfigError ? `existing machine config at ${path} is not valid JSON; left as-is` : `existing machine config at ${path} was not readable (${errnoOf(error)}); left as-is`;
17248
+ return { config: emptyMachineInventoryConfig(), warnings: [text] };
17249
+ }
17250
+ }
17251
+ async function bootstrapMachineConfig(options) {
17252
+ const logger = options.logger ?? noopLogger;
17253
+ if (existsSync6(options.path)) {
17254
+ const { config: config2, warnings: warnings2 } = await classifyExistingConfigWarnings(options.path, logger);
17255
+ logger.info("machine config bootstrap finished", {
17256
+ path: options.path,
17257
+ created: false,
17258
+ agents: 0,
17259
+ skipped: 0,
17260
+ plugin_harnesses: 0
17261
+ });
17262
+ return { path: options.path, created: false, config: config2, detection: { agents: [], pluginHarnesses: [], skipped: [] }, warnings: warnings2 };
17263
+ }
17264
+ const detection = await detectStarterHarnesses(options);
17265
+ const config = buildStarterMachineConfig(detection, {
17266
+ cloneRoots: options.cloneRoots,
17267
+ ...options.slotsTotal !== void 0 ? { slotsTotal: options.slotsTotal } : {}
17268
+ });
17269
+ let created;
17270
+ try {
17271
+ created = (await writeMachineConfigIfAbsent(options.path, config)).created;
17272
+ } catch (error) {
17273
+ const errno = errnoOf(error);
17274
+ logger.warn("machine config not written", { path: options.path, reason: "write_failed", errno, err: error });
17275
+ return {
17276
+ path: options.path,
17277
+ created: false,
17278
+ config,
17279
+ detection,
17280
+ warnings: [
17281
+ ...machineConfigWarningTexts(config, options.path).map((entry) => entry.text),
17282
+ `machine config was not written to ${options.path}: ${errno}`
17283
+ ]
17284
+ };
17285
+ }
17286
+ const warnings = created ? machineConfigWarningTexts(config, options.path).map((entry) => entry.text) : (await classifyExistingConfigWarnings(options.path, logger)).warnings;
17287
+ logger.info("machine config bootstrap finished", {
17288
+ path: options.path,
17289
+ created,
17290
+ agents: detection.agents.length,
17291
+ skipped: detection.skipped.length,
17292
+ plugin_harnesses: detection.pluginHarnesses.length
17293
+ });
17294
+ return { path: options.path, created, config, detection, warnings };
17295
+ }
17296
+
16823
17297
  // ../../core/packages/runner-core/src/inventory/packs.ts
16824
- import { lstat as lstat6, readFile as readFile5, readdir as readdir3 } from "node:fs/promises";
17298
+ import { lstat as lstat6, readFile as readFile6, readdir as readdir3 } from "node:fs/promises";
16825
17299
  import { join as join10 } from "node:path";
16826
17300
  var DirectoryPackCatalog = class {
16827
17301
  constructor(opts) {
@@ -16843,7 +17317,7 @@ var DirectoryPackCatalog = class {
16843
17317
  throw error;
16844
17318
  }
16845
17319
  const packs = [];
16846
- let invalid = 0;
17320
+ let invalid2 = 0;
16847
17321
  for (const dirent of dirents) {
16848
17322
  if (!dirent.isDirectory() || dirent.isSymbolicLink()) {
16849
17323
  this.opts.logger.debug("pack candidate skipped: not a directory", { root, entry: dirent.name });
@@ -16851,10 +17325,10 @@ var DirectoryPackCatalog = class {
16851
17325
  }
16852
17326
  const entry = await this.packAt(join10(root, dirent.name));
16853
17327
  if (entry !== void 0) packs.push(entry);
16854
- else invalid++;
17328
+ else invalid2++;
16855
17329
  }
16856
17330
  const result = packs.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
16857
- this.opts.logger.debug("packs listed", { root, packs_count: result.length, invalid_count: invalid });
17331
+ this.opts.logger.debug("packs listed", { root, packs_count: result.length, invalid_count: invalid2 });
16858
17332
  return result;
16859
17333
  }
16860
17334
  async packAt(dir) {
@@ -16875,7 +17349,7 @@ var DirectoryPackCatalog = class {
16875
17349
  }
16876
17350
  let raw;
16877
17351
  try {
16878
- raw = await readFile5(manifestPath, "utf8");
17352
+ raw = await readFile6(manifestPath, "utf8");
16879
17353
  } catch (error) {
16880
17354
  if (errnoOf(error) !== "ENOENT") {
16881
17355
  this.opts.logger.error("pack manifest read failed", { dir, err: error });
@@ -16911,19 +17385,19 @@ var DirectoryPackCatalog = class {
16911
17385
  };
16912
17386
 
16913
17387
  // ../../core/packages/runner-core/src/inventory/repo-bindings.ts
16914
- import { chmodSync as chmodSync4, statSync as statSync5 } from "node:fs";
17388
+ import { chmodSync as chmodSync4, statSync as statSync7 } from "node:fs";
16915
17389
  import { DatabaseSync as DatabaseSync5 } from "node:sqlite";
16916
17390
  var GIT_ACCESS_VALUES = ["ok", "auth_failed", "unreachable"];
16917
17391
  function isGitAccess(value) {
16918
17392
  return GIT_ACCESS_VALUES.includes(value);
16919
17393
  }
16920
17394
  function ensureOwnerOnly4(path, logger) {
16921
- const mode = statSync5(path).mode & 511;
17395
+ const mode = statSync7(path).mode & 511;
16922
17396
  if (mode !== 384) {
16923
17397
  logger.warn("bindings file mode corrected", { path, from_mode: mode.toString(8) });
16924
17398
  chmodSync4(path, 384);
16925
17399
  }
16926
- if ((statSync5(path).mode & 511) !== 384) {
17400
+ if ((statSync7(path).mode & 511) !== 384) {
16927
17401
  throw new Error(`repo bindings file ${path} is not owner-only`);
16928
17402
  }
16929
17403
  }
@@ -17022,7 +17496,7 @@ var RepoBindingsStore = class _RepoBindingsStore {
17022
17496
  };
17023
17497
 
17024
17498
  // ../../core/packages/runner-core/src/inventory/repo-bind-service.ts
17025
- import { isAbsolute as isAbsolute6, resolve as resolve6 } from "node:path";
17499
+ import { isAbsolute as isAbsolute7, resolve as resolve6 } from "node:path";
17026
17500
 
17027
17501
  // ../../core/packages/runner-core/src/inventory/repo-identity.ts
17028
17502
  function repositoryFromRemoteUrl(url) {
@@ -17060,7 +17534,7 @@ var RepoBindingService = class {
17060
17534
  }
17061
17535
  opts;
17062
17536
  async check(repository, rawPath) {
17063
- if (typeof rawPath !== "string" || !REPOSITORY_PATTERN2.test(repository) || rawPath === "" || !isAbsolute6(rawPath)) {
17537
+ if (typeof rawPath !== "string" || !REPOSITORY_PATTERN2.test(repository) || rawPath === "" || !isAbsolute7(rawPath)) {
17064
17538
  this.opts.logger.warn("bind params rejected", {
17065
17539
  repository,
17066
17540
  field: !REPOSITORY_PATTERN2.test(repository) ? "repository" : "path"
@@ -17302,7 +17776,8 @@ var InventoryService = class {
17302
17776
  hooks,
17303
17777
  slots: { total: this.opts.slots.total, busy },
17304
17778
  capabilities: [...this.opts.capabilities],
17305
- bindings
17779
+ bindings,
17780
+ reporters: this.opts.reporters?.() ?? []
17306
17781
  };
17307
17782
  this.lastBuilt = snapshot;
17308
17783
  this.logger.debug("inventory snapshot built", {
@@ -17434,11 +17909,11 @@ var InventoryService = class {
17434
17909
  };
17435
17910
 
17436
17911
  // ../../core/packages/runner-core/src/worktree/service.ts
17437
- import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
17912
+ import { createHash as createHash4, randomUUID as randomUUID6 } from "node:crypto";
17438
17913
  import { chmodSync as chmodSync5 } from "node:fs";
17439
17914
  import { constants as fsConstants3 } from "node:fs";
17440
- import { lstat as lstat10, mkdir as mkdir5, open as open5, readFile as readFile6, readdir as readdir4, realpath as realpath6, rename, stat as statFile, writeFile as writeFile2 } from "node:fs/promises";
17441
- import { basename as basename11, dirname as dirname5, join as join16, relative as relative2, resolve as resolve9, sep as sep3 } from "node:path";
17915
+ import { lstat as lstat10, mkdir as mkdir6, open as open5, readFile as readFile7, readdir as readdir4, realpath as realpath6, rename as rename2, stat as statFile, writeFile as writeFile3 } from "node:fs/promises";
17916
+ import { basename as basename12, dirname as dirname6, join as join16, relative as relative2, resolve as resolve9, sep as sep3 } from "node:path";
17442
17917
  import { DatabaseSync as DatabaseSync6 } from "node:sqlite";
17443
17918
 
17444
17919
  // ../../core/packages/runner-core/src/worktree/service-helpers.ts
@@ -17612,7 +18087,7 @@ async function baseRevisionOf(svc, clone, base) {
17612
18087
  }
17613
18088
 
17614
18089
  // ../../core/packages/runner-core/src/worktree/checkpoint.ts
17615
- import { mkdir as mkdir2, writeFile } from "node:fs/promises";
18090
+ import { mkdir as mkdir3, writeFile as writeFile2 } from "node:fs/promises";
17616
18091
  import { join as join11 } from "node:path";
17617
18092
  function stderrTail(stderr) {
17618
18093
  if (stderr === void 0 || stderr === "") return void 0;
@@ -17649,8 +18124,8 @@ async function savePatch(run, opts) {
17649
18124
  if (diff.stdout === "") return void 0;
17650
18125
  const target = join11(opts.patchDir, `checkpoint-${opts.patchStem}.patch`);
17651
18126
  try {
17652
- await mkdir2(opts.patchDir, { recursive: true });
17653
- await writeFile(target, Buffer.from(diff.stdout, "latin1"));
18127
+ await mkdir3(opts.patchDir, { recursive: true });
18128
+ await writeFile2(target, Buffer.from(diff.stdout, "latin1"));
17654
18129
  return target;
17655
18130
  } catch (error) {
17656
18131
  opts.onPatchError?.(`patch write failed: ${error instanceof Error ? error.message : "non-error"}`);
@@ -17708,8 +18183,8 @@ async function checkpointOf(path, message, run, opts = {}) {
17708
18183
  import { execFile as execFile4 } from "node:child_process";
17709
18184
  import { createHash as createHash3 } from "node:crypto";
17710
18185
  import { constants as constants3, createReadStream } from "node:fs";
17711
- import { chmod as chmod2, copyFile, glob, link, lstat as lstat7, mkdir as mkdir3, opendir, rmdir, unlink } from "node:fs/promises";
17712
- import { basename as basename9, dirname as dirname2, isAbsolute as isAbsolute7, join as join12, resolve as resolve7 } from "node:path";
18186
+ import { chmod as chmod3, copyFile, glob, link as link2, lstat as lstat7, mkdir as mkdir4, opendir, rmdir, unlink as unlink2 } from "node:fs/promises";
18187
+ import { basename as basename10, dirname as dirname3, isAbsolute as isAbsolute8, join as join12, resolve as resolve7 } from "node:path";
17713
18188
  var excluded = /* @__PURE__ */ new Set(["node_modules", "build", "dist", "target", "vendor", ".git", ".gradle", ".cache", "coverage"]);
17714
18189
  function ignoredPaths(clone, paths, logger) {
17715
18190
  return new Promise((resolve11, reject10) => {
@@ -17739,7 +18214,7 @@ function ignoredPaths(clone, paths, logger) {
17739
18214
  });
17740
18215
  }
17741
18216
  function safeRelative2(path) {
17742
- return path.length > 0 && !isAbsolute7(path) && !path.includes("\\") && !path.includes("\0") && !path.split("/").includes("..");
18217
+ return path.length > 0 && !isAbsolute8(path) && !path.includes("\\") && !path.includes("\0") && !path.split("/").includes("..");
17743
18218
  }
17744
18219
  async function noSymlinks(path, logger, allowMissing = false) {
17745
18220
  let current = resolve7(path);
@@ -17752,7 +18227,7 @@ async function noSymlinks(path, logger, allowMissing = false) {
17752
18227
  return false;
17753
18228
  }
17754
18229
  }
17755
- const parent = dirname2(current);
18230
+ const parent = dirname3(current);
17756
18231
  if (parent === current) return true;
17757
18232
  current = parent;
17758
18233
  }
@@ -17763,7 +18238,7 @@ async function fingerprint2(path) {
17763
18238
  return hash.digest("hex");
17764
18239
  }
17765
18240
  async function cleanupConfigStaging(clone, worktree, logger = noopLogger) {
17766
- const namespace = basename9(worktree);
18241
+ const namespace = basename10(worktree);
17767
18242
  const directory = join12(clone, ".git", "compivia", "config-staging", namespace);
17768
18243
  try {
17769
18244
  if (namespace === "" || namespace === "." || namespace === "..") throw new Error("unsafe_staging");
@@ -17772,7 +18247,7 @@ async function cleanupConfigStaging(clone, worktree, logger = noopLogger) {
17772
18247
  if (!entry.isFile() || !/^[a-f0-9]{64}$/.test(entry.name)) throw new Error("unsafe_staging");
17773
18248
  const path = join12(directory, entry.name);
17774
18249
  if (!await noSymlinks(path, logger) || !(await lstat7(path)).isFile()) throw new Error("unsafe_staging");
17775
- await unlink(path);
18250
+ await unlink2(path);
17776
18251
  }
17777
18252
  if (!await noSymlinks(directory, logger)) throw new Error("unsafe_staging");
17778
18253
  await rmdir(directory);
@@ -17817,13 +18292,13 @@ async function copyIgnoredConfigs(clone, worktree, globs = ["**/.env", "**/*.env
17817
18292
  skipped++;
17818
18293
  continue;
17819
18294
  }
17820
- const stagingDirectory = join12(clone, ".git", "compivia", "config-staging", basename9(worktree));
18295
+ const stagingDirectory = join12(clone, ".git", "compivia", "config-staging", basename10(worktree));
17821
18296
  const staging = join12(stagingDirectory, createHash3("sha256").update(relative3).digest("hex"));
17822
18297
  if (!await noSymlinks(staging, logger, true)) throw new Error("unsafe_staging");
17823
18298
  try {
17824
18299
  const stale = await lstat7(staging);
17825
18300
  if (!stale.isFile()) throw new Error("unsafe_staging");
17826
- await unlink(staging);
18301
+ await unlink2(staging);
17827
18302
  } catch (error) {
17828
18303
  if (errnoOf(error) !== "ENOENT") throw error;
17829
18304
  }
@@ -17837,22 +18312,22 @@ async function copyIgnoredConfigs(clone, worktree, globs = ["**/.env", "**/*.env
17837
18312
  }
17838
18313
  const sourceHash = await fingerprint2(source);
17839
18314
  await persistFingerprint?.(relative3, sourceHash);
17840
- await mkdir3(stagingDirectory, { recursive: true, mode: 448 });
18315
+ await mkdir4(stagingDirectory, { recursive: true, mode: 448 });
17841
18316
  if (!await noSymlinks(stagingDirectory, logger)) throw new Error("unsafe_staging");
17842
- await chmod2(stagingDirectory, 448);
18317
+ await chmod3(stagingDirectory, 448);
17843
18318
  try {
17844
18319
  if (!await noSymlinks(source, logger) || !(await lstat7(source)).isFile() || !await noSymlinks(staging, logger, true)) throw new Error("unsafe_staging");
17845
18320
  await copyFile(source, staging, constants3.COPYFILE_EXCL);
17846
- await chmod2(staging, 384);
18321
+ await chmod3(staging, 384);
17847
18322
  const copiedHash = await fingerprint2(staging);
17848
18323
  if (copiedHash !== sourceHash) {
17849
18324
  logger.warn("config source changed during copy", { path: relative3 });
17850
18325
  await persistFingerprint?.(relative3, copiedHash);
17851
18326
  }
17852
18327
  if (!await noSymlinks(destination, logger, true) || !await noSymlinks(staging, logger)) throw new Error("unsafe_staging");
17853
- await mkdir3(dirname2(destination), { recursive: true });
18328
+ await mkdir4(dirname3(destination), { recursive: true });
17854
18329
  try {
17855
- await link(staging, destination);
18330
+ await link2(staging, destination);
17856
18331
  } catch (error) {
17857
18332
  if (errnoOf(error) === "EEXIST") {
17858
18333
  logger.debug("ignored config skipped", { path: relative3, reason: "destination_exists" });
@@ -17866,7 +18341,7 @@ async function copyIgnoredConfigs(clone, worktree, globs = ["**/.env", "**/*.env
17866
18341
  } finally {
17867
18342
  if (!await noSymlinks(staging, logger, true)) throw new Error("unsafe_staging");
17868
18343
  try {
17869
- await unlink(staging);
18344
+ await unlink2(staging);
17870
18345
  } catch (error) {
17871
18346
  if (errnoOf(error) !== "ENOENT") {
17872
18347
  logger.error("config staging cleanup failed", { path: staging, err: error });
@@ -17954,10 +18429,10 @@ async function onlyCopiedConfigsInDirectory(worktree, directory, fingerprints, l
17954
18429
  if (!safeRelative2(relative3) || relative3.split("/").some((part) => part === "" || part === ".")) return false;
17955
18430
  if (!relative3.startsWith(`${directory}/`)) continue;
17956
18431
  files.add(relative3);
17957
- let parent = dirname2(relative3);
18432
+ let parent = dirname3(relative3);
17958
18433
  while (parent !== directory) {
17959
18434
  directories.add(parent);
17960
- parent = dirname2(parent);
18435
+ parent = dirname3(parent);
17961
18436
  }
17962
18437
  }
17963
18438
  if (files.size === 0) return false;
@@ -17984,8 +18459,8 @@ async function onlyCopiedConfigsInDirectory(worktree, directory, fingerprints, l
17984
18459
  }
17985
18460
 
17986
18461
  // ../../core/packages/runner-core/src/worktree/root.ts
17987
- import { lstat as lstat8, realpath as realpath4, stat as stat8 } from "node:fs/promises";
17988
- import { basename as basename10, dirname as dirname3, join as join13, sep as sep2 } from "node:path";
18462
+ import { lstat as lstat8, realpath as realpath4, stat as stat9 } from "node:fs/promises";
18463
+ import { basename as basename11, dirname as dirname4, join as join13, sep as sep2 } from "node:path";
17989
18464
  var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
17990
18465
  var DEFAULT_WORKTREE_ROOT_DIR = ".compivia-worktrees";
17991
18466
  function unsafe() {
@@ -18007,9 +18482,9 @@ async function realpathOfWorktreeRoot(root) {
18007
18482
  const tail = [];
18008
18483
  let current = root;
18009
18484
  for (; ; ) {
18010
- const parent = dirname3(current);
18485
+ const parent = dirname4(current);
18011
18486
  if (parent === current) unsafe();
18012
- tail.unshift(basename10(current));
18487
+ tail.unshift(basename11(current));
18013
18488
  current = parent;
18014
18489
  try {
18015
18490
  const real = await realpath4(current);
@@ -18024,7 +18499,7 @@ function overlaps(a, b) {
18024
18499
  return a === b || a.startsWith(`${b}${sep2}`) || b.startsWith(`${a}${sep2}`);
18025
18500
  }
18026
18501
  async function resolveWorktreeRoot(input) {
18027
- const root = input.configuredRoot ?? join13(dirname3(input.clone), DEFAULT_WORKTREE_ROOT_DIR);
18502
+ const root = input.configuredRoot ?? join13(dirname4(input.clone), DEFAULT_WORKTREE_ROOT_DIR);
18028
18503
  const segments2 = input.repository.toLowerCase().split("/");
18029
18504
  if (segments2.length !== 2 || segments2.some((segment) => !SEGMENT.test(segment))) unsafe();
18030
18505
  if (!/^[a-f0-9-]{36}$/.test(input.worktreeId)) unsafe();
@@ -18037,7 +18512,7 @@ async function resolveWorktreeRoot(input) {
18037
18512
  }
18038
18513
  const uid = input.uid ?? process.getuid?.();
18039
18514
  if (uid !== void 0) {
18040
- const info = await stat8(resolvedRoot).catch(() => void 0);
18515
+ const info = await stat9(resolvedRoot).catch(() => void 0);
18041
18516
  if (info !== void 0 && info.uid !== uid) unsafe();
18042
18517
  }
18043
18518
  return { root: resolvedRoot, recordPath };
@@ -18046,11 +18521,11 @@ function effectiveConfiguredWorktreeRoot(cliRoot, machineRoot) {
18046
18521
  return cliRoot ?? machineRoot;
18047
18522
  }
18048
18523
  function worktreeRootOfPath(recordPath) {
18049
- return dirname3(dirname3(dirname3(recordPath)));
18524
+ return dirname4(dirname4(dirname4(recordPath)));
18050
18525
  }
18051
18526
 
18052
18527
  // ../../core/packages/runner-core/src/worktree/release-steps.ts
18053
- import { unlink as unlink2 } from "node:fs/promises";
18528
+ import { unlink as unlink3 } from "node:fs/promises";
18054
18529
  import { join as join14 } from "node:path";
18055
18530
  function releasePolicyVerdict(record, input) {
18056
18531
  if (record.phase !== "releasing") return { conflict: false, upgrade: false };
@@ -18063,7 +18538,7 @@ async function forcedRemove(host, record) {
18063
18538
  await host.git(record.clone, ["worktree", "remove", "--force", host.pathOf(record)]);
18064
18539
  }
18065
18540
  async function ordinaryRemove(host, record, untrackedConfigs, recheckClean) {
18066
- for (const path of untrackedConfigs) await unlink2(join14(host.pathOf(record), path));
18541
+ for (const path of untrackedConfigs) await unlink3(join14(host.pathOf(record), path));
18067
18542
  try {
18068
18543
  await host.git(record.clone, ["worktree", "remove", host.pathOf(record)]);
18069
18544
  } catch (error) {
@@ -18668,7 +19143,7 @@ async function runSyncBase(ops, record, input) {
18668
19143
  // ../../core/packages/runner-core/src/worktree/setup-contract.ts
18669
19144
  import { constants as fsConstants2 } from "node:fs";
18670
19145
  import { lstat as lstat9, open as open4, realpath as realpath5 } from "node:fs/promises";
18671
- import { dirname as dirname4, join as join15 } from "node:path";
19146
+ import { dirname as dirname5, join as join15 } from "node:path";
18672
19147
  var COMPIVIA_DIR = ".compivia";
18673
19148
  var SETUP_SCRIPT = "setup.sh";
18674
19149
  var TEARDOWN_SCRIPT = "teardown.sh";
@@ -18782,7 +19257,7 @@ async function readRunEnvFile(worktree) {
18782
19257
  if (!st.isFile()) return { ok: false, reason: "unsafe_path" };
18783
19258
  if (st.size > RUN_ENV_MAX_BYTES) return { ok: false, reason: "too_large" };
18784
19259
  const [realDir, realFile] = await Promise.all([realpath5(dir), realpath5(path)]);
18785
- if (dirname4(realFile) !== realDir) return { ok: false, reason: "unsafe_path" };
19260
+ if (dirname5(realFile) !== realDir) return { ok: false, reason: "unsafe_path" };
18786
19261
  const handle = await open4(path, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW | fsConstants2.O_NONBLOCK);
18787
19262
  try {
18788
19263
  const { size } = await handle.stat();
@@ -19239,7 +19714,7 @@ var WorktreeService = class _WorktreeService {
19239
19714
  created = cas.created;
19240
19715
  startRevision = cas.startRevision;
19241
19716
  baseVerified = cas.baseVerified;
19242
- const worktreeId = randomUUID5();
19717
+ const worktreeId = randomUUID6();
19243
19718
  this.logger.info("worktree prepare started", {
19244
19719
  worktree_id: worktreeId,
19245
19720
  repository,
@@ -19262,7 +19737,7 @@ var WorktreeService = class _WorktreeService {
19262
19737
  boundClones
19263
19738
  });
19264
19739
  await this.safePath(resolved.root, resolved.recordPath, true);
19265
- await mkdir5(resolved.root, { recursive: true, mode: 448 });
19740
+ await mkdir6(resolved.root, { recursive: true, mode: 448 });
19266
19741
  await this.safePath(resolved.root, resolved.root);
19267
19742
  record.path = resolved.recordPath;
19268
19743
  } catch (error) {
@@ -19768,14 +20243,14 @@ var WorktreeService = class _WorktreeService {
19768
20243
  // сверяются по дескриптору, усечение даёт детерминированный file_changed.
19769
20244
  async guardedRead(root, file, maxBytes) {
19770
20245
  const full = join16(root, file);
19771
- const parent = join16(root, dirname5(file));
20246
+ const parent = join16(root, dirname6(file));
19772
20247
  await this.safePath(root, parent);
19773
20248
  let actualParent;
19774
20249
  try {
19775
20250
  actualParent = await realpath6(parent);
19776
20251
  } catch (error) {
19777
20252
  this.logger.warn("worktree path canonicalization failed", {
19778
- worktree_id: basename11(root),
20253
+ worktree_id: basename12(root),
19779
20254
  path: file,
19780
20255
  errno: error.code,
19781
20256
  err: error
@@ -19789,7 +20264,7 @@ var WorktreeService = class _WorktreeService {
19789
20264
  handle = await open5(full, fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW | fsConstants3.O_NONBLOCK);
19790
20265
  } catch (error) {
19791
20266
  this.logger.warn("worktree file open refused", {
19792
- worktree_id: basename11(root),
20267
+ worktree_id: basename12(root),
19793
20268
  path: file,
19794
20269
  errno: error.code
19795
20270
  });
@@ -19802,7 +20277,7 @@ var WorktreeService = class _WorktreeService {
19802
20277
  const stats = await handle.stat();
19803
20278
  if (!stats.isFile()) {
19804
20279
  this.logger.warn("worktree path is not a regular file", {
19805
- worktree_id: basename11(root),
20280
+ worktree_id: basename12(root),
19806
20281
  path: file,
19807
20282
  file_type: stats.isDirectory() ? "directory" : stats.isSymbolicLink() ? "symlink" : "other"
19808
20283
  });
@@ -19813,7 +20288,7 @@ var WorktreeService = class _WorktreeService {
19813
20288
  openedParent = await realpath6(parent);
19814
20289
  } catch (error) {
19815
20290
  this.logger.warn("worktree file stat failed", {
19816
- worktree_id: basename11(root),
20291
+ worktree_id: basename12(root),
19817
20292
  path: file,
19818
20293
  errno: error.code
19819
20294
  });
@@ -19826,7 +20301,7 @@ var WorktreeService = class _WorktreeService {
19826
20301
  pathStats = await statFile(full);
19827
20302
  } catch (error) {
19828
20303
  this.logger.warn("worktree file stat failed", {
19829
- worktree_id: basename11(root),
20304
+ worktree_id: basename12(root),
19830
20305
  path: file,
19831
20306
  errno: error.code
19832
20307
  });
@@ -19834,12 +20309,12 @@ var WorktreeService = class _WorktreeService {
19834
20309
  reject2("unsafe_path");
19835
20310
  }
19836
20311
  if (pathStats.dev !== stats.dev || pathStats.ino !== stats.ino) {
19837
- this.logger.warn("worktree file replaced during read", { worktree_id: basename11(root), path: file });
20312
+ this.logger.warn("worktree file replaced during read", { worktree_id: basename12(root), path: file });
19838
20313
  reject2("unsafe_path");
19839
20314
  }
19840
20315
  if (stats.size > maxBytes) {
19841
20316
  this.logger.warn("worktree file too large", {
19842
- worktree_id: basename11(root),
20317
+ worktree_id: basename12(root),
19843
20318
  path: file,
19844
20319
  size_bytes: stats.size,
19845
20320
  limit_bytes: maxBytes
@@ -19855,7 +20330,7 @@ var WorktreeService = class _WorktreeService {
19855
20330
  }
19856
20331
  if (read !== stats.size) {
19857
20332
  this.logger.warn("worktree file shrank during read", {
19858
- worktree_id: basename11(root),
20333
+ worktree_id: basename12(root),
19859
20334
  path: file,
19860
20335
  expected_bytes: stats.size,
19861
20336
  read_bytes: read
@@ -20115,7 +20590,7 @@ var WorktreeService = class _WorktreeService {
20115
20590
  if (managed(path)) remove.run(record.worktreeId, path);
20116
20591
  }
20117
20592
  for (const file of files) {
20118
- const hash = createHash4("sha256").update(await readFile6(file.path)).digest("hex");
20593
+ const hash = createHash4("sha256").update(await readFile7(file.path)).digest("hex");
20119
20594
  put.run(record.worktreeId, file.relative, hash);
20120
20595
  }
20121
20596
  await this.writeSetupExclude(record);
@@ -20124,10 +20599,10 @@ var WorktreeService = class _WorktreeService {
20124
20599
  const gitDir = join16(record.clone, ".git");
20125
20600
  await this.safePath(record.clone, gitDir);
20126
20601
  const info = join16(gitDir, "info");
20127
- await mkdir5(info, { recursive: true });
20602
+ await mkdir6(info, { recursive: true });
20128
20603
  let existing = "";
20129
20604
  try {
20130
- existing = await readFile6(join16(info, "exclude"), "utf8");
20605
+ existing = await readFile7(join16(info, "exclude"), "utf8");
20131
20606
  } catch (error) {
20132
20607
  if (error.code !== "ENOENT") throw error;
20133
20608
  }
@@ -20136,9 +20611,9 @@ var WorktreeService = class _WorktreeService {
20136
20611
  lines.add(pattern);
20137
20612
  }
20138
20613
  const target = join16(info, "exclude");
20139
- const temp = join16(info, `exclude.${randomUUID5()}.tmp`);
20140
- await writeFile2(temp, [...lines].join("\n") + "\n", { mode: 384 });
20141
- await rename(temp, target);
20614
+ const temp = join16(info, `exclude.${randomUUID6()}.tmp`);
20615
+ await writeFile3(temp, [...lines].join("\n") + "\n", { mode: 384 });
20616
+ await rename2(temp, target);
20142
20617
  }
20143
20618
  /** Окружение агента читается только из durable-записи, не из файла worktree:
20144
20619
  * агент мог подменить run.env между рестартами (#654 §5). */
@@ -20327,7 +20802,7 @@ var WorktreeService = class _WorktreeService {
20327
20802
  const gitFile = join16(this.path(record), ".git");
20328
20803
  const stats = await lstat10(gitFile);
20329
20804
  if (!stats.isFile() || stats.isSymbolicLink()) refuseIndirection("gitfile");
20330
- const content = await readFile6(gitFile, "utf8");
20805
+ const content = await readFile7(gitFile, "utf8");
20331
20806
  if (!content.startsWith("gitdir: ")) refuseIndirection("gitfile");
20332
20807
  const gitDir = resolve9(this.path(record), content.slice(8).trim());
20333
20808
  const rel = relative2(join16(record.clone, ".git", "worktrees"), gitDir);
@@ -20336,11 +20811,11 @@ var WorktreeService = class _WorktreeService {
20336
20811
  if (record.phase === "preparing" && await this.pathExists(join16(gitDir, "locked"))) reject2("worktree_incomplete", "failed");
20337
20812
  const commonFile = join16(gitDir, "commondir");
20338
20813
  const commonStat = await lstat10(commonFile);
20339
- if (!commonStat.isFile() || commonStat.isSymbolicLink() || resolve9(gitDir, (await readFile6(commonFile, "utf8")).trim()) !== join16(record.clone, ".git")) refuseIndirection("commondir");
20814
+ if (!commonStat.isFile() || commonStat.isSymbolicLink() || resolve9(gitDir, (await readFile7(commonFile, "utf8")).trim()) !== join16(record.clone, ".git")) refuseIndirection("commondir");
20340
20815
  const localConfig = join16(gitDir, "config.worktree");
20341
20816
  if (await this.pathExists(localConfig)) {
20342
- const stat11 = await lstat10(localConfig);
20343
- if (!stat11.isFile() || stat11.isSymbolicLink()) reject2("unsafe_path");
20817
+ const stat12 = await lstat10(localConfig);
20818
+ if (!stat12.isFile() || stat12.isSymbolicLink()) reject2("unsafe_path");
20344
20819
  const keys = await this.git(record.clone, ["config", "--file", localConfig, "--no-includes", "--name-only", "--list"]);
20345
20820
  const allowed = /^(?:user\.(?:name|email)|core\.(?:filemode|autocrlf|eol|safecrlf)|remote\..*\.(?:url|pushurl)|url\..*\.(?:insteadof|pushinsteadof))$/;
20346
20821
  const badKey = keys.split("\n").filter(Boolean).find((key) => !allowed.test(key));
@@ -20372,8 +20847,8 @@ var WorktreeService = class _WorktreeService {
20372
20847
  for (const part of ["", ...rel.split(sep3).filter(Boolean)]) {
20373
20848
  current = join16(current, part);
20374
20849
  try {
20375
- const stat11 = await lstat10(current);
20376
- if (stat11.isSymbolicLink() || !stat11.isDirectory()) reject2("unsafe_path");
20850
+ const stat12 = await lstat10(current);
20851
+ if (stat12.isSymbolicLink() || !stat12.isDirectory()) reject2("unsafe_path");
20377
20852
  } catch (error) {
20378
20853
  if (missing && error.code === "ENOENT") return;
20379
20854
  this.logger.warn("path safety check failed", {
@@ -20471,7 +20946,7 @@ var WorktreeService = class _WorktreeService {
20471
20946
  });
20472
20947
  if (path !== void 0) {
20473
20948
  this.logger.debug("git command finished", {
20474
- worktree_id: basename11(path),
20949
+ worktree_id: basename12(path),
20475
20950
  subcommand: subcommandOf2(args),
20476
20951
  exit_code: result.kind === "exited" ? result.exitCode : void 0,
20477
20952
  kind: result.kind,
@@ -20503,7 +20978,7 @@ var WorktreeService = class _WorktreeService {
20503
20978
  if (r.stdoutTruncated) reject2("git_output_truncated", "failed");
20504
20979
  if (r.exitCode !== 0) {
20505
20980
  this.logger.warn("git command failed", {
20506
- worktree_id: basename11(path),
20981
+ worktree_id: basename12(path),
20507
20982
  subcommand: subcommandOf2(args),
20508
20983
  exit_code: r.exitCode,
20509
20984
  reason,
@@ -20623,7 +21098,7 @@ var EvidenceService = class {
20623
21098
  /** Форма `evidence.collect` — публичная: обработчик команд проверяет её до
20624
21099
  * accepted; семантические отказы (неизвестные id/ревизия) — в run. */
20625
21100
  validateCollect(input) {
20626
- const invalid = (reason, field) => {
21101
+ const invalid2 = (reason, field) => {
20627
21102
  this.opts.logger.warn("evidence.collect rejected: invalid params", {
20628
21103
  reason,
20629
21104
  field,
@@ -20631,25 +21106,25 @@ var EvidenceService = class {
20631
21106
  });
20632
21107
  throw new CommandRejection("invalid", { reason });
20633
21108
  };
20634
- if (input.invocationId === void 0 === (input.sessionId === void 0)) invalid("bad_params", "session");
20635
- if (input.invocationId !== void 0 && (typeof input.invocationId !== "string" || !INVOCATION_ID.test(input.invocationId))) invalid("bad_params", "invocation_id");
21109
+ if (input.invocationId === void 0 === (input.sessionId === void 0)) invalid2("bad_params", "session");
21110
+ if (input.invocationId !== void 0 && (typeof input.invocationId !== "string" || !INVOCATION_ID.test(input.invocationId))) invalid2("bad_params", "invocation_id");
20636
21111
  if (input.sessionId !== void 0) {
20637
21112
  const sessionId = input.sessionId;
20638
- if (typeof sessionId !== "string" || sessionId.length === 0 || sessionId.length > 128 || sessionId.includes("/") || sessionId.includes("\\") || sessionId === "." || sessionId === "..") invalid("bad_params", "session_id");
21113
+ if (typeof sessionId !== "string" || sessionId.length === 0 || sessionId.length > 128 || sessionId.includes("/") || sessionId.includes("\\") || sessionId === "." || sessionId === "..") invalid2("bad_params", "session_id");
20639
21114
  }
20640
- if (typeof input.worktreeId !== "string" || !UUID2.test(input.worktreeId)) invalid("bad_params", "worktree_id");
20641
- if (typeof input.fromRevision !== "string" || !SHA2.test(input.fromRevision)) invalid("bad_params", "from_revision");
20642
- if (!Array.isArray(input.planPaths) || input.planPaths.length > MAX_PLAN_PATHS) invalid("bad_params", "plan_paths");
21115
+ if (typeof input.worktreeId !== "string" || !UUID2.test(input.worktreeId)) invalid2("bad_params", "worktree_id");
21116
+ if (typeof input.fromRevision !== "string" || !SHA2.test(input.fromRevision)) invalid2("bad_params", "from_revision");
21117
+ if (!Array.isArray(input.planPaths) || input.planPaths.length > MAX_PLAN_PATHS) invalid2("bad_params", "plan_paths");
20643
21118
  const seenPlans = /* @__PURE__ */ new Set();
20644
21119
  for (const path of input.planPaths) {
20645
- if (typeof path !== "string" || !safeRelative(path) || path.length > 1024) invalid("bad_params", "plan_path");
20646
- if (seenPlans.has(path)) invalid("bad_params", "plan_path");
21120
+ if (typeof path !== "string" || !safeRelative(path) || path.length > 1024) invalid2("bad_params", "plan_path");
21121
+ if (seenPlans.has(path)) invalid2("bad_params", "plan_path");
20647
21122
  seenPlans.add(path);
20648
21123
  }
20649
21124
  if (input.docsPaths !== void 0) {
20650
- if (!Array.isArray(input.docsPaths) || input.docsPaths.length > MAX_DOCS_PATHS) invalid("bad_params", "docs_paths");
21125
+ if (!Array.isArray(input.docsPaths) || input.docsPaths.length > MAX_DOCS_PATHS) invalid2("bad_params", "docs_paths");
20651
21126
  for (const path of input.docsPaths) {
20652
- if (typeof path !== "string" || !safeRelative(path) || path.length > 1024) invalid("bad_params", "docs_path");
21127
+ if (typeof path !== "string" || !safeRelative(path) || path.length > 1024) invalid2("bad_params", "docs_path");
20653
21128
  }
20654
21129
  }
20655
21130
  }
@@ -20907,7 +21382,7 @@ var EvidenceService = class {
20907
21382
 
20908
21383
  // ../../core/packages/runner-core/src/transcript/filter.ts
20909
21384
  import { Buffer as Buffer2 } from "node:buffer";
20910
- import { readFile as readFile7, readdir as readdir5 } from "node:fs/promises";
21385
+ import { readFile as readFile8, readdir as readdir5 } from "node:fs/promises";
20911
21386
  import { join as join17 } from "node:path";
20912
21387
  var SUMMARY_LIMIT_BYTES = 2048;
20913
21388
  var FRAME_BUDGET_BYTES = 8192;
@@ -20972,7 +21447,7 @@ async function envValuesFromRoot(root) {
20972
21447
  }
20973
21448
  const contents = [];
20974
21449
  for (const name of names) {
20975
- const content = await readFile7(join17(root, name), "utf8").catch(() => null);
21450
+ const content = await readFile8(join17(root, name), "utf8").catch(() => null);
20976
21451
  if (content !== null) contents.push(content);
20977
21452
  }
20978
21453
  return TranscriptRedactor.envValuesOf(contents);
@@ -21456,9 +21931,9 @@ function transcriptCommandHandlers(input) {
21456
21931
  }
21457
21932
 
21458
21933
  // ../../core/packages/runner-core/src/invocation/service.ts
21459
- import { randomUUID as randomUUID6 } from "node:crypto";
21460
- import { mkdir as mkdir6, readFile as readFile8, realpath as realpath7, rm, stat as stat9, writeFile as writeFile3 } from "node:fs/promises";
21461
- import { isAbsolute as isAbsolute8, join as join18, sep as sep4 } from "node:path";
21934
+ import { randomUUID as randomUUID7 } from "node:crypto";
21935
+ import { mkdir as mkdir7, readFile as readFile9, realpath as realpath7, rm, stat as stat10, writeFile as writeFile4 } from "node:fs/promises";
21936
+ import { isAbsolute as isAbsolute9, join as join18, sep as sep4 } from "node:path";
21462
21937
 
21463
21938
  // ../../core/packages/runner-core/src/invocation/denial-summary.ts
21464
21939
  var LOG_TAIL_BYTES = 256 * 1024;
@@ -21637,6 +22112,7 @@ async function appendCheckpointRecord(outcome, invocationId, payload) {
21637
22112
  }
21638
22113
 
21639
22114
  // ../../core/packages/runner-core/src/invocation/service.ts
22115
+ var ONBOARDING_REQUIRED_REASON = "onboarding_required";
21640
22116
  function logSafe9(logger, level, msg, fields) {
21641
22117
  try {
21642
22118
  logger[level](msg, fields);
@@ -21802,7 +22278,7 @@ var InvocationService = class {
21802
22278
  const adapter = this.adapterOf(params.harness);
21803
22279
  await this.assertLaunchable(params);
21804
22280
  const scratchDir = join18(this.opts.scratchRoot, params.invocationId);
21805
- await mkdir6(scratchDir, { recursive: true, mode: 448 });
22281
+ await mkdir7(scratchDir, { recursive: true, mode: 448 });
21806
22282
  return await this.startIn(scratchDir, params, adapter, outcome);
21807
22283
  });
21808
22284
  } catch (error) {
@@ -21831,7 +22307,7 @@ var InvocationService = class {
21831
22307
  async spawnStart(scratchDir, params, adapter, externalDir) {
21832
22308
  const { launch, sessionId, logFile, cwd, promptFile, contract } = await this.writeLaunchInputs(scratchDir, params, adapter, externalDir);
21833
22309
  if (launch.transcriptPath !== null) {
21834
- await mkdir6(join18(launch.transcriptPath, ".."), { recursive: true }).catch((error) => this.bestEffortUndefined(error, "mkdir", params.invocationId));
22310
+ await mkdir7(join18(launch.transcriptPath, ".."), { recursive: true }).catch((error) => this.bestEffortUndefined(error, "mkdir", params.invocationId));
21835
22311
  }
21836
22312
  const track = {
21837
22313
  invocationId: params.invocationId,
@@ -21863,7 +22339,7 @@ var InvocationService = class {
21863
22339
 
21864
22340
  ${contract.preamble}
21865
22341
  `;
21866
- await writeFile3(promptFile, prompt, { mode: 384 });
22342
+ await writeFile4(promptFile, prompt, { mode: 384 });
21867
22343
  let outputSchemaText = null;
21868
22344
  if (params.outputSchema !== void 0) {
21869
22345
  outputSchemaText = JSON.stringify(params.outputSchema);
@@ -21873,10 +22349,10 @@ ${contract.preamble}
21873
22349
  }
21874
22350
  const outputSchemaFile = outputSchemaText === null ? null : await (async () => {
21875
22351
  const path = join18(scratchDir, "output-schema.json");
21876
- await writeFile3(path, outputSchemaText, { mode: 384 });
22352
+ await writeFile4(path, outputSchemaText, { mode: 384 });
21877
22353
  return path;
21878
22354
  })();
21879
- const sessionId = params.resume !== void 0 ? params.resume.sessionId : randomUUID6();
22355
+ const sessionId = params.resume !== void 0 ? params.resume.sessionId : randomUUID7();
21880
22356
  const logFile = join18(scratchDir, "wrapper.log");
21881
22357
  const cwd = externalDir !== void 0 ? externalDir : await this.resolveCwd(params.worktreeId, scratchDir);
21882
22358
  const launchInput = {
@@ -22102,7 +22578,7 @@ ${contract.preamble}
22102
22578
  /** Сайдкар-манифест старта: phaseRunId/worktreeId переживают рестарт
22103
22579
  * runner'а (checkpoint и snapshot/heartbeat после подхвата). */
22104
22580
  async writeStartManifest(invocationId, scratchDir, params) {
22105
- await writeFile3(join18(scratchDir, "invocation.json"), JSON.stringify({
22581
+ await writeFile4(join18(scratchDir, "invocation.json"), JSON.stringify({
22106
22582
  ...params.phaseRunId !== void 0 ? { phaseRunId: params.phaseRunId } : {},
22107
22583
  ...params.worktreeId !== void 0 ? { worktreeId: params.worktreeId } : {}
22108
22584
  }), { mode: 384 }).catch((error) => {
@@ -22144,7 +22620,7 @@ ${contract.preamble}
22144
22620
  /** Форма `agent.start` — публичная: обработчик команд делегирует её сюда,
22145
22621
  * чтобы правила формы не расходились между слоями. */
22146
22622
  validateStart(params) {
22147
- const invalid = (reason) => {
22623
+ const invalid2 = (reason) => {
22148
22624
  logSafe9(this.logger, "warn", "agent.start rejected: invalid params", {
22149
22625
  reason,
22150
22626
  invocation_id: typeof params.invocationId === "string" ? params.invocationId : null,
@@ -22153,13 +22629,13 @@ ${contract.preamble}
22153
22629
  });
22154
22630
  throw new CommandRejection("invalid", { reason });
22155
22631
  };
22156
- if (typeof params.invocationId !== "string" || params.invocationId === "") return invalid("invocationId_required");
22157
- if (!ID_PATTERN.test(params.invocationId)) return invalid("invocationId_invalid");
22158
- if (!ACTIVE_MODES.has(params.mode)) return invalid("mode_invalid");
22159
- if (params.resume !== void 0 && (typeof params.resume.sessionId !== "string" || params.resume.sessionId === "")) return invalid("resume_session_required");
22160
- if (params.resume !== void 0 && !ID_PATTERN.test(params.resume.sessionId)) return invalid("resume_session_invalid");
22161
- if (params.systemPrompt !== void 0 && params.mode !== "sessionless") return invalid("system_prompt_sessionless_only");
22162
- if (typeof params.prompt !== "string" || params.prompt === "") return invalid("prompt_required");
22632
+ if (typeof params.invocationId !== "string" || params.invocationId === "") return invalid2("invocationId_required");
22633
+ if (!ID_PATTERN.test(params.invocationId)) return invalid2("invocationId_invalid");
22634
+ if (!ACTIVE_MODES.has(params.mode)) return invalid2("mode_invalid");
22635
+ if (params.resume !== void 0 && (typeof params.resume.sessionId !== "string" || params.resume.sessionId === "")) return invalid2("resume_session_required");
22636
+ if (params.resume !== void 0 && !ID_PATTERN.test(params.resume.sessionId)) return invalid2("resume_session_invalid");
22637
+ if (params.systemPrompt !== void 0 && params.mode !== "sessionless") return invalid2("system_prompt_sessionless_only");
22638
+ if (typeof params.prompt !== "string" || params.prompt === "") return invalid2("prompt_required");
22163
22639
  }
22164
22640
  adapterOf(harness) {
22165
22641
  const adapter = this.opts.adapters.get(harness);
@@ -22270,7 +22746,7 @@ ${contract.preamble}
22270
22746
  if (typeof dir !== "string" || dir === "") {
22271
22747
  throw new CommandRejection("invalid", { reason: "dir_required" });
22272
22748
  }
22273
- if (!isAbsolute8(dir)) throw new CommandRejection("invalid", { reason: "dir_not_absolute" });
22749
+ if (!isAbsolute9(dir)) throw new CommandRejection("invalid", { reason: "dir_not_absolute" });
22274
22750
  let real;
22275
22751
  try {
22276
22752
  real = await realpath7(dir);
@@ -22282,7 +22758,7 @@ ${contract.preamble}
22282
22758
  });
22283
22759
  throw new CommandRejection("invalid", { reason: "dir_not_found" });
22284
22760
  }
22285
- const info = await stat9(real).catch((error) => {
22761
+ const info = await stat10(real).catch((error) => {
22286
22762
  logSafe9(this.logger, "warn", "invocation.external_dir_stat_failed", {
22287
22763
  err_code: errnoOf(error),
22288
22764
  reason: "dir_stat_failed",
@@ -22624,7 +23100,7 @@ ${contract.preamble}
22624
23100
  this.externalSinks.set(params.invocationId, outcome);
22625
23101
  const scratchDir = join18(this.opts.scratchRoot, params.invocationId);
22626
23102
  try {
22627
- await mkdir6(scratchDir, { recursive: true, mode: 448 });
23103
+ await mkdir7(scratchDir, { recursive: true, mode: 448 });
22628
23104
  return await this.spawnStart(scratchDir, params, adapter, dir);
22629
23105
  } catch (error) {
22630
23106
  await this.abandonFailedStart(params.invocationId, error, true);
@@ -22653,6 +23129,14 @@ ${contract.preamble}
22653
23129
  throw new CommandRejection("unavailable", { reason: "harness_signin_needed" });
22654
23130
  }
22655
23131
  }
23132
+ if (this.opts.harnessVerdict !== void 0) {
23133
+ const verdicts = await this.opts.harnessVerdict();
23134
+ const verdict = verdicts?.get(params.harness);
23135
+ if (verdict?.compatibility === "needs_setup" && verdict.compatibilityReason === ONBOARDING_REQUIRED_REASON) {
23136
+ logSafe9(this.logger, "warn", "agent.start rejected: harness needs setup", { harness: params.harness, reason: "harness_needs_setup" });
23137
+ throw new CommandRejection("unavailable", { reason: "harness_needs_setup" });
23138
+ }
23139
+ }
22656
23140
  const active = await this.busyCount();
22657
23141
  if (active >= this.opts.slotsTotal) {
22658
23142
  logSafe9(this.logger, "warn", "agent.start rejected: no free slot", {
@@ -23165,7 +23649,7 @@ ${contract.preamble}
23165
23649
  // agent.stop
23166
23650
  /** Форма `agent.stop` — публичная: обработчик команд делегирует её сюда. */
23167
23651
  validateStop(params) {
23168
- const invalid = (reason) => {
23652
+ const invalid2 = (reason) => {
23169
23653
  logSafe9(this.logger, "warn", "agent.stop rejected: invalid params", {
23170
23654
  reason,
23171
23655
  invocation_id: typeof params.invocationId === "string" ? params.invocationId : null,
@@ -23173,8 +23657,8 @@ ${contract.preamble}
23173
23657
  });
23174
23658
  throw new CommandRejection("invalid", { reason });
23175
23659
  };
23176
- if (typeof params.invocationId !== "string" || params.invocationId === "") return invalid("invocationId_required");
23177
- if (params.mode !== "graceful" && params.mode !== "hard") return invalid("mode_invalid");
23660
+ if (typeof params.invocationId !== "string" || params.invocationId === "") return invalid2("invocationId_required");
23661
+ if (params.mode !== "graceful" && params.mode !== "hard") return invalid2("mode_invalid");
23178
23662
  }
23179
23663
  /** Форма agent.stop — диспетчер над тремя путями (раунд 1 Architecture:
23180
23664
  * lost-receipt, acknowledgment доставленного терминала, обычная лестница);
@@ -23799,7 +24283,7 @@ ${contract.preamble}
23799
24283
  if (opts.remove === true) await this.opts.registry.remove(record.processId).catch((error) => this.bestEffortUndefined(error));
23800
24284
  }
23801
24285
  async readManifest(invocationId) {
23802
- const raw = await readFile8(join18(this.opts.scratchRoot, invocationId, "invocation.json"), "utf8").catch((error) => this.bestEffortNull(error, "readManifest", invocationId));
24286
+ const raw = await readFile9(join18(this.opts.scratchRoot, invocationId, "invocation.json"), "utf8").catch((error) => this.bestEffortNull(error, "readManifest", invocationId));
23803
24287
  if (raw === null) return null;
23804
24288
  try {
23805
24289
  const parsed = JSON.parse(raw);
@@ -23843,16 +24327,16 @@ function clipFinal(text, invocationId, logger) {
23843
24327
  }
23844
24328
 
23845
24329
  // ../../core/packages/runner-core/src/runner-cli.ts
23846
- import { existsSync as existsSync5, statSync as statSync7 } from "node:fs";
23847
- import { isAbsolute as isAbsolute9 } from "node:path";
23848
- import { dirname as dirname8, join as join21, resolve as resolve10 } from "node:path";
24330
+ import { existsSync as existsSync7, statSync as statSync9 } from "node:fs";
24331
+ import { isAbsolute as isAbsolute10 } from "node:path";
24332
+ import { dirname as dirname9, join as join22, resolve as resolve10 } from "node:path";
23849
24333
  import { parseArgs } from "node:util";
23850
24334
 
23851
24335
  // ../../core/packages/runner-core/src/runner-process.ts
23852
- import { dirname as dirname7, join as join20 } from "node:path";
24336
+ import { dirname as dirname8, join as join21 } from "node:path";
23853
24337
 
23854
24338
  // ../../core/packages/runner-core/src/inventory/auto-bind.ts
23855
- import { readFile as readFile9, stat as stat10 } from "node:fs/promises";
24339
+ import { readFile as readFile10, stat as stat11 } from "node:fs/promises";
23856
24340
  var AutoBinder = class {
23857
24341
  constructor(options) {
23858
24342
  this.options = options;
@@ -23927,7 +24411,7 @@ var AutoBinder = class {
23927
24411
  if (this.options.repositoriesPath === void 0) return [];
23928
24412
  let stats;
23929
24413
  try {
23930
- stats = await stat10(this.options.repositoriesPath);
24414
+ stats = await stat11(this.options.repositoriesPath);
23931
24415
  } catch (error) {
23932
24416
  if (errnoOf(error) === "ENOENT") {
23933
24417
  this.cache = null;
@@ -23943,7 +24427,7 @@ var AutoBinder = class {
23943
24427
  }
23944
24428
  let parsed;
23945
24429
  try {
23946
- parsed = JSON.parse(await readFile9(this.options.repositoriesPath, "utf8"));
24430
+ parsed = JSON.parse(await readFile10(this.options.repositoriesPath, "utf8"));
23947
24431
  } catch {
23948
24432
  this.options.logger.warn("runner repositories file ignored", { reason: "malformed_json" });
23949
24433
  this.cache = { mtimeMs: stats.mtimeMs, size: stats.size, repositories: this.lastValid };
@@ -23974,9 +24458,9 @@ var AutoBinder = class {
23974
24458
 
23975
24459
  // ../../core/packages/runner-core/src/inventory/autonomy.ts
23976
24460
  import { createHash as createHash5 } from "node:crypto";
23977
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
23978
- import { join as join19, dirname as dirname6 } from "node:path";
23979
- import { randomUUID as randomUUID7 } from "node:crypto";
24461
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
24462
+ import { join as join19, dirname as dirname7 } from "node:path";
24463
+ import { randomUUID as randomUUID8 } from "node:crypto";
23980
24464
  var TRANSIENT_REASONS = /* @__PURE__ */ new Set(["agent_error", "probe_timeout", "probe_unavailable"]);
23981
24465
  var REASON_PATTERN = /^[a-z][a-z0-9_]{2,63}$/;
23982
24466
  var PROBE_PROMPT = "Create a file named probe.txt containing exactly the text probe-ok in the current directory, then commit it with the message probe. Do not read or change anything else.";
@@ -23999,7 +24483,7 @@ function policyOf(harness) {
23999
24483
  function readCache(cachePath, logger) {
24000
24484
  let raw;
24001
24485
  try {
24002
- raw = readFileSync3(cachePath, "utf8");
24486
+ raw = readFileSync5(cachePath, "utf8");
24003
24487
  } catch (error) {
24004
24488
  const code = error.code;
24005
24489
  if (code !== void 0 && code !== "ENOENT") logger.warn("inventory.autonomy_cache_unreadable", { code });
@@ -24030,8 +24514,8 @@ function readCache(cachePath, logger) {
24030
24514
  }
24031
24515
  }
24032
24516
  function writeCache(cachePath, cache) {
24033
- const tmp = `${cachePath}.${randomUUID7()}.tmp`;
24034
- mkdirSync2(dirname6(cachePath), { recursive: true });
24517
+ const tmp = `${cachePath}.${randomUUID8()}.tmp`;
24518
+ mkdirSync2(dirname7(cachePath), { recursive: true });
24035
24519
  writeFileSync2(tmp, `${JSON.stringify(cache)}
24036
24520
  `, { mode: 384 });
24037
24521
  renameSync(tmp, cachePath);
@@ -24088,7 +24572,7 @@ function autonomyProbesOf(deps) {
24088
24572
  try {
24089
24573
  const adapter = adapters.get(harness.id);
24090
24574
  if (adapter?.autonomyCheck === void 0) return;
24091
- const sandbox = join19(probeRoot, `${sandboxNameOf(harness.id)}-${randomUUID7()}`);
24575
+ const sandbox = join19(probeRoot, `${sandboxNameOf(harness.id)}-${randomUUID8()}`);
24092
24576
  try {
24093
24577
  mkdirSync2(sandbox, { recursive: true, mode: 448 });
24094
24578
  mkdirSync2(join19(sandbox, ".git", "info"), { recursive: true });
@@ -24118,7 +24602,7 @@ function autonomyProbesOf(deps) {
24118
24602
  verdict = verdictOf(outcome, () => {
24119
24603
  let probeText;
24120
24604
  try {
24121
- probeText = readFileSync3(join19(sandbox, "probe.txt"), "utf8");
24605
+ probeText = readFileSync5(join19(sandbox, "probe.txt"), "utf8");
24122
24606
  } catch {
24123
24607
  probeText = void 0;
24124
24608
  }
@@ -24217,6 +24701,395 @@ function autonomyProbesOf(deps) {
24217
24701
  };
24218
24702
  }
24219
24703
 
24704
+ // ../../core/packages/runner-core/src/reporter/host.ts
24705
+ import { createHash as createHash6 } from "node:crypto";
24706
+ import { join as join20 } from "node:path";
24707
+ function reporterHostDataDir(instanceDataDir, entry) {
24708
+ const identity = `${entry.package}@${entry.version}#${entry.subscription}`;
24709
+ const suffix = createHash6("sha256").update(identity).digest("hex").slice(0, 16);
24710
+ const slug = entry.package.replace(/^@/, "").replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 40);
24711
+ return join20(instanceDataDir, "plugin-host", `reporter-${slug || "package"}-${suffix}`);
24712
+ }
24713
+ function createReporterHost(entry, opts) {
24714
+ const manager = new PluginHostManager(
24715
+ {
24716
+ package: entry.package,
24717
+ version: entry.version,
24718
+ kind: "reporter",
24719
+ id: entry.reporterId,
24720
+ dir: entry.dir,
24721
+ options: entry.options,
24722
+ envNames: entry.envNames,
24723
+ secrets: entry.secrets,
24724
+ subscription: entry.subscription,
24725
+ dataDir: reporterHostDataDir(opts.instanceDataDir, entry)
24726
+ },
24727
+ { baseEnv: opts.baseEnv, ...opts.hostOptions },
24728
+ opts.logger
24729
+ );
24730
+ return {
24731
+ probe: (timeoutMs) => manager.call("probe", {}, timeoutMs),
24732
+ dispose: () => manager.dispose()
24733
+ };
24734
+ }
24735
+
24736
+ // ../../core/packages/runner-core/src/reporter/resolve.ts
24737
+ var import_semver2 = __toESM(require_semver2(), 1);
24738
+ import { basename as basename13 } from "node:path";
24739
+ function reporterRefOf(pkg, version, reporterId) {
24740
+ return version === void 0 ? `${pkg}#${reporterId}` : `${pkg}@${version}#${reporterId}`;
24741
+ }
24742
+ function contributionIdOf(config) {
24743
+ return config.reporter ?? config.subscription;
24744
+ }
24745
+ function dirVersionOf(dir) {
24746
+ return (0, import_semver2.valid)(basename13(dir)) ?? void 0;
24747
+ }
24748
+ function validateOptionsAgainstSchema(options, schema) {
24749
+ if (schema === void 0) return { ok: true };
24750
+ const props = schema.properties ?? {};
24751
+ if (schema.additionalProperties === false) {
24752
+ for (const key of Object.keys(options)) {
24753
+ if (!(key in props)) return { ok: false, detail: `options.${key}: unknown field` };
24754
+ }
24755
+ }
24756
+ for (const key of schema.required ?? []) {
24757
+ if (!(key in options)) return { ok: false, detail: `options.${key}: required` };
24758
+ }
24759
+ for (const [key, raw] of Object.entries(options)) {
24760
+ const prop = props[key];
24761
+ if (prop === null || typeof prop !== "object") continue;
24762
+ const expected = prop.type;
24763
+ if (typeof expected !== "string") continue;
24764
+ const actual = Array.isArray(raw) ? "array" : raw === null ? "null" : typeof raw;
24765
+ const match = expected === "integer" ? typeof raw === "number" && Number.isInteger(raw) : actual === expected;
24766
+ if (!match) return { ok: false, detail: `options.${key}: expected ${expected}` };
24767
+ }
24768
+ return { ok: true };
24769
+ }
24770
+ function resolveReporters(opts) {
24771
+ if (opts.config.length === 0) return { entries: [], failed: [] };
24772
+ const installed = opts.pluginsRoot !== void 0 && opts.pluginsRoot !== "" ? scanInstalledPlugins(opts.pluginsRoot) : [];
24773
+ const entries = [];
24774
+ const failed = [];
24775
+ for (const config of opts.config) {
24776
+ const result = resolveOne(config, installed, opts);
24777
+ if ("entry" in result) entries.push(result.entry);
24778
+ else failed.push(result.failed);
24779
+ }
24780
+ return { entries, failed };
24781
+ }
24782
+ function unavailableFailure(config, installed, opts) {
24783
+ const broken = installed.find((candidate) => "error" in candidate && candidate.package === config.package);
24784
+ if (broken === void 0 || !("error" in broken)) {
24785
+ return { subscription: config.subscription, reporter: reporterRefOf(config.package, void 0, contributionIdOf(config)), status: { failed: "not_installed" } };
24786
+ }
24787
+ const reason = broken.error.includes("apiVersion") ? "incompatible_api" : "load_failed";
24788
+ opts.logger.warn("reporter package unreadable", { subscription: config.subscription, package: config.package, reason });
24789
+ return {
24790
+ subscription: config.subscription,
24791
+ reporter: reporterRefOf(config.package, dirVersionOf(broken.dir), contributionIdOf(config)),
24792
+ status: { failed: reason }
24793
+ };
24794
+ }
24795
+ function reporterContribution(config, present) {
24796
+ const reporters = present.manifest.contributions.filter((candidate) => candidate.kind === "reporter");
24797
+ if (config.reporter !== void 0) return reporters.find((candidate) => candidate.id === config.reporter);
24798
+ return reporters.length === 1 ? reporters[0] : void 0;
24799
+ }
24800
+ function resolveOne(config, installed, opts) {
24801
+ const present = installed.find((candidate) => "package" in candidate && "manifest" in candidate && candidate.package === config.package);
24802
+ if (present === void 0) return { failed: unavailableFailure(config, installed, opts) };
24803
+ const contribution = reporterContribution(config, present);
24804
+ const ref = (id) => reporterRefOf(config.package, present.version, id);
24805
+ if (contribution === void 0) {
24806
+ return { failed: { subscription: config.subscription, reporter: ref(contributionIdOf(config)), status: { failed: "load_failed" } } };
24807
+ }
24808
+ const options = validateOptionsAgainstSchema(config.options, contribution.optionsSchema);
24809
+ if (!options.ok) {
24810
+ opts.logger.warn("reporter options rejected", { subscription: config.subscription, package: config.package, id: contribution.id, reason: "invalid_options" });
24811
+ return { failed: { subscription: config.subscription, reporter: ref(contribution.id), status: { failed: "invalid_options" } } };
24812
+ }
24813
+ const missingEnv = config.env.filter((name) => opts.baseEnv[name] === void 0);
24814
+ if (missingEnv.length > 0) {
24815
+ opts.logger.warn("reporter env missing", { subscription: config.subscription, package: config.package, id: contribution.id, names: missingEnv.join(",") });
24816
+ return { failed: { subscription: config.subscription, reporter: ref(contribution.id), status: { failed: "missing_env" } } };
24817
+ }
24818
+ return {
24819
+ entry: {
24820
+ subscription: config.subscription,
24821
+ package: config.package,
24822
+ version: present.version,
24823
+ reporterId: contribution.id,
24824
+ dir: present.dir,
24825
+ options: config.options,
24826
+ envNames: config.env,
24827
+ secrets: contribution.secrets ?? [],
24828
+ intervalMinutes: config.intervalMinutes,
24829
+ timeoutSeconds: config.timeoutSeconds
24830
+ }
24831
+ };
24832
+ }
24833
+
24834
+ // ../../core/packages/runner-core/src/reporter/fingerprint.ts
24835
+ import { createHmac } from "node:crypto";
24836
+ function accountFingerprint(salt, accountId) {
24837
+ return createHmac("sha256", salt).update(accountId).digest("hex");
24838
+ }
24839
+ function fingerprintOf2(report, salt) {
24840
+ if (salt === void 0 || report.accountId === void 0) return void 0;
24841
+ return accountFingerprint(salt, report.accountId);
24842
+ }
24843
+
24844
+ // ../../core/packages/runner-core/src/reporter/report.ts
24845
+ var RFC33393 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
24846
+ function isPlainObject6(value) {
24847
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24848
+ }
24849
+ function invalid(detail) {
24850
+ return { ok: false, reason: "invalid_report", detail };
24851
+ }
24852
+ function validateWindow(raw, index, seen) {
24853
+ const at = `report.windows[${index}]`;
24854
+ if (!isPlainObject6(raw)) return { ok: false, detail: `${at}: expected an object` };
24855
+ for (const key of Object.keys(raw)) {
24856
+ if (!["id", "usedPercent", "resetsAt", "durationSec", "label"].includes(key)) {
24857
+ return { ok: false, detail: `${at}.${key}: unknown field` };
24858
+ }
24859
+ }
24860
+ if (typeof raw.id !== "string" || raw.id === "") return { ok: false, detail: `${at}.id: expected a non-empty string` };
24861
+ if (seen.has(raw.id)) return { ok: false, detail: `${at}.id: duplicate id` };
24862
+ seen.add(raw.id);
24863
+ if (typeof raw.usedPercent !== "number" || !Number.isFinite(raw.usedPercent) || raw.usedPercent < 0 || raw.usedPercent > 100) {
24864
+ return { ok: false, detail: `${at}.usedPercent: expected a finite number in 0..100` };
24865
+ }
24866
+ const window = { id: raw.id, usedPercent: raw.usedPercent };
24867
+ if (raw.resetsAt !== void 0) {
24868
+ if (typeof raw.resetsAt !== "string" || !RFC33393.test(raw.resetsAt)) return { ok: false, detail: `${at}.resetsAt: expected an RFC 3339 timestamp` };
24869
+ window.resetsAt = raw.resetsAt;
24870
+ }
24871
+ if (raw.durationSec !== void 0) {
24872
+ if (typeof raw.durationSec !== "number" || !Number.isSafeInteger(raw.durationSec) || raw.durationSec < 1) {
24873
+ return { ok: false, detail: `${at}.durationSec: expected a positive safe integer` };
24874
+ }
24875
+ window.durationSec = raw.durationSec;
24876
+ }
24877
+ if (raw.label !== void 0) {
24878
+ if (typeof raw.label !== "string" || raw.label === "") return { ok: false, detail: `${at}.label: expected a non-empty string` };
24879
+ window.label = raw.label;
24880
+ }
24881
+ return { ok: true, window };
24882
+ }
24883
+ function validateUsageReport(report, opts) {
24884
+ if (!isPlainObject6(report)) return invalid("report: expected an object");
24885
+ for (const key of Object.keys(report)) {
24886
+ if (!["windows", "observedAt", "accountId"].includes(key)) return invalid(`report.${key}: unknown field`);
24887
+ }
24888
+ if (!Array.isArray(report.windows)) return invalid("report.windows: expected an array");
24889
+ if (opts.apiVersion === 1 && report.windows.length === 0) return invalid("report.windows: expected a non-empty array for apiVersion 1");
24890
+ const windows2 = [];
24891
+ const seen = /* @__PURE__ */ new Set();
24892
+ for (const raw of report.windows) {
24893
+ const result = validateWindow(raw, windows2.length, seen);
24894
+ if (!result.ok) return invalid(result.detail);
24895
+ windows2.push(result.window);
24896
+ }
24897
+ const validated = { windows: windows2 };
24898
+ if (report.observedAt !== void 0) {
24899
+ if (typeof report.observedAt !== "string" || !RFC33393.test(report.observedAt)) return invalid("report.observedAt: expected an RFC 3339 timestamp");
24900
+ validated.observedAt = report.observedAt;
24901
+ }
24902
+ if (report.accountId !== void 0) {
24903
+ if (typeof report.accountId !== "string" || report.accountId === "") return invalid("report.accountId: expected a non-empty string");
24904
+ validated.accountId = report.accountId;
24905
+ }
24906
+ return { ok: true, report: validated };
24907
+ }
24908
+
24909
+ // ../../core/packages/runner-core/src/reporter/scheduler.ts
24910
+ var MAX_INTERVAL_MS = 60 * 6e4;
24911
+ var MAX_TIMER_DELAY_MS = 2147483647;
24912
+ var realTimers = {
24913
+ setTimeout: (fn, ms) => {
24914
+ const handle = globalThis.setTimeout(fn, ms);
24915
+ handle.unref?.();
24916
+ return handle;
24917
+ },
24918
+ clearTimeout: (handle) => globalThis.clearTimeout(handle)
24919
+ };
24920
+ var ReporterScheduler = class {
24921
+ constructor(opts) {
24922
+ this.opts = opts;
24923
+ this.timers = opts.timers ?? realTimers;
24924
+ this.maxIntervalMs = opts.maxIntervalMs ?? MAX_INTERVAL_MS;
24925
+ this.states = opts.entries.map((entry) => ({
24926
+ entry,
24927
+ intervalMs: entry.intervalMinutes * 6e4,
24928
+ probing: false,
24929
+ timer: void 0,
24930
+ host: opts.createHost(entry),
24931
+ disposed: false
24932
+ }));
24933
+ }
24934
+ opts;
24935
+ states;
24936
+ timers;
24937
+ maxIntervalMs;
24938
+ disposed = false;
24939
+ started = false;
24940
+ /** Первый тик каждой записи — немедленно по плану §5.2. */
24941
+ start() {
24942
+ if (this.started) return;
24943
+ this.started = true;
24944
+ for (const state of this.states) this.schedule(state, 0);
24945
+ }
24946
+ /** Таймеры стоп, хосты dispose (grace 5 с у manager); идемпотентен. */
24947
+ async dispose() {
24948
+ if (this.disposed) return;
24949
+ this.disposed = true;
24950
+ for (const state of this.states) {
24951
+ state.disposed = true;
24952
+ if (state.timer !== void 0) {
24953
+ this.timers.clearTimeout(state.timer);
24954
+ state.timer = void 0;
24955
+ }
24956
+ }
24957
+ await Promise.all(this.states.map((state) => state.host.dispose()));
24958
+ }
24959
+ schedule(state, delayMs) {
24960
+ if (this.disposed || state.disposed) return;
24961
+ state.timer = this.timers.setTimeout(() => {
24962
+ state.timer = void 0;
24963
+ void this.tick(state);
24964
+ }, Math.min(Math.max(0, delayMs), MAX_TIMER_DELAY_MS));
24965
+ }
24966
+ tick(state) {
24967
+ if (this.disposed || state.disposed || state.probing) return;
24968
+ state.probing = true;
24969
+ void this.probeOnce(state).catch((error) => {
24970
+ this.opts.logger.warn("reporter probe cycle failed", {
24971
+ subscription: state.entry.subscription,
24972
+ err: error
24973
+ });
24974
+ }).finally(() => {
24975
+ state.probing = false;
24976
+ if (!this.disposed && !state.disposed) this.schedule(state, state.intervalMs);
24977
+ });
24978
+ }
24979
+ async probeOnce(state) {
24980
+ const { entry } = state;
24981
+ const reporter = reporterRefOf(entry.package, entry.version, entry.reporterId);
24982
+ let report;
24983
+ try {
24984
+ report = await state.host.probe(entry.timeoutSeconds * 1e3);
24985
+ } catch (error) {
24986
+ this.onFailure(state, error instanceof PluginHostDownError ? `host_${error.reason}` : "probe_error");
24987
+ return;
24988
+ }
24989
+ if (report === null) {
24990
+ this.setStatus(entry.subscription, "idle");
24991
+ return;
24992
+ }
24993
+ const validated = validateUsageReport(report, { apiVersion: 1 });
24994
+ if (!validated.ok) {
24995
+ this.onFailure(state, "invalid_report");
24996
+ return;
24997
+ }
24998
+ await this.recordSnapshot(state, validated.report, reporter);
24999
+ }
25000
+ async recordSnapshot(state, report, reporter) {
25001
+ const { entry } = state;
25002
+ if (await this.opts.journal.isFull()) {
25003
+ this.opts.logger.warn("reporter snapshot skipped: journal full", { subscription: entry.subscription, reporter });
25004
+ return;
25005
+ }
25006
+ const fingerprint3 = fingerprintOf2(report, this.opts.salt());
25007
+ const payload = {
25008
+ subscription: entry.subscription,
25009
+ observedAt: report.observedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
25010
+ windows: report.windows,
25011
+ ...fingerprint3 !== void 0 ? { accountFingerprint: fingerprint3 } : {},
25012
+ source: { kind: "probe", reporter }
25013
+ };
25014
+ const record = { type: "limits.snapshot", payload };
25015
+ try {
25016
+ await this.opts.journal.append(record);
25017
+ } catch (error) {
25018
+ this.opts.logger.warn("reporter snapshot append failed", { subscription: entry.subscription, reporter, err: error });
25019
+ this.setStatus(entry.subscription, "degraded");
25020
+ return;
25021
+ }
25022
+ state.intervalMs = state.entry.intervalMinutes * 6e4;
25023
+ this.setStatus(entry.subscription, "ok");
25024
+ }
25025
+ onFailure(state, reason) {
25026
+ state.intervalMs = Math.min(state.intervalMs * 2, this.maxIntervalMs);
25027
+ this.opts.logger.warn("reporter probe failed", {
25028
+ subscription: state.entry.subscription,
25029
+ reporter: reporterRefOf(state.entry.package, state.entry.version, state.entry.reporterId),
25030
+ reason
25031
+ });
25032
+ this.setStatus(state.entry.subscription, "degraded");
25033
+ }
25034
+ setStatus(subscription, status) {
25035
+ this.opts.onStatus(subscription, status);
25036
+ }
25037
+ };
25038
+
25039
+ // ../../core/packages/runner-core/src/reporter/wiring.ts
25040
+ function mountReporters(opts) {
25041
+ const resolved = resolveReporters({
25042
+ config: opts.config,
25043
+ pluginsRoot: opts.pluginsRoot,
25044
+ baseEnv: opts.baseEnv,
25045
+ logger: opts.logger
25046
+ });
25047
+ const statuses = new Map(
25048
+ resolved.failed.map((failed) => [failed.subscription, failed])
25049
+ );
25050
+ const reporterSalt = { value: void 0 };
25051
+ let scheduler;
25052
+ if (resolved.entries.length > 0) {
25053
+ scheduler = new ReporterScheduler({
25054
+ entries: resolved.entries,
25055
+ journal: opts.journal,
25056
+ createHost: opts.createHost ?? ((entry) => createReporterHost(entry, {
25057
+ instanceDataDir: opts.instanceDataDir,
25058
+ baseEnv: opts.baseEnv,
25059
+ logger: opts.logger
25060
+ })),
25061
+ salt: () => reporterSalt.value,
25062
+ onStatus: (subscription, status) => {
25063
+ const entry = resolved.entries.find((candidate) => candidate.subscription === subscription);
25064
+ if (entry === void 0) return;
25065
+ statuses.set(subscription, {
25066
+ subscription,
25067
+ reporter: reporterRefOf(entry.package, entry.version, entry.reporterId),
25068
+ status
25069
+ });
25070
+ opts.onStatus?.(subscription, status);
25071
+ },
25072
+ logger: opts.logger,
25073
+ ...opts.timers !== void 0 ? { timers: opts.timers } : {}
25074
+ });
25075
+ }
25076
+ return { scheduler, statuses, reporterSalt };
25077
+ }
25078
+ function setupReporters(opts) {
25079
+ return mountReporters({ ...opts, ...opts.refresh === void 0 ? {} : { onStatus: opts.refresh } });
25080
+ }
25081
+ function applyReporterSalt(holder, ack) {
25082
+ holder.value = ack.fingerprintSalt;
25083
+ }
25084
+ async function disposeReporters(scheduler, logger) {
25085
+ if (scheduler === void 0) return;
25086
+ try {
25087
+ await scheduler.dispose();
25088
+ } catch (error) {
25089
+ logger.warn("reporter.dispose_failed", { err: error });
25090
+ }
25091
+ }
25092
+
24220
25093
  // ../../core/packages/runner-core/src/worktree/setup-teardown-wiring.ts
24221
25094
  function wireSetupTeardown(invocations, worktrees, logger) {
24222
25095
  return invocations.onTerminal((terminal) => {
@@ -24369,6 +25242,9 @@ async function runRunnerProcess(start, io) {
24369
25242
  bindings.close();
24370
25243
  return 1;
24371
25244
  }
25245
+ for (const section of machineConfigEmptySections(machine)) {
25246
+ io.logger.warn("machine config section is empty", { path: config.machineConfigPath, section, reason: "empty" });
25247
+ }
24372
25248
  let userPlugins;
24373
25249
  if (config.userSettingsPath !== void 0) {
24374
25250
  try {
@@ -24376,7 +25252,8 @@ async function runRunnerProcess(start, io) {
24376
25252
  } catch (error) {
24377
25253
  io.logger.error("user settings unreadable", {
24378
25254
  file: config.userSettingsPath,
24379
- detail: error instanceof Error ? error.message : "unknown"
25255
+ detail: error instanceof Error ? error.message : "unknown",
25256
+ err: error
24380
25257
  });
24381
25258
  bindings.close();
24382
25259
  registry?.close();
@@ -24418,7 +25295,7 @@ async function runRunnerProcess(start, io) {
24418
25295
  // `worktree.root`; отсутствие обоих — дефолт сервиса рядом с клоном.
24419
25296
  ...worktreeRoot !== void 0 ? { worktreeRoot } : {},
24420
25297
  // Патчи checkpoint'ов — рядом с журналом: один каталог данных runner'а (#564).
24421
- checkpointsDir: join20(dirname7(config.journalPath), "checkpoints"),
25298
+ checkpointsDir: join21(dirname8(config.journalPath), "checkpoints"),
24422
25299
  activeWorktreeInvocations: async (worktreeId) => (await invocationsRef?.snapshot() ?? { invocations: [] }).invocations.some((entry) => entry.worktreeId === worktreeId),
24423
25300
  // Контракт .compivia (#654): валидация harness'а машины и окружение
24424
25301
  // скрипта без секретов runner'а (deny-list по имени).
@@ -24455,18 +25332,40 @@ async function runRunnerProcess(start, io) {
24455
25332
  pluginsRoot: config.pluginsRoot,
24456
25333
  machinePlugins: machine.plugins,
24457
25334
  userPlugins,
24458
- instanceDataDir: dirname7(config.journalPath),
24459
- baseEnv: process.env,
25335
+ instanceDataDir: dirname8(config.journalPath),
25336
+ // #872: env-файл для configSource — путь #873 (envPath = $COMPIVIA_INSTANCE_DIR/env),
25337
+ // композитор ставит его из --agent-env; нет флага — instance-источника нет (R0 #873).
25338
+ ...config.instanceEnvFile !== void 0 ? { instanceEnvFile: config.instanceEnvFile } : {},
25339
+ ...config.homeDir !== void 0 ? { homeDir: config.homeDir } : {},
25340
+ // #873: карта экземпляра — нижний слой и для инвентаря/проб, и для хостов
25341
+ // плагинов (host-manager берёт envNames из baseEnv).
25342
+ baseEnv: { ...process.env, ...start.agentEnv ?? {} },
25343
+ ...start.agentEnv !== void 0 ? { agentEnv: start.agentEnv } : {},
24460
25344
  logger: io.logger
24461
25345
  });
25346
+ if (start.agentEnv !== void 0) {
25347
+ io.logger.debug("agent env applied", { [KEY_ENV_KEY_COUNT]: Object.keys(start.agentEnv).length });
25348
+ }
24462
25349
  const adapters = detectorSet.adapters;
25350
+ let refreshReporterInventory = () => void 0;
25351
+ const mountedReporters = setupReporters({
25352
+ config: machine.reporters ?? [],
25353
+ pluginsRoot: config.pluginsRoot,
25354
+ baseEnv: process.env,
25355
+ instanceDataDir: dirname8(config.journalPath),
25356
+ journal,
25357
+ logger: io.logger,
25358
+ refresh: () => refreshReporterInventory()
25359
+ });
25360
+ const reporters = mountedReporters.scheduler;
25361
+ const reporterSalt = mountedReporters.reporterSalt;
24463
25362
  let inventoryRef;
24464
25363
  let invocations;
24465
25364
  const probes = autonomyProbesOf({
24466
25365
  harnesses: machine.harnesses,
24467
25366
  adapters,
24468
- cachePath: join20(dirname7(config.journalPath), "harness-autonomy.json"),
24469
- probeRoot: join20(dirname7(config.journalPath), "autonomy-probe"),
25367
+ cachePath: join21(dirname8(config.journalPath), "harness-autonomy.json"),
25368
+ probeRoot: join21(dirname8(config.journalPath), "autonomy-probe"),
24470
25369
  runner: commandRunner,
24471
25370
  refresh: () => refreshInventory(),
24472
25371
  logger: io.logger,
@@ -24484,12 +25383,25 @@ async function runRunnerProcess(start, io) {
24484
25383
  stallTimeoutMsByHarness: new Map(machine.harnesses.map((harness) => [harness.id, (harness.stallTimeoutMinutes ?? 20) * 6e4])),
24485
25384
  slotsTotal: machine.slots.total,
24486
25385
  scratchRoot: `${config.bindingsPath}.scratch`,
24487
- baseEnv: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "" },
25386
+ // #873: env-файл экземпляра ложится поверх PATH/HOME; специализированные
25387
+ // слои run.env/launch.env/identity накладываются выше в buildLaunchEnv.
25388
+ baseEnv: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", ...start.agentEnv ?? {} },
24488
25389
  harnessStatus: async () => {
24489
25390
  const snapshot = inventoryRef?.lastSnapshot();
24490
25391
  if (snapshot === void 0 || snapshot === null) return null;
24491
25392
  return new Map(snapshot.agents.map((agent) => [agent.id, agent.status]));
24492
25393
  },
25394
+ // Вердикты автономности (#872 D6): постоянная needs_setup-причина
25395
+ // отклоняет agent.start, включая лестницу повторов движка. Тот же снимок
25396
+ // инвентаря, что и harnessStatus — без повторных проб и лишнего чтения.
25397
+ harnessVerdict: async () => {
25398
+ const snapshot = inventoryRef?.lastSnapshot();
25399
+ if (snapshot === void 0 || snapshot === null) return null;
25400
+ return new Map(snapshot.agents.map((agent) => [agent.id, {
25401
+ compatibility: agent.compatibility,
25402
+ compatibilityReason: agent.compatibilityReason
25403
+ }]));
25404
+ },
24493
25405
  worktrees: {
24494
25406
  resolvePath: (worktreeId) => worktrees.resolvePath(worktreeId),
24495
25407
  checkpoint: (worktreeId, message, hint) => worktrees.checkpoint(worktreeId, message, hint),
@@ -24524,6 +25436,8 @@ async function runRunnerProcess(start, io) {
24524
25436
  capabilities: runnerCapabilities(machine),
24525
25437
  // Привязки в снимке и refresh статусов git-доступа (задача #14).
24526
25438
  bindings: repoBindings,
25439
+ // Статусы репортеров (#130 §9): смена триггерит inventory.changed.
25440
+ reporters: () => [...mountedReporters.statuses.values()],
24527
25441
  autoBind: autoBinder === void 0 ? void 0 : (clones) => autoBinder.run(clones),
24528
25442
  journal,
24529
25443
  logger: io.logger,
@@ -24591,6 +25505,7 @@ async function runRunnerProcess(start, io) {
24591
25505
  void flight.catch(() => void 0);
24592
25506
  }
24593
25507
  };
25508
+ refreshReporterInventory = refreshInventory;
24594
25509
  const testHandlers = testCommandHandlers();
24595
25510
  const inventoryHandlers = inventoryCommandHandlers(inventory);
24596
25511
  const agentHandlers = agentCommandHandlers(invocations, io.logger);
@@ -24648,14 +25563,15 @@ async function runRunnerProcess(start, io) {
24648
25563
  });
24649
25564
  commands.start();
24650
25565
  io.logger.info("runner.channel_started", { channel: "commands" });
25566
+ const heartbeatIntervalMs = config.heartbeatIntervalMs ?? RUN_HEARTBEAT_INTERVAL_MS;
24651
25567
  const heartbeats = new HeartbeatChannel({
24652
25568
  connection: engineConnection,
24653
25569
  invocations: () => invocations.heartbeatInvocations(),
24654
- intervalMs: RUN_HEARTBEAT_INTERVAL_MS,
25570
+ intervalMs: heartbeatIntervalMs,
24655
25571
  logger: io.logger
24656
25572
  });
24657
25573
  heartbeats.start();
24658
- io.logger.info("runner.channel_started", { channel: "heartbeats", interval_ms: RUN_HEARTBEAT_INTERVAL_MS });
25574
+ io.logger.info("runner.channel_started", { channel: "heartbeats", interval_ms: heartbeatIntervalMs });
24659
25575
  refreshInventory();
24660
25576
  const inventoryTimer = setInterval(refreshInventory, config.inventoryIntervalMs);
24661
25577
  inventoryTimer.unref();
@@ -24672,6 +25588,8 @@ async function runRunnerProcess(start, io) {
24672
25588
  connectedStatus = snapshot.status;
24673
25589
  });
24674
25590
  engineConnection.onHelloAck((ack) => {
25591
+ applyReporterSalt(reporterSalt, ack);
25592
+ reporters?.start();
24675
25593
  io.logger.info("connection.hello_ack", {
24676
25594
  runner_id: connection.runnerId,
24677
25595
  runner_version: runnerVersion,
@@ -24716,6 +25634,8 @@ async function runRunnerProcess(start, io) {
24716
25634
  io.write(mode === "keep-agents" ? `stopping\u2026${count} agent(s) left running for adoption
24717
25635
  ` : `stopping\u2026${count} agent(s)
24718
25636
  `);
25637
+ step = "reporters_dispose";
25638
+ await disposeReporters(reporters, io.logger);
24719
25639
  step = "stop_all";
24720
25640
  try {
24721
25641
  await (mode === "keep-agents" ? invocations.detachAll() : invocations.stopAll());
@@ -24794,6 +25714,7 @@ var START_OPTIONS = {
24794
25714
  "machine-config": { type: "string" },
24795
25715
  repositories: { type: "string" },
24796
25716
  "inventory-interval-ms": { type: "string" },
25717
+ "heartbeat-interval-ms": { type: "string" },
24797
25718
  "user-settings": { type: "string" },
24798
25719
  "plugins-root": { type: "string" },
24799
25720
  "worktree-root": { type: "string" }
@@ -24832,25 +25753,25 @@ function parseRunnerStartArgs(argv, env, extraOptions) {
24832
25753
  if (journalPath === void 0 || journalPath === "") {
24833
25754
  throw new RunnerCliUsageError("--journal: runner journal file path is required (the runner syncs its journal with the engine)");
24834
25755
  }
24835
- const commandsPath = stringValue(values.commands) ?? join21(dirname8(journalPath), "runner-commands.sqlite");
24836
- const bindingsPath = stringValue(values.bindings) ?? join21(dirname8(journalPath), "runner-bindings.sqlite");
25756
+ const commandsPath = stringValue(values.commands) ?? join22(dirname9(journalPath), "runner-commands.sqlite");
25757
+ const bindingsPath = stringValue(values.bindings) ?? join22(dirname9(journalPath), "runner-bindings.sqlite");
24837
25758
  const machineConfigFlag = stringValue(values["machine-config"]);
24838
- const machineConfigPath = machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG ?? join21(dirname8(journalPath), "machine.json");
24839
- if ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 && !existsSync5(machineConfigPath)) {
25759
+ const machineConfigPath = machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG ?? join22(dirname9(journalPath), "machine.json");
25760
+ if ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 && !existsSync7(machineConfigPath)) {
24840
25761
  throw new RunnerCliUsageError(`--machine-config: file not found: ${machineConfigPath}`);
24841
25762
  }
24842
25763
  const repositoriesFlag = stringValue(values.repositories);
24843
25764
  const repositoriesPath = repositoriesFlag ?? env.COMPIVIA_RUNNER_REPOSITORIES;
24844
- if (repositoriesPath !== void 0 && repositoriesPath !== "" && !existsSync5(repositoriesPath)) {
25765
+ if (repositoriesPath !== void 0 && repositoriesPath !== "" && !existsSync7(repositoriesPath)) {
24845
25766
  throw new RunnerCliUsageError(`--repositories: file not found: ${repositoriesPath}`);
24846
25767
  }
24847
25768
  const userSettingsPath = stringValue(values["user-settings"]) ?? env.COMPIVIA_RUNNER_USER_SETTINGS;
24848
- if (userSettingsPath !== void 0 && !existsSync5(userSettingsPath)) {
25769
+ if (userSettingsPath !== void 0 && !existsSync7(userSettingsPath)) {
24849
25770
  throw new RunnerCliUsageError(`--user-settings: file not found: ${userSettingsPath}`);
24850
25771
  }
24851
25772
  const pluginsRootFlag = stringValue(values["plugins-root"]) ?? env.COMPIVIA_RUNNER_PLUGINS_ROOT;
24852
- const pluginsRoot = pluginsRootFlag ?? ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 ? join21(dirname8(machineConfigPath), "plugins") : void 0);
24853
- if (pluginsRootFlag !== void 0 && pluginsRoot !== void 0 && !existsSync5(pluginsRoot)) {
25773
+ const pluginsRoot = pluginsRootFlag ?? ((machineConfigFlag ?? env.COMPIVIA_RUNNER_MACHINE_CONFIG) !== void 0 ? join22(dirname9(machineConfigPath), "plugins") : void 0);
25774
+ if (pluginsRootFlag !== void 0 && pluginsRoot !== void 0 && !existsSync7(pluginsRoot)) {
24854
25775
  throw new RunnerCliUsageError(`--plugins-root: directory not found: ${pluginsRoot}`);
24855
25776
  }
24856
25777
  const backoff = {
@@ -24861,7 +25782,7 @@ function parseRunnerStartArgs(argv, env, extraOptions) {
24861
25782
  throw new RunnerCliUsageError("--backoff-max-ms: must not be smaller than --backoff-initial-ms");
24862
25783
  }
24863
25784
  const worktreeRootFlag = stringValue(values["worktree-root"]) ?? env.COMPIVIA_RUNNER_WORKTREE_ROOT;
24864
- if (worktreeRootFlag !== void 0 && (worktreeRootFlag === "" || !isAbsolute9(worktreeRootFlag))) {
25785
+ if (worktreeRootFlag !== void 0 && (worktreeRootFlag === "" || !isAbsolute10(worktreeRootFlag))) {
24865
25786
  throw new RunnerCliUsageError("--worktree-root: expected an absolute path");
24866
25787
  }
24867
25788
  return {
@@ -24873,6 +25794,7 @@ function parseRunnerStartArgs(argv, env, extraOptions) {
24873
25794
  machineConfigPath,
24874
25795
  ...repositoriesPath === "" ? {} : { repositoriesPath },
24875
25796
  inventoryIntervalMs: parseMs(stringValue(values["inventory-interval-ms"]), "--inventory-interval-ms", 6e4),
25797
+ heartbeatIntervalMs: parseMs(stringValue(values["heartbeat-interval-ms"]), "--heartbeat-interval-ms", 15e3),
24876
25798
  ...userSettingsPath !== void 0 && userSettingsPath !== "" ? { userSettingsPath } : {},
24877
25799
  ...pluginsRoot !== void 0 && pluginsRoot !== "" ? { pluginsRoot } : {},
24878
25800
  ...worktreeRootFlag !== void 0 ? { worktreeRoot: worktreeRootFlag } : {}
@@ -24923,14 +25845,15 @@ async function runConfigCheck(argv, io, env) {
24923
25845
  };
24924
25846
  if (explicit) {
24925
25847
  try {
24926
- statSync7(path);
25848
+ statSync9(path);
24927
25849
  } catch (error) {
24928
25850
  const errno = errnoOf(error);
24929
25851
  io.logger.warn("runner.machine_config_check_failed", { path, errno, err: error });
24930
25852
  return fail(errno === "ENOENT" ? `file not found: ${path}` : `machine config is unreadable: ${errno}`);
24931
25853
  }
24932
- } else if (!existsSync5(path)) {
24933
- io.write(`${JSON.stringify({ ok: true, path, empty: true, permissionModes: {} })}
25854
+ } else if (!existsSync7(path)) {
25855
+ const warnings = machineConfigWarningTexts(emptyMachineInventoryConfig(), path).map((entry) => entry.text);
25856
+ io.write(`${JSON.stringify({ ok: true, path, empty: true, permissionModes: {}, warnings })}
24934
25857
  `);
24935
25858
  return 0;
24936
25859
  }
@@ -24950,7 +25873,9 @@ async function runConfigCheck(argv, io, env) {
24950
25873
  cloneRoots: config.cloneRoots.length,
24951
25874
  // Presence-флаг корня worktree'ов (#660 §4.1): значение не выводится.
24952
25875
  worktreeRoot: config.worktree?.root !== void 0,
24953
- permissionModes
25876
+ permissionModes,
25877
+ // #995: пустые секции — warnings в ok-отчёте (D9), код выхода не меняется.
25878
+ warnings: machineConfigWarningTexts(config, path).map((entry) => entry.text)
24954
25879
  })}
24955
25880
  `
24956
25881
  );
@@ -24962,6 +25887,7 @@ async function runConfigCheck(argv, io, env) {
24962
25887
  }
24963
25888
 
24964
25889
  // src/commands.ts
25890
+ import { existsSync as existsSync9 } from "node:fs";
24965
25891
  import { parseArgs as parseArgs2 } from "node:util";
24966
25892
 
24967
25893
  // src/pairing.ts
@@ -25259,9 +26185,9 @@ async function journalHasUnconfirmedEvents(journalPath, runnerId, logger = noopL
25259
26185
 
25260
26186
  // src/token-store.ts
25261
26187
  import { randomBytes } from "node:crypto";
25262
- import { lstat as lstat11, link as link2, mkdir as mkdir7, open as open7, readFile as readFile10, unlink as unlink3 } from "node:fs/promises";
25263
- import { homedir as homedir3 } from "node:os";
25264
- import { basename as basename12, dirname as dirname9, join as join22 } from "node:path";
26188
+ import { lstat as lstat11, link as link3, mkdir as mkdir8, open as open7, readFile as readFile11, unlink as unlink4 } from "node:fs/promises";
26189
+ import { homedir as homedir4 } from "node:os";
26190
+ import { basename as basename14, dirname as dirname10, join as join23 } from "node:path";
25265
26191
  var TokenStoreError = class extends Error {
25266
26192
  constructor(message, options) {
25267
26193
  super(message, options);
@@ -25269,8 +26195,8 @@ var TokenStoreError = class extends Error {
25269
26195
  }
25270
26196
  };
25271
26197
  var RUNNER_ID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
25272
- function defaultCredentialsPath(home = homedir3()) {
25273
- return join22(home, ".compivia", "runner-platform", "credentials.json");
26198
+ function defaultCredentialsPath(home = homedir4()) {
26199
+ return join23(home, ".compivia", "runner-platform", "credentials.json");
25274
26200
  }
25275
26201
  async function credentialsFileExists(path) {
25276
26202
  try {
@@ -25307,9 +26233,9 @@ async function assertPrivateDir(dir, logger = noopLogger) {
25307
26233
  }
25308
26234
  }
25309
26235
  async function prepareCredentialsDir(path, logger = noopLogger) {
25310
- const dir = dirname9(path);
26236
+ const dir = dirname10(path);
25311
26237
  try {
25312
- await mkdir7(dir, { recursive: true, mode: 448 });
26238
+ await mkdir8(dir, { recursive: true, mode: 448 });
25313
26239
  await assertPrivateDir(dir, logger);
25314
26240
  } catch (error) {
25315
26241
  if (error instanceof TokenStoreError) throw error;
@@ -25337,8 +26263,8 @@ async function assertSafeRegularFile(path, logger = noopLogger) {
25337
26263
  }
25338
26264
  }
25339
26265
  async function publishAtomically(path, contents, logger) {
25340
- const dir = dirname9(path);
25341
- const base = join22(dir, `.${basename12(path)}.tmp-${randomBytes(8).toString("hex")}`);
26266
+ const dir = dirname10(path);
26267
+ const base = join23(dir, `.${basename14(path)}.tmp-${randomBytes(8).toString("hex")}`);
25342
26268
  try {
25343
26269
  let handle;
25344
26270
  try {
@@ -25349,7 +26275,7 @@ async function publishAtomically(path, contents, logger) {
25349
26275
  await handle?.close();
25350
26276
  }
25351
26277
  try {
25352
- await link2(base, path);
26278
+ await link3(base, path);
25353
26279
  } catch (error) {
25354
26280
  if (error.code === "EEXIST") {
25355
26281
  throw new TokenStoreError(`credentials file already exists: ${path}`);
@@ -25367,7 +26293,7 @@ async function publishAtomically(path, contents, logger) {
25367
26293
  }
25368
26294
  }
25369
26295
  } finally {
25370
- await unlink3(base).catch((error) => {
26296
+ await unlink4(base).catch((error) => {
25371
26297
  logger.warn("temporary credentials file cleanup failed", {
25372
26298
  err: error,
25373
26299
  operation: "unlink",
@@ -25377,8 +26303,8 @@ async function publishAtomically(path, contents, logger) {
25377
26303
  }
25378
26304
  }
25379
26305
  async function createCredentialsFile(path, value, logger = noopLogger) {
25380
- const dir = dirname9(path);
25381
- await mkdir7(dir, { recursive: true, mode: 448 });
26306
+ const dir = dirname10(path);
26307
+ await mkdir8(dir, { recursive: true, mode: 448 });
25382
26308
  await assertPrivateDir(dir, logger);
25383
26309
  const contents = `${JSON.stringify(value, null, 2)}
25384
26310
  `;
@@ -25389,7 +26315,7 @@ async function createCredentialsFile(path, value, logger = noopLogger) {
25389
26315
  }
25390
26316
  async function readCredentialsFile(path, logger = noopLogger) {
25391
26317
  await assertSafeRegularFile(path, logger);
25392
- const raw = await readFile10(path, "utf8");
26318
+ const raw = await readFile11(path, "utf8");
25393
26319
  let parsed;
25394
26320
  try {
25395
26321
  parsed = JSON.parse(raw);
@@ -25429,8 +26355,8 @@ async function readCredentialsFile(path, logger = noopLogger) {
25429
26355
  }
25430
26356
 
25431
26357
  // src/manifest.ts
25432
- import { readFileSync as readFileSync4 } from "node:fs";
25433
- import { dirname as dirname10 } from "node:path";
26358
+ import { readFileSync as readFileSync6 } from "node:fs";
26359
+ import { dirname as dirname11 } from "node:path";
25434
26360
  import { fileURLToPath as fileURLToPath4 } from "node:url";
25435
26361
  var ManifestError = class extends Error {
25436
26362
  constructor(message) {
@@ -25441,7 +26367,7 @@ var ManifestError = class extends Error {
25441
26367
  var MODE_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
25442
26368
  var COMMAND_WORD_PATTERN = /^[a-z][a-z0-9-]*$/;
25443
26369
  var MANIFEST_FIELDS = /* @__PURE__ */ new Set(["mode", "wrapperCompat", "description", "commands"]);
25444
- function readOwnPackage(baseDir = dirname10(fileURLToPath4(import.meta.url))) {
26370
+ function readOwnPackage(baseDir = dirname11(fileURLToPath4(import.meta.url))) {
25445
26371
  const pkg = readJsonFile2(`${baseDir}/../package.json`);
25446
26372
  if (pkg !== null) {
25447
26373
  if (typeof pkg.name !== "string" || typeof pkg.version !== "string") {
@@ -25461,7 +26387,7 @@ function readOwnPackage(baseDir = dirname10(fileURLToPath4(import.meta.url))) {
25461
26387
  }
25462
26388
  function readJsonFile2(path) {
25463
26389
  try {
25464
- const parsed = JSON.parse(readFileSync4(path, "utf8"));
26390
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
25465
26391
  return typeof parsed === "object" && parsed !== null ? parsed : null;
25466
26392
  } catch {
25467
26393
  return null;
@@ -25537,15 +26463,15 @@ function runnerPlatformVersion() {
25537
26463
  }
25538
26464
 
25539
26465
  // src/instance.ts
25540
- import { readFileSync as readFileSync5 } from "node:fs";
25541
- import { chmod as chmod3, mkdir as mkdir8, writeFile as writeFile4 } from "node:fs/promises";
25542
- import { basename as basename13, dirname as dirname11, join as join23 } from "node:path";
26466
+ import { readFileSync as readFileSync7 } from "node:fs";
26467
+ import { chmod as chmod4, mkdir as mkdir9, writeFile as writeFile5 } from "node:fs/promises";
26468
+ import { basename as basename15, dirname as dirname12, join as join24 } from "node:path";
25543
26469
  var CREDENTIALS_ENV = "COMPIVIA_RUNNER_CREDENTIALS";
25544
26470
  function resolveInstance(env, flags) {
25545
26471
  const instanceDir = nonEmpty(env.COMPIVIA_INSTANCE_DIR) ?? null;
25546
- const instanceId = nonEmpty(env.COMPIVIA_INSTANCE) ?? (instanceDir !== null ? basename13(instanceDir) : null);
25547
- const credentialsPath = nonEmpty(flags?.credentials) ?? nonEmpty(env[CREDENTIALS_ENV]) ?? (instanceDir !== null ? join23(instanceDir, "credentials.json") : defaultCredentialsPath());
25548
- const dataDir = nonEmpty(flags?.dataDir) ?? nonEmpty(env.COMPIVIA_DATA_DIR) ?? (instanceDir !== null ? join23(instanceDir, "data") : null);
26472
+ const instanceId = nonEmpty(env.COMPIVIA_INSTANCE) ?? (instanceDir !== null ? basename15(instanceDir) : null);
26473
+ const credentialsPath = nonEmpty(flags?.credentials) ?? nonEmpty(env[CREDENTIALS_ENV]) ?? (instanceDir !== null ? join24(instanceDir, "credentials.json") : defaultCredentialsPath());
26474
+ const dataDir = nonEmpty(flags?.dataDir) ?? nonEmpty(env.COMPIVIA_DATA_DIR) ?? (instanceDir !== null ? join24(instanceDir, "data") : null);
25549
26475
  return { instanceId, instanceDir, credentialsPath, dataDir };
25550
26476
  }
25551
26477
  function nonEmpty(value) {
@@ -25556,17 +26482,17 @@ function resolveJournalPath(env, flags, paths) {
25556
26482
  if (fromFlags !== void 0) return fromFlags;
25557
26483
  const fromEnv = nonEmpty(env.COMPIVIA_RUNNER_JOURNAL);
25558
26484
  if (fromEnv !== void 0) return fromEnv;
25559
- if (paths.dataDir !== null) return join23(paths.dataDir, "runner-journal.sqlite");
25560
- return join23(dirname11(paths.credentialsPath), "runner-journal.sqlite");
26485
+ if (paths.dataDir !== null) return join24(paths.dataDir, "runner-journal.sqlite");
26486
+ return join24(dirname12(paths.credentialsPath), "runner-journal.sqlite");
25561
26487
  }
25562
26488
  async function ensurePrivateDir(dir) {
25563
- await mkdir8(dir, { recursive: true, mode: 448 });
25564
- await chmod3(dir, 448);
26489
+ await mkdir9(dir, { recursive: true, mode: 448 });
26490
+ await chmod4(dir, 448);
25565
26491
  }
25566
26492
  function readLocalJson(dataDir) {
25567
26493
  let raw;
25568
26494
  try {
25569
- raw = readFileSync5(join23(dataDir, "local.json"), "utf8");
26495
+ raw = readFileSync7(join24(dataDir, "local.json"), "utf8");
25570
26496
  } catch {
25571
26497
  return null;
25572
26498
  }
@@ -25584,8 +26510,8 @@ function readLocalJson(dataDir) {
25584
26510
  return value;
25585
26511
  }
25586
26512
  async function writeLocalJson(dataDir, value) {
25587
- await mkdir8(dataDir, { recursive: true });
25588
- await writeFile4(join23(dataDir, "local.json"), `${JSON.stringify(value)}
26513
+ await mkdir9(dataDir, { recursive: true });
26514
+ await writeFile5(join24(dataDir, "local.json"), `${JSON.stringify(value)}
25589
26515
  `, { encoding: "utf8", mode: 384 });
25590
26516
  }
25591
26517
  function resolveWrapperVersion(env) {
@@ -25594,7 +26520,7 @@ function resolveWrapperVersion(env) {
25594
26520
  const home = nonEmpty(env.COMPIVIA_HOME);
25595
26521
  if (home === void 0) return void 0;
25596
26522
  try {
25597
- const raw = JSON.parse(readFileSync5(join23(home, "current", "set.json"), "utf8"));
26523
+ const raw = JSON.parse(readFileSync7(join24(home, "current", "set.json"), "utf8"));
25598
26524
  if (typeof raw !== "object" || raw === null) return void 0;
25599
26525
  const wrapper = raw.wrapper;
25600
26526
  if (typeof wrapper !== "object" || wrapper === null) return void 0;
@@ -25605,6 +26531,94 @@ function resolveWrapperVersion(env) {
25605
26531
  }
25606
26532
  }
25607
26533
 
26534
+ // src/machine-config.ts
26535
+ import { existsSync as existsSync8 } from "node:fs";
26536
+ import { mkdtemp, rm as rm2 } from "node:fs/promises";
26537
+ import { homedir as homedir5, tmpdir } from "node:os";
26538
+ import { join as join25 } from "node:path";
26539
+ var MACHINE_CONFIG_ENV = "COMPIVIA_RUNNER_MACHINE_CONFIG";
26540
+ var HOME_ENV = "COMPIVIA_HOME";
26541
+ function resolveHome(env) {
26542
+ const fromEnv = nonEmpty2(env[HOME_ENV]);
26543
+ return fromEnv ?? join25(homedir5(), ".compivia");
26544
+ }
26545
+ function resolveMachineConfigPath(argv, env, home) {
26546
+ return scanFlagValue(argv, "--machine-config") ?? nonEmpty2(env[MACHINE_CONFIG_ENV]) ?? join25(home, "machine.json");
26547
+ }
26548
+ function hasExplicitMachineConfig(argv, env) {
26549
+ return argv.some((token) => token === "--machine-config" || token.startsWith("--machine-config=")) || nonEmpty2(env[MACHINE_CONFIG_ENV]) !== void 0;
26550
+ }
26551
+ function defaultCloneRoots(env, home) {
26552
+ const instanceDir = resolveInstance(env).instanceDir;
26553
+ return [instanceDir !== null ? join25(instanceDir, "work") : join25(home, "clones")];
26554
+ }
26555
+ async function ensureCloudMachineConfig(options) {
26556
+ const logger = options.logger;
26557
+ const pluginsRoot = join25(options.home, "plugins");
26558
+ const instanceDataDir = await mkdtemp(join25(tmpdir(), "compivia-runner-bootstrap-"));
26559
+ logger.debug("machine config detection dir prepared", { path: instanceDataDir });
26560
+ try {
26561
+ const result = await bootstrapMachineConfig({
26562
+ path: options.path,
26563
+ cloneRoots: defaultCloneRoots(options.env, options.home),
26564
+ baseEnv: options.env,
26565
+ instanceDataDir,
26566
+ ...existsSync8(pluginsRoot) ? { pluginsRoot } : {},
26567
+ logger,
26568
+ ...options.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
26569
+ });
26570
+ return { path: result.path, created: result.created, warnings: result.warnings };
26571
+ } finally {
26572
+ const removed = await rm2(instanceDataDir, { recursive: true, force: true }).then(
26573
+ () => true,
26574
+ () => false
26575
+ );
26576
+ logger.debug("machine config detection dir cleaned", { path: instanceDataDir, removed });
26577
+ }
26578
+ }
26579
+ async function ensureMachineConfigForCommand(options) {
26580
+ const home = resolveHome(options.env);
26581
+ const path = resolveMachineConfigPath(options.argv, options.env, home);
26582
+ try {
26583
+ const result = await ensureCloudMachineConfig({
26584
+ env: options.env,
26585
+ home,
26586
+ path,
26587
+ logger: options.logger,
26588
+ ...options.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
26589
+ });
26590
+ for (const warning of result.warnings) {
26591
+ options.logger.warn("machine config warning", { path: result.path, warning });
26592
+ }
26593
+ if (!existsSync8(result.path)) {
26594
+ options.logger.warn("machine config not written", { path: result.path, reason: "write_failed" });
26595
+ }
26596
+ return { result, failure: null };
26597
+ } catch (error) {
26598
+ options.logger.warn("machine config ensure failed", { path, reason: "bootstrap_failed", err: error });
26599
+ return { result: null, failure: { path, reason: "bootstrap_failed", error } };
26600
+ }
26601
+ }
26602
+ function machineConfigCheckEnv(argv, env) {
26603
+ if (argv[0] !== "config") return env;
26604
+ if (hasExplicitMachineConfig(argv, env)) return env;
26605
+ const machinePath = resolveMachineConfigPath(argv, env, resolveHome(env));
26606
+ if (!existsSync8(machinePath)) return env;
26607
+ return { ...env, [MACHINE_CONFIG_ENV]: machinePath };
26608
+ }
26609
+ function scanFlagValue(argv, flag) {
26610
+ let value;
26611
+ for (let index = 0; index < argv.length; index += 1) {
26612
+ const token = argv[index];
26613
+ if (token === flag) value = argv[index + 1];
26614
+ if (token?.startsWith(`${flag}=`)) value = token.slice(flag.length + 1);
26615
+ }
26616
+ return value;
26617
+ }
26618
+ function nonEmpty2(value) {
26619
+ return value !== void 0 && value !== "" ? value : void 0;
26620
+ }
26621
+
25608
26622
  // src/healthz.ts
25609
26623
  import { createServer } from "node:http";
25610
26624
  var HealthzError = class extends Error {
@@ -25728,10 +26742,22 @@ async function resolveCloudConnection(argv, env, io) {
25728
26742
  adapter: cloudAdapter(credentialsPath, journalPath, credentials.runnerId, io.logger)
25729
26743
  };
25730
26744
  }
25731
- async function platformRunnerStart(argv, env, io) {
26745
+ async function platformRunnerStart(argv, env, io, options) {
25732
26746
  const hasJournalFlag = argv.some((token) => token === "--journal" || token.startsWith("--journal="));
25733
26747
  const journalDefault = resolveJournalPath(env, {}, resolveInstance(env, { credentials: scanFlagValue(argv, "--credentials") }));
25734
- const envForParse = hasJournalFlag || env.COMPIVIA_RUNNER_JOURNAL !== void 0 ? env : { ...env, COMPIVIA_RUNNER_JOURNAL: journalDefault };
26748
+ let envForParse = hasJournalFlag || env.COMPIVIA_RUNNER_JOURNAL !== void 0 ? env : { ...env, COMPIVIA_RUNNER_JOURNAL: journalDefault };
26749
+ if (!hasExplicitMachineConfig(argv, env)) {
26750
+ const ensured = await ensureMachineConfigForCommand({
26751
+ argv,
26752
+ env,
26753
+ logger: io.logger,
26754
+ ...options?.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
26755
+ });
26756
+ const ensuredPath = ensured.result?.path;
26757
+ if (ensuredPath !== void 0 && existsSync9(ensuredPath)) {
26758
+ envForParse = { ...envForParse, COMPIVIA_RUNNER_MACHINE_CONFIG: ensuredPath };
26759
+ }
26760
+ }
25735
26761
  const { config, values } = parseRunnerStartArgs(argv, envForParse, {
25736
26762
  options: { credentials: { type: "string", envName: CREDENTIALS_ENV2 }, "api-port": { type: "string" } }
25737
26763
  });
@@ -25795,20 +26821,11 @@ async function prepareInstanceServices(argv, env, apiPort, io) {
25795
26821
  return null;
25796
26822
  }
25797
26823
  }
25798
- function scanFlagValue(argv, flag) {
25799
- let value;
25800
- for (let index = 0; index < argv.length; index += 1) {
25801
- const token = argv[index];
25802
- if (token === flag) value = argv[index + 1];
25803
- if (token?.startsWith(`${flag}=`)) value = token.slice(flag.length + 1);
25804
- }
25805
- return value;
25806
- }
25807
- function pairCommand() {
26824
+ function pairCommand(options) {
25808
26825
  return {
25809
26826
  name: "pair",
25810
26827
  run: async (argv, io) => {
25811
- const args = parsePairArgs(argv, process.env);
26828
+ const args = parsePairArgs(argv, options?.env ?? process.env);
25812
26829
  let enrolledOrigin;
25813
26830
  const fail = (message, err) => {
25814
26831
  io.logger.error(message, {
@@ -25825,7 +26842,15 @@ function pairCommand() {
25825
26842
  const code = normalizePairingCode(args.rawCode);
25826
26843
  const origin = resolveEnrollOrigin(args.rawUrl);
25827
26844
  enrolledOrigin = origin;
25828
- return await enrollAndSave({ ...args, code, origin }, io, fail);
26845
+ return await enrollAndSave(
26846
+ { ...args, code, origin },
26847
+ io,
26848
+ fail,
26849
+ {
26850
+ ...options?.env !== void 0 ? { env: options.env } : {},
26851
+ ...options?.detectorSetFactory !== void 0 ? { detectorSetFactory: options.detectorSetFactory } : {}
26852
+ }
26853
+ );
25829
26854
  } catch (error) {
25830
26855
  if (error instanceof RunnerCliUsageError) throw error;
25831
26856
  if (error instanceof PairingError || error instanceof TokenStoreError) {
@@ -25866,7 +26891,7 @@ function parsePairArgs(argv, pairEnv) {
25866
26891
  instanceId: paths.instanceId
25867
26892
  };
25868
26893
  }
25869
- async function enrollAndSave(task, io, fail) {
26894
+ async function enrollAndSave(task, io, fail, bootstrapOptions) {
25870
26895
  if (task.instanceDir !== null) {
25871
26896
  await ensurePrivateDir(task.instanceDir);
25872
26897
  if (task.dataDir === null || task.instanceId === null) {
@@ -25915,6 +26940,24 @@ async function enrollAndSave(task, io, fail) {
25915
26940
  ` : `${JSON.stringify({ ok: true, runnerId, credentials: task.file })}
25916
26941
  `
25917
26942
  );
26943
+ const outcome = await ensureMachineConfigForCommand({
26944
+ argv: [],
26945
+ env: bootstrapOptions?.env ?? process.env,
26946
+ logger: io.logger,
26947
+ ...bootstrapOptions?.detectorSetFactory !== void 0 ? { detectorSetFactory: bootstrapOptions.detectorSetFactory } : {}
26948
+ });
26949
+ if (outcome.result?.created) {
26950
+ io.logger.info("machine config created", { path: outcome.result.path });
26951
+ process.stderr.write(`compivia-runner-platform: machine config created at ${outcome.result.path}
26952
+ `);
26953
+ }
26954
+ for (const warning of outcome.result?.warnings ?? []) {
26955
+ process.stderr.write(`compivia-runner-platform: machine config warning: ${warning}
26956
+ `);
26957
+ }
26958
+ if (outcome.failure !== null) {
26959
+ process.stderr.write("compivia-runner-platform: machine config could not be ensured; see the log for details\n");
26960
+ }
25918
26961
  return 0;
25919
26962
  }
25920
26963
  function parseArgsStrict2(argv) {
@@ -26003,6 +27046,12 @@ function helpText(pkg) {
26003
27046
  ];
26004
27047
  const lines = [`compivia runner <command> [args]`, "", "Commands:"];
26005
27048
  for (const entry of commands) lines.push(` ${entry.name.padEnd(23)} ${entry.description}`);
27049
+ lines.push(
27050
+ "",
27051
+ "Machine configuration: <COMPIVIA_HOME|~/.compivia>/machine.json",
27052
+ " created automatically by pair/start; override the path with --machine-config",
27053
+ " or COMPIVIA_RUNNER_MACHINE_CONFIG; validate it with `config check`."
27054
+ );
26006
27055
  return `${lines.join("\n")}
26007
27056
  `;
26008
27057
  }
@@ -26014,7 +27063,7 @@ function createCliStderrLogger(env = process.env) {
26014
27063
  }
26015
27064
 
26016
27065
  // src/status.ts
26017
- import { existsSync as existsSync6 } from "node:fs";
27066
+ import { existsSync as existsSync10 } from "node:fs";
26018
27067
  import { parseArgs as parseArgs3 } from "node:util";
26019
27068
  function formatStatusReport(report) {
26020
27069
  return JSON.stringify(report);
@@ -26027,7 +27076,7 @@ function statusCommand() {
26027
27076
  const env = process.env;
26028
27077
  const paths = resolveCloudPaths(argv, env);
26029
27078
  const wrapperVersion = resolveWrapperVersion(env);
26030
- const paired = existsSync6(paths.credentialsPath);
27079
+ const paired = existsSync10(paths.credentialsPath);
26031
27080
  let runnerId = null;
26032
27081
  if (paired) {
26033
27082
  try {
@@ -26084,7 +27133,7 @@ function parseStatusArgs(argv) {
26084
27133
  }
26085
27134
 
26086
27135
  // src/unpair.ts
26087
- import { existsSync as existsSync7, unlink as unlink4 } from "node:fs";
27136
+ import { existsSync as existsSync11, unlink as unlink5 } from "node:fs";
26088
27137
  import { parseArgs as parseArgs4, promisify as promisify4 } from "node:util";
26089
27138
 
26090
27139
  // src/revoke.ts
@@ -26143,7 +27192,7 @@ async function drainAndClose(response) {
26143
27192
  }
26144
27193
 
26145
27194
  // src/unpair.ts
26146
- var unlinkAsync = promisify4(unlink4);
27195
+ var unlinkAsync = promisify4(unlink5);
26147
27196
  function unpairCommand(deps) {
26148
27197
  const revoke = deps?.revoke ?? revokeToken;
26149
27198
  const removeCredentials = deps?.removeCredentials ?? ((path) => unlinkAsync(path));
@@ -26152,7 +27201,7 @@ function unpairCommand(deps) {
26152
27201
  run: async (argv, io) => {
26153
27202
  const args = parseUnpairArgs(argv);
26154
27203
  const paths = resolveCloudPaths(argv, process.env);
26155
- if (!existsSync7(paths.credentialsPath)) {
27204
+ if (!existsSync11(paths.credentialsPath)) {
26156
27205
  io.logger.error("not paired \u2014 nothing to revoke", { file: paths.credentialsPath });
26157
27206
  return 1;
26158
27207
  }
@@ -26215,7 +27264,7 @@ function parseUnpairArgs(argv) {
26215
27264
  }
26216
27265
 
26217
27266
  // src/verify.ts
26218
- import { existsSync as existsSync8 } from "node:fs";
27267
+ import { existsSync as existsSync12 } from "node:fs";
26219
27268
  import { parseArgs as parseArgs5 } from "node:util";
26220
27269
  function formatVerifyReport(report) {
26221
27270
  return JSON.stringify(report);
@@ -26237,7 +27286,7 @@ function verifyCommand(deps) {
26237
27286
  wrapperVersion: wrapperVersion ?? null,
26238
27287
  instance: paths.instanceId
26239
27288
  };
26240
- if (!existsSync8(paths.credentialsPath)) {
27289
+ if (!existsSync12(paths.credentialsPath)) {
26241
27290
  return finish({ ...base, reason: "not_paired", runnerId: null }, args, io);
26242
27291
  }
26243
27292
  let credentials;
@@ -26409,11 +27458,17 @@ if (front.type === "metadata") {
26409
27458
  void runnerCli({
26410
27459
  argv,
26411
27460
  io,
27461
+ // #223 C2: config check reads the existing machine-level machine.json via
27462
+ // an injected env (read-only, D5); other invocations keep the env.
27463
+ env: machineConfigCheckEnv(argv, process.env),
26412
27464
  start: (startArgv) => {
26413
27465
  armSignals();
26414
27466
  return platformRunnerStart(startArgv, process.env, io);
26415
27467
  },
26416
- extraCommands: [pairCommand(), verifyCommand(), unpairCommand(), statusCommand()]
27468
+ // #223: the pair environment is threaded from the composition root the
27469
+ // same way the start path receives its env; the machine-config bootstrap
27470
+ // inside pair resolves its paths from it.
27471
+ extraCommands: [pairCommand({ env: process.env }), verifyCommand(), unpairCommand(), statusCommand()]
26417
27472
  }).then(
26418
27473
  (code) => {
26419
27474
  logger.info("runner exited", { exit_code: code });