@caveman-ai/cli 1.3.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { createHash, createHmac, createPublicKey, randomBytes, randomUUID, verif
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { parseEnv } from "node:util";
13
13
  import { PROFILES } from "./agents.generated.js";
14
+ import { autopilotStatusText, claimLearnNudge, confirmLearnNudge, maybeSpawnAutopilot, runAutopilot } from "./learn-autopilot.js";
14
15
  import { BINARY_RELEASE, BINARY_RELEASE_BASE_DEFAULT, BINARY_SIGNING_PUBKEY, } from "./binaries.generated.js";
15
16
  import { installProxyAwareFetch, resolveProxyUrl } from "./proxy-fetch.js";
16
17
  import { RECIPES } from "./recipes.generated.js";
@@ -22,7 +23,8 @@ import { NATIVE_CORE, NATIVE_PACK, NATIVE_SKILL_INSTRUCTIONS } from "./native-pa
22
23
  import { serveAgentMcp, } from "./agent-mcp.js";
23
24
  import { portableInvocation } from "./portable-command.js";
24
25
  import { hardenedGitArgs, hardenedGitEnv } from "./git-safe.js";
25
- import { publishedForwardHeadersOf, publishedUpstreamsOf, unforwardedProviderHeaders, verifiedProviderRoute } from "./provider-routing.js";
26
+ import { learnTrendLines, learnTrendTable } from "./learn-trends.js";
27
+ import { publishedForwardHeadersOf, publishedUpstreamsOf, trimTrailingSlashes, unforwardedProviderHeaders, verifiedProviderRoute } from "./provider-routing.js";
26
28
  import { openClawRequestCompatibilityIssue, preserveOpenClawProviderCompat } from "./openclaw-provider-compat.js";
27
29
  import { parseStatsOptions, renderStatsSummary, STATS_HELP, STATS_USAGE } from "./stats-cli.js";
28
30
  export const overlayBuilders = {};
@@ -124,7 +126,7 @@ const CLOUD_DISCOVERY = [
124
126
  { heading: "governance", verbs: [
125
127
  { verb: "audit", description: "import or report audit evidence" },
126
128
  { verb: "sync", description: "sync local metadata to connected org" },
127
- { verb: "agent", description: "inspect proposal-only optimization PRs" },
129
+ { verb: "agent", description: "inspect agents and optimization proposals" },
128
130
  ] },
129
131
  ];
130
132
  const TOOL_VERBS = new Set(TOOL_DISCOVERY.flatMap((group) => group.verbs.map((entry) => entry.verb)));
@@ -233,14 +235,22 @@ const CLOUD_HANDLERS = {
233
235
  },
234
236
  audit,
235
237
  sync: () => sync(),
236
- agent: (argv) => {
238
+ agent: async (argv) => {
239
+ if (argv[0] === "factory") {
240
+ if (argv[1] === "list" && argv.length === 2)
241
+ return get(`/api/v1/projects/${await projectId()}/agents`).then(print);
242
+ if (argv[1] === "show" && argv.length === 3 && /^[A-Za-z0-9_-]+$/.test(argv[2])) {
243
+ return get(`/api/v1/projects/${await projectId()}/agents/${argv[2]}`).then(print);
244
+ }
245
+ return commandUsage("agent factory list|show <id>");
246
+ }
237
247
  if (argv[0] === "list")
238
248
  return get("/api/v1/optimization-proposals").then(print);
239
249
  if (argv[0] === "show")
240
250
  return get(`/api/v1/optimization-proposals/${argv[1] ?? ""}`).then(print);
241
251
  if (argv[0] === "run")
242
252
  return post(`/api/v1/optimization-proposals/${argv[1] ?? ""}/run`, {}).then(print);
243
- return commandUsage("agent list|show <id>|run <id>");
253
+ return commandUsage("agent list|show <id>|run <id> | agent factory list|show <id>");
244
254
  },
245
255
  };
246
256
  const LEGACY_HANDLERS = {
@@ -403,18 +413,20 @@ function invokedCommand(legacyVerb, groupedTail = "") {
403
413
  }
404
414
  let currentInvocation;
405
415
  currentInvocation = resolveInvocation(process.argv.slice(2));
406
- // Version 4 = default-on (opt-out) plus token volume: command_run now carries
407
- // the local proxy's processed/saved token deltas, so a v3 "yes" was given for a
408
- // narrower scope and gets the new disclosure reprinted once (never re-asked, and
409
- // never flipped on). A persisted decision from any version — including a "no" to
410
- // the old v1 [y/N] prompt — is honored forever; the default only fills the
411
- // undecided gap, and the first default-on run prints the disclosure line.
412
- const TELEMETRY_PROMPT_VERSION = 4;
413
- const TELEMETRY_URL = "https://api.caveman.so/telemetry/cli";
414
- // The production control-API origin — derived from TELEMETRY_URL (the CLI's
415
- // other hardcoded prod-host literal) so the two can never drift apart.
416
- const PROD_API_URL = new URL(TELEMETRY_URL).origin;
417
- const TELEMETRY_DISCLOSURE_LINE = "anonymous usage stats on — command counts and token totals only, never prompts, code, or file paths · caveman telemetry off";
416
+ // Version 5 = the receiver stores the client IP address with each event. v4 was
417
+ // default-on (opt-out) plus token volume (command_run carries the local proxy's
418
+ // processed/saved token deltas). A stale-version "yes" was given for a narrower
419
+ // scope and gets the new disclosure reprinted once (never re-asked, and never
420
+ // flipped on). A persisted decision from any version — including a "no" to the
421
+ // old v1 [y/N] prompt — is honored forever; the default only fills the undecided
422
+ // gap, and the first default-on run prints the disclosure line.
423
+ const TELEMETRY_PROMPT_VERSION = 5;
424
+ // Supabase Edge Function; source and schema live in supabase/ at the repo root.
425
+ const TELEMETRY_URL = "https://xvfgtprkhzlvegvmeefq.supabase.co/functions/v1/cli-telemetry";
426
+ const PROD_API_URL = "https://api.caveman.so";
427
+ // Where `telemetry off` points someone who wants already-sent events deleted.
428
+ const TELEMETRY_DELETION_URL = "https://github.com/JuliusBrussee/caveman/blob/main/SECURITY.md#delete-sent-telemetry";
429
+ const TELEMETRY_DISCLOSURE_LINE = "usage stats on — commands, agent sessions, token totals, account and install type, timezone and language, and your IP address; never prompts, code, or file paths · caveman telemetry off";
418
430
  // Reading token totals means spawning caveman-proxy to query the local SQLite
419
431
  // store. It runs after the command's own work, so the cost lands on process exit;
420
432
  // a slow or wedged binary drops the token fields rather than holding the CLI.
@@ -479,10 +491,25 @@ function telemetryState() {
479
491
  }
480
492
  // telemetrySendable is the single choke point every emitter must pass: on, and
481
493
  // never the un-persisted default (no silent sends, no ephemeral-id retention
482
- // noise from commands that skipped the disclosure).
494
+ // noise from commands that skipped the disclosure). A config-sourced yes given
495
+ // under older wording also waits until the current disclosure has printed —
496
+ // help-like and `telemetry …` invocations skip that reprint, so without this
497
+ // they would send the widened scope unseen.
483
498
  function telemetrySendable(state) {
499
+ if (state.source === "config" && (state.config?.promptVersion ?? 0) < TELEMETRY_PROMPT_VERSION)
500
+ return false;
484
501
  return state.state === "on" && state.source !== "default";
485
502
  }
503
+ // Native agent sessions never have a TTY. A decision persisted by an
504
+ // interactive run (which printed the disclosure) still covers them; CI and the
505
+ // env kills still win, and no default is ever minted here.
506
+ function sessionTelemetryState() {
507
+ const state = telemetryState();
508
+ if (state.source !== "runtime" || envTruthy(process.env.CI))
509
+ return state;
510
+ const cfg = state.config;
511
+ return cfg?.decidedAt ? { state: cfg.enabled ? "on" : "off", source: "config", config: cfg } : state;
512
+ }
486
513
  function envTruthy(v) {
487
514
  return v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
488
515
  }
@@ -524,6 +551,7 @@ function parseTelemetryConfig(value) {
524
551
  // any persisted decision — including a "no" to the old v1 prompt — win.
525
552
  async function ensureTelemetryDefault() {
526
553
  const state = telemetryState();
554
+ await persistTelemetryEnvKill(state);
527
555
  if (isHelpLikeInvocation())
528
556
  return;
529
557
  // `caveman telemetry …` manages the decision explicitly — don't pre-mint an
@@ -551,6 +579,28 @@ async function ensureTelemetryDefault() {
551
579
  }
552
580
  process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
553
581
  }
582
+ // persistTelemetryEnvKill turns DO_NOT_TRACK / CAVEMAN_TELEMETRY=0, seen by an
583
+ // interactive run, into a persisted opt-out. Native agent hooks run under hosts
584
+ // that often never read the shell rc (GUI apps, launchd/systemd services), so an
585
+ // env-only kill would not reach them while config still says yes.
586
+ async function persistTelemetryEnvKill(state) {
587
+ if (state.source !== "env" || state.state !== "off" || !state.config?.enabled || !interactive())
588
+ return;
589
+ try {
590
+ await saveTelemetryConfig({ enabled: false, decidedAt: new Date().toISOString(), promptVersion: TELEMETRY_PROMPT_VERSION });
591
+ mutateRawConfig((out) => {
592
+ delete out.telemetryTokens;
593
+ });
594
+ }
595
+ catch {
596
+ /* best effort: the env var still wins for this process */
597
+ return;
598
+ }
599
+ // The id is gone from disk now, and it is the only key to a deletion request.
600
+ if (state.config.anonymousId) {
601
+ process.stderr.write(`${dim(`telemetry off · old install id ${state.config.anonymousId} · delete what it sent: ${TELEMETRY_DELETION_URL}`)}\n`);
602
+ }
603
+ }
554
604
  // ensureTelemetryDisclosureVersion reprints the disclosure once for someone who
555
605
  // consented under older wording. v4 widened command_run with token volume, and a
556
606
  // v3 "yes" was given for command counts alone — it stays a yes (re-asking would
@@ -621,12 +671,19 @@ async function telemetryCmd(argv) {
621
671
  return telemetryOn();
622
672
  if (sub === "off")
623
673
  return telemetryOff();
674
+ // Unprinted: the detached children startSessionTelemetry and emitTelemetryEvents spawn.
675
+ if (sub === "session")
676
+ return telemetrySession(argv.slice(1));
677
+ if (sub === "send")
678
+ return telemetrySend();
624
679
  emitCommandRunOnce("error", "usage");
625
680
  console.error(`usage: ${invokedCommand("telemetry")} [status|on|off]`);
626
681
  process.exit(2);
627
682
  }
628
683
  function telemetryStatus() {
629
- const state = telemetryState();
684
+ // Session state, not command state: an agent or pipe running this has no TTY,
685
+ // yet native hooks still send under a persisted yes.
686
+ const state = sessionTelemetryState();
630
687
  print({
631
688
  enabled: state.state === "on",
632
689
  state: state.state,
@@ -644,6 +701,8 @@ async function telemetryOn() {
644
701
  promptVersion: TELEMETRY_PROMPT_VERSION,
645
702
  };
646
703
  await saveTelemetryConfig(telemetry);
704
+ // The stored version claims this wording was shown, so show it.
705
+ process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
647
706
  if (!(prior?.enabled && prior.anonymousId) && !telemetryEnvForcesOff())
648
707
  emitConsentGranted(anonymousId);
649
708
  if (telemetryEnvForcesOff()) {
@@ -653,6 +712,7 @@ async function telemetryOn() {
653
712
  print({ telemetry: "on", anonymous_id: anonymousId });
654
713
  }
655
714
  async function telemetryOff() {
715
+ const prior = telemetryConfigFromDisk();
656
716
  const telemetry = {
657
717
  enabled: false,
658
718
  decidedAt: new Date().toISOString(),
@@ -670,8 +730,96 @@ async function telemetryOff() {
670
730
  catch {
671
731
  /* best effort: the decision itself is already persisted */
672
732
  }
733
+ // The id leaves the config here, and it is the only key to events already
734
+ // sent, so show it once with where to ask for their deletion.
735
+ if (prior?.anonymousId) {
736
+ print({ telemetry: "off", anonymous_id: "none", discarded_anonymous_id: prior.anonymousId, delete_sent_data: TELEMETRY_DELETION_URL });
737
+ return;
738
+ }
673
739
  print({ telemetry: "off", anonymous_id: "none" });
674
740
  }
741
+ // Native sessions are where installed users show up: after setup most people
742
+ // launch the agent directly and never run the CLI. The host waits on the
743
+ // SessionStart hook, so the send runs in a detached child and never delays the
744
+ // agent's start.
745
+ function startSessionTelemetry(agent, sessionId, source) {
746
+ if (!telemetrySendable(sessionTelemetryState()))
747
+ return;
748
+ // One event per host session: resumes, repeated SessionStart calls (the
749
+ // OpenCode V1 plugin re-asks on every model step when it gets no context) and
750
+ // hooks registered in two scopes would otherwise each count. Checked here so
751
+ // a repeat costs one failed file create, not a process spawn.
752
+ if (sessionId) {
753
+ const dir = join(cavemanHome(), "runtime", "telemetry-sessions");
754
+ try {
755
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
756
+ closeSync(openSync(join(dir, createHash("sha256").update(`${agent}\0${sessionId}`).digest("hex")), "wx", 0o600));
757
+ }
758
+ catch (error) {
759
+ if (error.code === "EEXIST")
760
+ return;
761
+ /* unwritable home: count it rather than lose it */
762
+ }
763
+ }
764
+ const sessionSource = source === "startup" || source === "resume" || source === "clear" ? source : "unknown";
765
+ try {
766
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "telemetry", "session", agent, sessionSource], {
767
+ detached: true,
768
+ stdio: "ignore",
769
+ windowsHide: true,
770
+ });
771
+ child.on("error", () => { });
772
+ child.unref();
773
+ }
774
+ catch {
775
+ /* telemetry never blocks a session */
776
+ }
777
+ }
778
+ async function telemetrySession(argv) {
779
+ // session_start stands in for this invocation's command_run.
780
+ telemetryCommandSent = true;
781
+ pruneSessionMarkers();
782
+ const agent = findAgent(argv[0] ?? "")?.id;
783
+ const state = sessionTelemetryState();
784
+ // No persisted id means every session would mint a fresh "user".
785
+ if (!agent || !telemetrySendable(state) || !state.config?.anonymousId)
786
+ return;
787
+ const event = {
788
+ schema: "cli/v1",
789
+ anonymous_id: state.config.anonymousId,
790
+ event: "session_start",
791
+ agent,
792
+ session_source: argv[1] === "startup" || argv[1] === "resume" || argv[1] === "clear" ? argv[1] : "unknown",
793
+ cli_version: cliVersion(),
794
+ os: process.platform,
795
+ arch: process.arch,
796
+ node_major: Number(process.versions.node.split(".")[0] ?? 0),
797
+ ts: new Date().toISOString(),
798
+ };
799
+ const tokens = telemetryTokenDelta();
800
+ if (tokens) {
801
+ event.tokens_processed = tokens.processed;
802
+ event.tokens_saved = tokens.saved;
803
+ event.tokens_basis = tokens.basis;
804
+ }
805
+ await postTelemetry(telemetryBody([event]), 10_000);
806
+ }
807
+ // Markers only need to outlive one session's repeated SessionStart calls; a
808
+ // resume the next day counts as a new session. Bounded per run.
809
+ function pruneSessionMarkers() {
810
+ const dir = join(cavemanHome(), "runtime", "telemetry-sessions");
811
+ try {
812
+ const cutoff = Date.now() - 24 * 60 * 60 * 1000;
813
+ for (const name of readdirSync(dir).slice(0, 500)) {
814
+ const path = join(dir, name);
815
+ if (statSync(path).mtimeMs < cutoff)
816
+ unlinkSync(path);
817
+ }
818
+ }
819
+ catch {
820
+ /* nothing to prune */
821
+ }
822
+ }
675
823
  function telemetryCommandName() {
676
824
  if (currentInvocation.verb === "mcp-serve")
677
825
  return "mcp";
@@ -781,6 +929,8 @@ function readProxyTokenTotals() {
781
929
  encoding: "utf8",
782
930
  timeout: TELEMETRY_TOKEN_READ_TIMEOUT_MS,
783
931
  stdio: ["ignore", "pipe", "ignore"],
932
+ // The detached session sender has no console; without this Windows opens one.
933
+ windowsHide: true,
784
934
  });
785
935
  const parsed = parseProxyStatsPayload(out);
786
936
  if (!parsed)
@@ -908,8 +1058,8 @@ function commandRunEventOnce(exitClass, errorClass) {
908
1058
  event.agent = agent;
909
1059
  if (exitClass === "error")
910
1060
  event.error_class = errorClass ?? "other";
911
- // Token volume rides on command_run only — runtime_bootstrap shares the same
912
- // watermark and would race it into a double count.
1061
+ // Token volume rides on command_run and session_start only; the watermark
1062
+ // claim in telemetryTokenDelta keeps concurrent readers from double counting.
913
1063
  const tokens = telemetryTokenDelta();
914
1064
  if (tokens) {
915
1065
  event.tokens_processed = tokens.processed;
@@ -955,15 +1105,90 @@ function emitRuntimeBootstrap(exitClass, durationMS, errorClass) {
955
1105
  event.error_class = errorClass ?? "other";
956
1106
  emitTelemetryEvents([event]);
957
1107
  }
1108
+ // Fields every event carries. Cheap local reads only: no keychain lookup, no
1109
+ // network, and the install path never leaves the machine — only its channel.
1110
+ function telemetryContext() {
1111
+ let raw = {};
1112
+ try {
1113
+ raw = JSON.parse(readFileSync(configPath(), "utf8"));
1114
+ }
1115
+ catch {
1116
+ /* no config yet */
1117
+ }
1118
+ const connected = Boolean(process.env.CAVE_TOKEN || raw.tokenStore || raw.token);
1119
+ const out = {
1120
+ account: connected ? "connected" : "none",
1121
+ install_channel: telemetryInstallChannel(),
1122
+ };
1123
+ // Logout leaves the cached entitlement behind, so only a live account's
1124
+ // unexpired plan counts.
1125
+ const entitlement = connected ? parseWrapEntitlement(raw.wrapEntitlement) : null;
1126
+ if (entitlement?.plan && !(Date.parse(entitlement.expires_at) < Date.now()))
1127
+ out.plan = entitlement.plan;
1128
+ try {
1129
+ const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions();
1130
+ if (timeZone)
1131
+ out.timezone = timeZone;
1132
+ if (locale)
1133
+ out.locale = locale;
1134
+ }
1135
+ catch {
1136
+ /* runtime without Intl data */
1137
+ }
1138
+ return out;
1139
+ }
1140
+ function telemetryInstallChannel() {
1141
+ const path = fileURLToPath(import.meta.url).replace(/\\/g, "/");
1142
+ if (path.includes("/_npx/"))
1143
+ return "npx";
1144
+ if (path.includes("/.pnpm/"))
1145
+ return "pnpm";
1146
+ if (path.includes("/.bun/") || path.includes("/bunx-"))
1147
+ return "bun";
1148
+ if (path.includes("/node_modules/"))
1149
+ return "npm";
1150
+ return "source";
1151
+ }
1152
+ function telemetryBody(events) {
1153
+ const context = telemetryContext();
1154
+ return JSON.stringify(events.map((event) => ({ ...event, ...context })));
1155
+ }
1156
+ // Sends run in a detached child so no command waits on the network at exit.
1157
+ // The child has no user-facing deadline, so it can outwait a cold endpoint.
958
1158
  function emitTelemetryEvents(events) {
1159
+ const body = telemetryBody(events);
1160
+ try {
1161
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "telemetry", "send"], {
1162
+ detached: true,
1163
+ stdio: "ignore",
1164
+ windowsHide: true,
1165
+ env: { ...process.env, CAVEMAN_TELEMETRY_PAYLOAD: body },
1166
+ });
1167
+ child.on("error", () => { });
1168
+ child.unref();
1169
+ return Promise.resolve();
1170
+ }
1171
+ catch {
1172
+ return postTelemetry(body, 1500);
1173
+ }
1174
+ }
1175
+ function postTelemetry(body, timeoutMs) {
959
1176
  const url = process.env.CAVEMAN_TELEMETRY_URL || TELEMETRY_URL;
960
1177
  return fetch(url, {
961
1178
  method: "POST",
962
1179
  headers: { "content-type": "application/json" },
963
- body: JSON.stringify(events),
964
- signal: AbortSignal.timeout(1500),
1180
+ body,
1181
+ signal: AbortSignal.timeout(timeoutMs),
965
1182
  }).then(() => { }).catch(() => { });
966
1183
  }
1184
+ // `caveman telemetry send` (unprinted): the detached child emitTelemetryEvents
1185
+ // spawns. Consent was checked by the emitter; this only delivers.
1186
+ async function telemetrySend() {
1187
+ telemetryCommandSent = true;
1188
+ const body = process.env.CAVEMAN_TELEMETRY_PAYLOAD;
1189
+ if (body)
1190
+ await postTelemetry(body, 10_000);
1191
+ }
967
1192
  function classifyTelemetryError(error) {
968
1193
  const message = error instanceof Error ? error.message : "";
969
1194
  if (telemetryCommandName() === "unknown" || message.startsWith("unknown command:"))
@@ -2173,7 +2398,22 @@ function verifiedLocalInstall(binDir) {
2173
2398
  }
2174
2399
  return installed;
2175
2400
  }
2176
- function parseSignedChecksums(raw) {
2401
+ // A signed manifest names its release through a `RELEASE` entry: the sha256 of
2402
+ // the release asset `RELEASE`, whose content is "<tag>\n". Without it, anyone
2403
+ // able to edit a release page could serve an older, validly signed manifest
2404
+ // and its binaries. It rides as an ordinary checksum line so the shipped
2405
+ // wedge installers' strict parsers keep accepting the manifest. Releases
2406
+ // before bin-v2.0.0 were signed without it, so it is required from there on.
2407
+ const FIRST_RELEASE_WITH_SIGNED_NAME = [2, 0, 0];
2408
+ function releaseRequiresSignedName(release) {
2409
+ const match = release.match(/^bin-v(\d+)\.(\d+)\.(\d+)/);
2410
+ if (!match)
2411
+ return true;
2412
+ const version = match.slice(1, 4).map(Number);
2413
+ const i = version.findIndex((part, index) => part !== FIRST_RELEASE_WITH_SIGNED_NAME[index]);
2414
+ return i === -1 || version[i] > FIRST_RELEASE_WITH_SIGNED_NAME[i];
2415
+ }
2416
+ export function parseSignedChecksums(raw, release = BINARY_RELEASE) {
2177
2417
  const checksums = new Map();
2178
2418
  for (const line of raw.split("\n")) {
2179
2419
  if (!line)
@@ -2186,6 +2426,10 @@ function parseSignedChecksums(raw) {
2186
2426
  throw new Error(`duplicate checksum manifest entry: ${filename}`);
2187
2427
  checksums.set(filename, match[1]);
2188
2428
  }
2429
+ const signedName = checksums.get("RELEASE");
2430
+ if (signedName === undefined ? releaseRequiresSignedName(release) : signedName !== createHash("sha256").update(`${release}\n`).digest("hex")) {
2431
+ throw new Error(`manifest is not signed for release ${release}`);
2432
+ }
2189
2433
  return checksums;
2190
2434
  }
2191
2435
  function verifyChecksumSignature(checksums, signature) {
@@ -2326,7 +2570,7 @@ async function setupInstall(json, options = {}) {
2326
2570
  printInstallResult(local, platform, binDir, json, options.continuing);
2327
2571
  return;
2328
2572
  }
2329
- const base = (process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT).replace(/\/+$/, "");
2573
+ const base = trimTrailingSlashes(process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT);
2330
2574
  const releaseBase = `${base}/${BINARY_RELEASE}`;
2331
2575
  let checksumsRaw;
2332
2576
  let signatureRaw;
@@ -2347,8 +2591,8 @@ async function setupInstall(json, options = {}) {
2347
2591
  try {
2348
2592
  checksums = parseSignedChecksums(checksumsRaw);
2349
2593
  }
2350
- catch {
2351
- throw new Error("signature check failed for checksums.txt — refusing to install; partial download deleted");
2594
+ catch (error) {
2595
+ throw new Error(`signature check failed for checksums.txt (${error.message}) — refusing to install; partial download deleted`);
2352
2596
  }
2353
2597
  const installed = [];
2354
2598
  const artifactDigests = {};
@@ -2407,7 +2651,7 @@ function cliVersionBehind(current, latest) {
2407
2651
  return false;
2408
2652
  }
2409
2653
  async function latestPublishedCliVersion(timeoutSeconds) {
2410
- const registry = (process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org").replace(/\/+$/, "");
2654
+ const registry = trimTrailingSlashes(process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org");
2411
2655
  try {
2412
2656
  const response = await fetch(`${registry}/@caveman-ai%2fcli`, {
2413
2657
  headers: { accept: "application/vnd.npm.install-v1+json" },
@@ -3650,14 +3894,28 @@ function mutateRawConfig(fn) {
3650
3894
  }
3651
3895
  fn(out);
3652
3896
  mkdirSync(dirname(configPath()), { recursive: true });
3653
- writeFileSync(configPath(), JSON.stringify(out, null, 2), { mode: 0o600 });
3897
+ const target = configWriteTarget();
3898
+ const tmp = `${target}.${process.pid}.tmp`;
3899
+ writeFileSync(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
3900
+ renameSync(tmp, target);
3654
3901
  try {
3655
- chmodSync(configPath(), 0o600);
3902
+ chmodSync(target, 0o600);
3656
3903
  }
3657
3904
  catch {
3658
3905
  /* best effort */
3659
3906
  }
3660
3907
  }
3908
+ // Config writes go temp-file + rename so a concurrent reader (background
3909
+ // session senders) never sees a truncated file and rewrites it as {}. Resolves
3910
+ // a symlinked config.json so the rename replaces its target, not the link.
3911
+ function configWriteTarget() {
3912
+ try {
3913
+ return realpathSync(configPath());
3914
+ }
3915
+ catch {
3916
+ return configPath();
3917
+ }
3918
+ }
3661
3919
  // ensureDeviceId returns a stable, opaque per-machine id, generated once and
3662
3920
  // persisted in config.json. The entitlement device_hash is sha256(deviceId) — a
3663
3921
  // random per-install id, NEVER derived from a hardware serial.
@@ -4843,7 +5101,7 @@ async function agentShortcut(rest) {
4843
5101
  // is the one-command compression path. If the proxy can't be reached, a TTY run
4844
5102
  // offers to launch the agent directly (no Caveman, no compression this run) rather
4845
5103
  // than wire it to a dead endpoint; non-TTY runs warn and route through as before.
4846
- async function runWrapped(bin, cmdArgs, agent, opts = { mode: "compress", noProxy: false, toon: true, noShrink: false, mcpMode: "auto", noBrowse: false, delegate: false, minimal: false, command: [] }, codexSubscription = false, routeDecision) {
5104
+ async function runWrapped(bin, cmdArgs, agent, opts = { mode: "compress", noProxy: false, toon: true, noShrink: false, mcpMode: "auto", noBrowse: false, delegate: false, minimal: false, command: [] }, codexSubscription, routeDecision) {
4847
5105
  const result = await spawnWrapped(bin, cmdArgs, agent, opts, gatewayURL(), codexSubscription, routeDecision);
4848
5106
  // Preflight route bypass is intentionally outside Caveman's lifecycle: no
4849
5107
  // savings read, sync, telemetry, or other post-child mutation.
@@ -4909,7 +5167,21 @@ function routedAiderArgs(args) {
4909
5167
  process.stderr.write(`caveman: aider model not set; routing with --model ${AIDER_ROUTED_DEFAULT_MODEL}\n`);
4910
5168
  return ["--model", AIDER_ROUTED_DEFAULT_MODEL, ...args];
4911
5169
  }
4912
- async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = false, routeDecision) {
5170
+ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOverride, routeDecision) {
5171
+ // Which Codex route is correct is a fact about ~/.codex/auth.json, not about
5172
+ // the caller: a ChatGPT login must reach the `/chatgpt` mux handler, an api-key
5173
+ // login the attributed `/w/codex/v1`. This used to be a defaulted parameter, so
5174
+ // every caller had to remember to pass it. `wrap codex` did (it resolves the
5175
+ // mode for --pixel anyway); `trial` and the interactive picker did not, and
5176
+ // their `false` built an ephemeral CODEX_HOME pinning the api-key route. Codex
5177
+ // then sent the OAuth token to the platform Responses API, which rejects it
5178
+ // with "Missing scopes: api.responses.write", while the model refresh 404s
5179
+ // because `/w/codex/v1/models` is not in the openai adapter's closed
5180
+ // allowlist (#1092). Resolving it here fixes every caller that forgets; an
5181
+ // explicit override still wins, which is what `wrap` passes.
5182
+ const codexSubscription = agent?.id === "codex"
5183
+ ? codexSubscriptionOverride ?? detectCodexWrapAuthMode() === "subscription"
5184
+ : false;
4913
5185
  const { host, port } = gatewayHostPort(gw);
4914
5186
  const local = wrapMode(gw) === "local";
4915
5187
  let proxyStarted = false;
@@ -5179,7 +5451,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
5179
5451
  if (direct) {
5180
5452
  // buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
5181
5453
  // outer routed wrap may leak the bare form; a direct launch strips both.
5182
- const gwPrefix = `${gw.replace(/\/+$/, "")}/`;
5454
+ const gwPrefix = `${trimTrailingSlashes(gw)}/`;
5183
5455
  for (const k of WRAP_BASE_URL_ENV_VARS) {
5184
5456
  const value = env[k];
5185
5457
  if (value !== undefined && (value === gw || value.startsWith(gwPrefix)))
@@ -5367,7 +5639,13 @@ function applyHermesAuthEnv(env, gw, modeGw = gw) {
5367
5639
  if (key && name)
5368
5640
  env[name] = key;
5369
5641
  }
5370
- async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw = gatewayURL(), purpose = "standard", observeEstimate = false) {
5642
+ // spawnLocalProxyProcess resolves the proxy binary, builds its env, and spawns
5643
+ // it detached + unref'd — the part every caller needs identically. Split out
5644
+ // of startWrapProxy so a caller that only wants to kick the proxy off (never
5645
+ // waiting to confirm it came up) doesn't have to either duplicate this env
5646
+ // assembly or pay for the readiness-poll loop below, which holds this
5647
+ // process's event loop open via a non-unref'd sleep() timer.
5648
+ function spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw, purpose, observeEstimate) {
5371
5649
  const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
5372
5650
  const resolved = which(bin);
5373
5651
  if (!resolved) {
@@ -5377,7 +5655,7 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
5377
5655
  else {
5378
5656
  process.stderr.write(`${mark("warn")} ${bin} not found; wrap will still launch, but no local compression/metering will run — run ${cyan("caveman setup")} to see what's missing\n`);
5379
5657
  }
5380
- return false;
5658
+ return null;
5381
5659
  }
5382
5660
  const { host, port } = gatewayHostPort(gw);
5383
5661
  const env = {
@@ -5425,14 +5703,59 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
5425
5703
  process.stderr.write(`${mark("warn")} could not start ${bin}: ${error.message}\n`);
5426
5704
  });
5427
5705
  child.unref();
5706
+ return { host, port };
5707
+ }
5708
+ // Best-effort "there should be a proxy on this port now" for the `enable` door.
5709
+ // Fire-and-forget: the caller never waits, so `enable` returns at its own pace.
5710
+ //
5711
+ // Deliberately not startWrapProxy: that readiness poll's sleep() timer is not
5712
+ // unref'd, so awaiting it would hold this command's process open for up to two
5713
+ // seconds on every enable where nothing is listening yet — the common case this
5714
+ // exists to cover. Probe first (one fast TCP connect, not the retry loop) so a
5715
+ // second enable against a live proxy spawns nothing; the redundant process that
5716
+ // skipping the probe would create is harmless, since run state is only written
5717
+ // once the listener binds, but free beats harmless.
5718
+ //
5719
+ // aider is excluded on purpose. It is the one native agent installed without an
5720
+ // MCP binary (see nativeMcpBinaryRequired's aider branch), so the recovery flag
5721
+ // derived below would stamp CAVEMAN_RECOVERY=mcp onto a proxy with no retrieve
5722
+ // tool to back it — the exact leak the explicit stamping elsewhere exists to
5723
+ // prevent. Giving aider a proxy needs recovery pinned off and its own coverage;
5724
+ // until then it keeps the pre-existing behaviour, no better and no worse.
5725
+ function ensureLocalProxyForNative(agent, gw) {
5726
+ if (agent === "aider" || wrapMode(gw) !== "local")
5727
+ return;
5728
+ void (async () => {
5729
+ try {
5730
+ const opts = defaultWrapOptions();
5731
+ // Every other spawn site gates on this (agentShortcut, the native hook).
5732
+ // Without it, `enable` starts a proxy the user's config switched off.
5733
+ if (opts.noProxy)
5734
+ return;
5735
+ const { host, port } = gatewayHostPort(gw);
5736
+ if (await portListening(host, port))
5737
+ return;
5738
+ const subscription = agent === "codex" && detectCodexWrapAuthMode() === "subscription";
5739
+ const mode = subscription && opts.mode === "pixel" ? "record" : opts.mode;
5740
+ const recovery = Boolean(probeMcpBinary()?.probe.current);
5741
+ spawnLocalProxyProcess(mode, recovery, subscription ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, subscription ? "codex-subscription" : "standard", false);
5742
+ }
5743
+ catch { /* fail-open, same as the SessionStart hook and the shortcut door */ }
5744
+ })();
5745
+ }
5746
+ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw = gatewayURL(), purpose = "standard", observeEstimate = false) {
5747
+ const spawned = spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw, purpose, observeEstimate);
5748
+ if (!spawned)
5749
+ return false;
5750
+ const { host, port } = spawned;
5428
5751
  for (let i = 0; i < 20; i++) {
5429
5752
  await sleep(100);
5430
5753
  if (await portListening(host, port)) {
5431
- process.stderr.write(dim(`→ started Caveman proxy on ${host}:${port} (${env.CAVEMAN_MODE})\n`));
5754
+ process.stderr.write(dim(`→ started Caveman proxy on ${host}:${port} (${mode})\n`));
5432
5755
  return true;
5433
5756
  }
5434
5757
  }
5435
- process.stderr.write(`${mark("warn")} started ${bin}, but proxy did not become ready on ${host}:${port}\n`);
5758
+ process.stderr.write(`${mark("warn")} started ${cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN")}, but proxy did not become ready on ${host}:${port}\n`);
5436
5759
  return false;
5437
5760
  }
5438
5761
  // startProxyKeepalive heartbeats the local proxy while the wrapped agent process
@@ -5833,7 +6156,7 @@ function freshOpenClawModelRef(ctx) {
5833
6156
  return { provider: "openai", model: OPENCLAW_FRESH_MODEL, raw: `openai/${OPENCLAW_FRESH_MODEL}` };
5834
6157
  }
5835
6158
  function appendUrlPath(base, path) {
5836
- return `${base.replace(/\/+$/, "")}${path}`;
6159
+ return `${trimTrailingSlashes(base)}${path}`;
5837
6160
  }
5838
6161
  export function claudeConfigDir(env = process.env) {
5839
6162
  return env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(homedir(), ".claude");
@@ -5952,7 +6275,7 @@ function stripCodexCavemanProviderToml(text) {
5952
6275
  // The api-key Codex route, in ONE place: the provider TOML writes it, the
5953
6276
  // install journal records it, and the doctor compares against it, and a route
5954
6277
  // only three of those four agree on reads as permanently degraded.
5955
- const CODEX_API_KEY_ROUTE = "/w/codex/v1";
6278
+ const CODEX_PAYG_ROUTE = "/w/codex/v1";
5956
6279
  function codexGatewayBase(gw, subscription) {
5957
6280
  // Codex's OpenAI-Responses client appends "/responses" onto base_url itself,
5958
6281
  // exactly as it does against the real api.openai.com, so what the proxy
@@ -5963,7 +6286,7 @@ function codexGatewayBase(gw, subscription) {
5963
6286
  // convention aider already uses (`/w/aider/openai/v1`). The subscription
5964
6287
  // route is a different mux handler (`/chatgpt/`) that takes the suffix
5965
6288
  // verbatim, so it must NOT gain a "/v1".
5966
- return appendUrlPath(gw, subscription ? "/chatgpt" : CODEX_API_KEY_ROUTE);
6289
+ return appendUrlPath(gw, subscription ? "/chatgpt" : CODEX_PAYG_ROUTE);
5967
6290
  }
5968
6291
  // Codex clears the stdio MCP environment, including these non-secret store
5969
6292
  // selectors. Forward their names so the proxy and recovery server share the
@@ -6768,7 +7091,30 @@ function geminiNativeMutations(gw, mcpBinary) {
6768
7091
  function opencodeNativePluginPath() {
6769
7092
  return join(homedir(), ".config", "opencode", "plugins", "caveman-native.js");
6770
7093
  }
7094
+ function opencodePluginMajor() {
7095
+ const profile = AGENTS.find((agent) => agent.id === "opencode");
7096
+ const semver = parsedSemver(profile ? detectedAgentVersion(profile) : null);
7097
+ return semver ? semver[0] : null;
7098
+ }
6771
7099
  function opencodeNativePluginSource() {
7100
+ // OpenCode 2 replaced the plugin API: a V1 hook map no longer loads
7101
+ // (PluginModule.LoadError, missing "default"). Emit the implementation
7102
+ // matching the detected host major. See #1083.
7103
+ //
7104
+ // An unreadable version keeps V1, the status quo. nativeHostProbe returns
7105
+ // version: null for an empty/non-zero/unspawnable `opencode --version`
7106
+ // ("version_probe_failed"), and #1081 records exactly that state on a live
7107
+ // OpenCode 1.18.31 host — so "unknown" is not evidence of "new". Defaulting
7108
+ // it to V2 would break a 1.x user whose probe merely flaked, turning a
7109
+ // working install into one whose plugin the host refuses to load; a 2.x user
7110
+ // in the same state is no worse off than before this gate existed. Only a
7111
+ // version that positively reads as major >= 2 opts into the V2 API.
7112
+ const major = opencodePluginMajor();
7113
+ if (major === null || major < 2)
7114
+ return opencodeNativePluginSourceV1();
7115
+ return opencodeNativePluginSourceV2();
7116
+ }
7117
+ function opencodeNativePluginSourceV1() {
6772
7118
  const { cmd, pre } = cavemanInvocation();
6773
7119
  return `// caveman:native-opencode — GENERATED by \`caveman enable opencode\`.
6774
7120
  // Contract: @opencode-ai/plugin 1.17.8 Hooks (installed local type source).
@@ -6939,6 +7285,211 @@ export const CavemanNative = async () => ({
6939
7285
  });
6940
7286
  `;
6941
7287
  }
7288
+ function opencodeNativePluginSourceV2() {
7289
+ const { cmd, pre } = cavemanInvocation();
7290
+ return `// caveman:native-opencode — GENERATED by \`caveman enable opencode\`.
7291
+ // Contract: OpenCode 2 plugin API — default export { id, setup }
7292
+ // (https://opencode.ai/v2/docs/build/plugins/migrate-v1).
7293
+ import { execFileSync } from "node:child_process";
7294
+ import { createHash } from "node:crypto";
7295
+
7296
+ const command = ${JSON.stringify(cmd)};
7297
+ const prefix = ${JSON.stringify(pre)};
7298
+
7299
+ function call(event, payload = {}) {
7300
+ try {
7301
+ const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
7302
+ input: JSON.stringify({ event_name: event, ...payload }),
7303
+ encoding: "utf8",
7304
+ timeout: 2000,
7305
+ maxBuffer: 2 * 1024 * 1024,
7306
+ });
7307
+ if (!raw.trim()) return undefined;
7308
+ const value = JSON.parse(raw);
7309
+ return value && typeof value === "object" ? value : undefined;
7310
+ } catch { return undefined; }
7311
+ }
7312
+
7313
+ function digest(value) {
7314
+ try {
7315
+ const raw = JSON.stringify(value);
7316
+ return { bytes: Buffer.byteLength(raw), sha256: "sha256:" + createHash("sha256").update(raw).digest("hex") };
7317
+ } catch { return undefined; }
7318
+ }
7319
+
7320
+ function taskType(value) {
7321
+ let text;
7322
+ try { text = JSON.stringify(value).toLowerCase(); } catch { return "general"; }
7323
+ const has = (...terms) => terms.some((term) => text.includes(term));
7324
+ if (has("migration", "migrate", "schema change", "backfill", "rollback")) return "migration";
7325
+ if (has("bug", "fix", "broken", "regression", "crash", "error", "incorrect")) return "bugfix";
7326
+ if (has("investigate", "diagnose", "root cause", "why does", "trace")) return "investigation";
7327
+ if (has("refactor", "restructure", "reorganize", "cleanup")) return "refactor";
7328
+ if (has("review", "audit", "critique", "assess")) return "review";
7329
+ if (has("verify", "verification", "prove", "validate", "check that")) return "verification";
7330
+ if (has("build", "implement", "add", "create", "ship", "feature")) return "feature";
7331
+ return "general";
7332
+ }
7333
+
7334
+ function taskTerms(value) {
7335
+ let text;
7336
+ try { text = JSON.stringify(value); } catch { return []; }
7337
+ const stop = new Set(["about", "after", "agent", "before", "build", "change", "code", "create", "from", "have", "help", "implement", "into", "make", "please", "project", "repository", "should", "spec", "task", "that", "then", "there", "these", "they", "this", "through", "user", "want", "what", "when", "where", "which", "with", "would", "your"]);
7338
+ const out = [];
7339
+ const seen = new Set();
7340
+ for (const raw of text.match(/[A-Za-z][A-Za-z0-9_./-]{2,63}/g) ?? []) {
7341
+ const term = raw.toLowerCase().replace(/^[-./]+|[-./]+$/g, "");
7342
+ if (!term || term.includes("..") || stop.has(term) || seen.has(term) || /^(?:sk|pk|rk|ghp|github_pat|xox[baprs]|akia)[-_]/i.test(term) || /^[a-z0-9_-]{40,}$/i.test(term)) continue;
7343
+ seen.add(term);
7344
+ out.push(term);
7345
+ if (out.length === 12) break;
7346
+ }
7347
+ return out;
7348
+ }
7349
+
7350
+ function taskContinuation(value) {
7351
+ const visit = (item) => {
7352
+ if (typeof item === "string") return item;
7353
+ if (Array.isArray(item)) return item.map(visit).filter(Boolean).join(" ");
7354
+ if (!item || typeof item !== "object") return "";
7355
+ return visit(item.text ?? item.content ?? item.message ?? "");
7356
+ };
7357
+ const prompt = visit(value).trim().toLowerCase();
7358
+ if (!prompt || prompt.length > 160 || prompt.split(/\\s+/).length > 14) return false;
7359
+ return /^(?:please\\s+)?(?:continue|go ahead|keep going|proceed|do (?:it|that)|fix (?:it|that)|retry|try again|explain (?:it|that)|what do you mean|yes|yep|yeah|why\\??|how\\??)[.!?\\s]*$/.test(prompt);
7360
+ }
7361
+
7362
+ export default {
7363
+ id: "caveman-native",
7364
+ async setup(ctx) {
7365
+ // Per-plugin-instance state: one setup() runs per location, so two
7366
+ // projects never share session context through module scope.
7367
+ const contexts = new Map();
7368
+ const pending = new Map();
7369
+
7370
+ function sessionContext(sessionID) {
7371
+ if (!contexts.has(sessionID)) {
7372
+ const out = call("SessionStart", { session_id: sessionID, surface: "cli" });
7373
+ const context = out?.hookSpecificOutput?.additionalContext;
7374
+ contexts.set(sessionID, typeof context === "string" ? context : "");
7375
+ }
7376
+ return contexts.get(sessionID);
7377
+ }
7378
+
7379
+ const controller = new AbortController();
7380
+ const events = (async () => {
7381
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
7382
+ handleEvent(event);
7383
+ }
7384
+ })().catch(() => {
7385
+ if (!controller.signal.aborted) console.warn("[caveman-native] Event subscription failed");
7386
+ });
7387
+
7388
+ function sameLocation(event) {
7389
+ return event.location?.directory === ctx.location.directory &&
7390
+ event.location?.workspaceID === ctx.location.workspaceID;
7391
+ }
7392
+
7393
+ function handleEvent(event) {
7394
+ if (!sameLocation(event)) return;
7395
+ const type = event.type;
7396
+ const sessionID = event.data?.sessionID;
7397
+ if (typeof sessionID !== "string" || !sessionID) return;
7398
+ if (type === "session.created") sessionContext(sessionID);
7399
+ if (type === "session.idle") call("Stop", { session_id: sessionID });
7400
+ // "session.compacted" is the V1 event name; V2 reports compaction
7401
+ // through "session.compaction.ended". Handle both.
7402
+ if (type === "session.compaction.ended" || type === "session.compacted") {
7403
+ const out = call("PostCompact", { session_id: sessionID });
7404
+ const context = out?.hookSpecificOutput?.additionalContext;
7405
+ if (typeof context === "string" && context) contexts.set(sessionID, context);
7406
+ }
7407
+ if (type === "session.deleted") {
7408
+ call("SessionEnd", { session_id: sessionID });
7409
+ contexts.delete(sessionID);
7410
+ pending.delete(sessionID);
7411
+ }
7412
+ }
7413
+
7414
+ await ctx.session.hook("prompt", (event) => {
7415
+ const prompt = event.prompt ?? {};
7416
+ const decision = call("UserPromptSubmit", {
7417
+ session_id: event.sessionID,
7418
+ prompt: digest(prompt),
7419
+ task_type: taskType(prompt),
7420
+ task_terms: taskTerms(prompt),
7421
+ task_continuation: taskContinuation(prompt),
7422
+ });
7423
+ const dynamic = decision?.hookSpecificOutput?.additionalContext;
7424
+ if (typeof dynamic === "string" && dynamic) pending.set(event.sessionID, dynamic);
7425
+ });
7426
+
7427
+ await ctx.session.hook("context", (event) => {
7428
+ const stable = sessionContext(event.sessionID);
7429
+ if (stable) event.system.push({ type: "text", text: stable });
7430
+ const hint = pending.get(event.sessionID);
7431
+ if (hint) {
7432
+ event.system.push({ type: "text", text: hint });
7433
+ pending.delete(event.sessionID);
7434
+ }
7435
+ });
7436
+
7437
+ await ctx.session.hook("compaction", (event) => {
7438
+ call("PreCompact", { session_id: event.sessionID });
7439
+ const stable = sessionContext(event.sessionID);
7440
+ if (stable) event.system.push({ type: "text", text: stable });
7441
+ });
7442
+
7443
+ await ctx.tool.hook("execute.before", (event) => {
7444
+ const decision = call("PreToolUse", {
7445
+ session_id: event.sessionID,
7446
+ tool_name: event.tool,
7447
+ tool_input: event.input,
7448
+ });
7449
+ if (typeof decision?.hookSpecificOutput?.additionalContext === "string") {
7450
+ pending.set(event.sessionID, decision.hookSpecificOutput.additionalContext);
7451
+ }
7452
+ // V1 named this tool "bash"; V2 renamed the permission action to
7453
+ // "shell". Accept both so the rewrite survives either host.
7454
+ const input = event.input;
7455
+ if ((event.tool === "bash" || event.tool === "shell") &&
7456
+ input && typeof input === "object" && typeof input.command === "string") {
7457
+ try {
7458
+ const raw = execFileSync(command, [...prefix, "shrink-hook"], {
7459
+ input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
7460
+ encoding: "utf8",
7461
+ timeout: 750,
7462
+ });
7463
+ const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
7464
+ if (typeof rewritten === "string" && rewritten) input.command = rewritten;
7465
+ } catch {}
7466
+ }
7467
+ });
7468
+
7469
+ await ctx.tool.hook("execute.after", (event) => {
7470
+ if (event.status !== "completed") return;
7471
+ const decision = call("PostToolUse", {
7472
+ session_id: event.sessionID,
7473
+ tool_name: event.tool,
7474
+ tool_input: event.input,
7475
+ tool_output: event.result,
7476
+ });
7477
+ const replacement = decision?.hookSpecificOutput?.updatedToolOutput ?? decision?.output_replacement;
7478
+ if (typeof replacement === "string") {
7479
+ event.result = { ...event.result, content: replacement };
7480
+ }
7481
+ });
7482
+
7483
+ return () => {
7484
+ controller.abort();
7485
+ for (const sessionID of contexts.keys()) call("SessionEnd", { session_id: sessionID });
7486
+ contexts.clear();
7487
+ pending.clear();
7488
+ };
7489
+ },
7490
+ };
7491
+ `;
7492
+ }
6942
7493
  function opencodeNativeMutations(gw, mcpBinary) {
6943
7494
  const configPath = join(homedir(), ".config", "opencode", "opencode.json");
6944
7495
  const before = fileBytes(configPath);
@@ -7671,6 +8222,69 @@ function readNativeJournal(agent) {
7671
8222
  function readPendingNativeJournal(agent) {
7672
8223
  return readNativeJournalAt(nativePendingJournalPath(agent), agent);
7673
8224
  }
8225
+ // nativeRoutePinnedFor reports the config file that pins this agent's base URL,
8226
+ // when native routing is installed for it, or null when nothing is pinned.
8227
+ //
8228
+ // It reads the install journal rather than re-deriving per-agent config shapes,
8229
+ // so it covers every native host by construction: claude's settings.json env
8230
+ // block, codex's config.toml model_provider, hermes/gemini/aider's marker
8231
+ // fences, opencode's routes map, pi's bundle. A caller that needs to point an
8232
+ // agent somewhere else for one run has to know that any of these outranks the
8233
+ // environment it is about to set.
8234
+ //
8235
+ // Deliberately journal-only and file-cheap: unlike nativeIntegrationStatus this
8236
+ // probes no binary, proxy or MCP server, because the question is only "is a
8237
+ // route pinned on disk", not "is the whole integration healthy".
8238
+ //
8239
+ // The PENDING journal has to be consulted too, and the two are read differently.
8240
+ // installNativeAgent writes the pending journal first, then each host file, and
8241
+ // publishes the committed journal LAST. So a process death between those leaves
8242
+ // a fully applied, fully readable pinned route on disk with only the pending
8243
+ // journal to show for it — which is exactly the state this guard exists to
8244
+ // catch, reached by a crash instead of a successful install.
8245
+ //
8246
+ // A committed journal is taken at its word: enable finished, the route is
8247
+ // pinned. A pending one is genuinely ambiguous — the mutation may or may not
8248
+ // have landed before the process died — so it is resolved against the file
8249
+ // itself using the after_sha256 the journal already records. That is
8250
+ // agent-agnostic (no per-host config shapes here) and avoids refusing a trial
8251
+ // over a stale pending journal whose writes never happened.
8252
+ function nativeRoutePinnedFor(agent) {
8253
+ const routeIn = (owned) => {
8254
+ if (!owned)
8255
+ return null;
8256
+ if (typeof owned.route === "string" && owned.route)
8257
+ return owned.route;
8258
+ // opencode pins one route per protocol instead of a single base URL.
8259
+ const routes = owned.routes;
8260
+ if (routes && typeof routes === "object" && !Array.isArray(routes)) {
8261
+ for (const value of Object.values(routes)) {
8262
+ if (typeof value === "string" && value)
8263
+ return value;
8264
+ }
8265
+ }
8266
+ return null;
8267
+ };
8268
+ const committed = readNativeJournal(agent);
8269
+ for (const operation of committed?.operations ?? []) {
8270
+ const route = routeIn(operation.owned);
8271
+ if (route)
8272
+ return { file: operation.file, route, pending: false };
8273
+ }
8274
+ const pending = readPendingNativeJournal(agent);
8275
+ for (const operation of pending?.operations ?? []) {
8276
+ const route = routeIn(operation.owned);
8277
+ if (!route)
8278
+ continue;
8279
+ const current = fileBytes(operation.file);
8280
+ // No file, or contents that are not what this operation would have written,
8281
+ // means the interrupted install never got as far as pinning this route.
8282
+ if (current && bytesHash(current) === operation.after_sha256) {
8283
+ return { file: operation.file, route, pending: true };
8284
+ }
8285
+ }
8286
+ return null;
8287
+ }
7674
8288
  function recoverPendingNativeInstallUnlocked(agent) {
7675
8289
  const pending = readPendingNativeJournal(agent);
7676
8290
  if (!pending)
@@ -7780,6 +8394,22 @@ function enableNative(argv) {
7780
8394
  applyNativeMutations(agent, profile, mutations);
7781
8395
  return "enabled";
7782
8396
  });
8397
+ // Outside the lock, and on BOTH outcomes. The native SessionStart hook
8398
+ // autostarts the proxy, but only once the host has approved the installed
8399
+ // hooks (Codex gates this behind /hooks), and `enable` run on its own —
8400
+ // outside the `caveman <agent>` shortcut, which has its own blocking
8401
+ // pre-start at its call site — otherwise leaves that window open
8402
+ // indefinitely: config.toml/settings route every request through a proxy
8403
+ // nothing has confirmed is listening, which is what turns a fresh Codex
8404
+ // session into a mid-stream disconnect rather than a connection error.
8405
+ //
8406
+ // "already" has to run it too. Re-running `enable` is exactly what someone
8407
+ // does when the route is dead, and the installed-state branch returns
8408
+ // before any of this; gating on a fresh install would make proxy startup an
8409
+ // accidental side effect of the first install rather than something the
8410
+ // command does. The integration lock is for file mutations — a liveness
8411
+ // probe and a detached spawn need no part of it.
8412
+ ensureLocalProxyForNative(agent, gw);
7783
8413
  if (outcome === "already") {
7784
8414
  process.stderr.write(`${mark("ok")} ${profile.display_name}: ${agent === "aider" ? "shallow" : "native"} Caveman already enabled\n`);
7785
8415
  continue;
@@ -8311,13 +8941,38 @@ function nativeIntegrationStatus(agent) {
8311
8941
  return false;
8312
8942
  }
8313
8943
  })();
8944
+ // Same class as piBundleCurrent above, one step removed: opencode's plugin API
8945
+ // is chosen when the mutations are built, so an install made against OpenCode
8946
+ // 1.x keeps its V1 hook map after the host upgrades to 2.x — which that host
8947
+ // refuses to load (#1083). Nothing else drifts on that upgrade: same journal,
8948
+ // same bytes, so packCurrent and ownedHealthy both still pass and doctor called
8949
+ // an unloadable plugin "installed". `caveman opencode` deliberately skips
8950
+ // enableNative whenever a journal exists (status probes spawn subprocesses),
8951
+ // which is exactly why that skip's own comment names doctor as the repair door
8952
+ // for drifted installs — so the drift has to be visible here to be repairable.
8953
+ // An unreadable version yields no judgement, matching opencodeNativePluginSource:
8954
+ // "unknown" is not evidence of a new host, so it must not degrade a good install.
8955
+ const opencodePluginApiCurrent = agent !== "opencode" || (() => {
8956
+ const operation = journal?.operations.find((item) => item.kind === "opencode-plugin");
8957
+ const current = operation ? fileBytes(operation.file)?.toString("utf8") : null;
8958
+ if (!current)
8959
+ return true;
8960
+ const installedV2 = current.includes("async setup(ctx)");
8961
+ const installedV1 = current.includes("export const CavemanNative");
8962
+ if (installedV1 === installedV2)
8963
+ return true;
8964
+ const semver = parsedSemver(host.version);
8965
+ if (!semver)
8966
+ return true;
8967
+ return (semver[0] >= 2) === installedV2;
8968
+ })();
8314
8969
  const routeHealthy = ownedHealthy && (agent === "opencode"
8315
8970
  ? routeOperation?.owned?.routes?.openai === appendUrlPath(expectedRoute, "/openai/v1")
8316
8971
  && routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
8317
8972
  : agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
8318
8973
  const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
8319
8974
  const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
8320
- const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy ? "degraded" : "installed";
8975
+ const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy || !opencodePluginApiCurrent ? "degraded" : "installed";
8321
8976
  const coreSupported = agent === "aider" ? ownedHealthy : ownedHealthy && Boolean(NATIVE_PACK.core);
8322
8977
  const coreActive = agent === "aider"
8323
8978
  ? ownedHealthy
@@ -8325,7 +8980,8 @@ function nativeIntegrationStatus(agent) {
8325
8980
  const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
8326
8981
  const components = {
8327
8982
  routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? fileText.includes(HERMES_NATIVE_ROUTE_BEGIN) : agent === "gemini" ? fileText.includes(GEMINI_NATIVE_ENV_BEGIN) : agent === "opencode" ? fileText.includes("caveman:native-opencode") : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
8328
- lifecycle_hooks: agent !== "aider" && ownedHealthy,
8983
+ // A plugin the host cannot load runs no hooks, whatever its bytes hash to.
8984
+ lifecycle_hooks: agent !== "aider" && ownedHealthy && opencodePluginApiCurrent,
8329
8985
  core: coreActive,
8330
8986
  mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
8331
8987
  // Codex is false for the same reason hermes is: no command rewrite happens. The
@@ -8893,6 +9549,70 @@ function wrapBaseUrlEnv(gw) {
8893
9549
  env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
8894
9550
  return env;
8895
9551
  }
9552
+ // wrapWorkTags names the repository and branch a wrapped session is launched
9553
+ // in, as the managed gateway's x-cave-tags value ("repo=owner/name,branch=…").
9554
+ // Delivery joins coding-agent spend to merged changes on exactly these two
9555
+ // keys, and nothing else in the request carries them. Read once at spawn with
9556
+ // hardened git (git-safe.ts); a launch outside a repository, without an origin,
9557
+ // or on a detached HEAD yields the tags it can and never fails the wrap.
9558
+ // The value is fixed for the process: a branch switch mid-session is picked up
9559
+ // by the next launch, not this one.
9560
+ //
9561
+ // Only github.com remotes are tagged: Cloud joins tags['repo'] to the GitHub
9562
+ // pull requests it imported, keyed owner/name, so a same-named fork on another
9563
+ // host would collide with the wrong repository. Values are printable ASCII
9564
+ // without comma or equals — a header value must be a ByteString, and the tag
9565
+ // list is comma/equals delimited — anything else drops the tag, never the wrap.
9566
+ export function wrapWorkTags(cwd = process.cwd()) {
9567
+ const read = (...args) => {
9568
+ try {
9569
+ return execFileSync("git", hardenedGitArgs(cwd, ...args), {
9570
+ encoding: "utf8", env: hardenedGitEnv(), stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
9571
+ }).trim();
9572
+ }
9573
+ catch {
9574
+ return "";
9575
+ }
9576
+ };
9577
+ const parts = [];
9578
+ const repo = repoSlugFromRemote(read("remote", "get-url", "origin"));
9579
+ if (repo)
9580
+ parts.push(`repo=${repo}`);
9581
+ const branch = read("branch", "--show-current");
9582
+ if (branch && branch.length <= 255 && workTagValueSafe(branch))
9583
+ parts.push(`branch=${branch}`);
9584
+ return parts.join(",");
9585
+ }
9586
+ // workTagValueSafe: printable ASCII (0x21–0x7E) with no comma or equals.
9587
+ export function workTagValueSafe(value) {
9588
+ return /^[\x21-\x2B\x2D-\x3C\x3E-\x7E]+$/.test(value);
9589
+ }
9590
+ // repoSlugFromRemote reduces a github.com remote URL to owner/name — the form
9591
+ // Cloud's Delivery join and its imported pull requests use — or "" when the
9592
+ // remote is on any other host or has no such shape. Never the URL itself: a
9593
+ // remote can embed a credential.
9594
+ export function repoSlugFromRemote(remote) {
9595
+ const cleaned = trimTrailingSlashes(remote.trim()).replace(/\.git$/i, "");
9596
+ let host = "";
9597
+ let path = "";
9598
+ const url = /^[a-z][a-z0-9+.-]*:\/\/([^/]+)\/(.*)$/i.exec(cleaned);
9599
+ const scp = /^(?:[^@/:]+@)?([^/:]+):(.*)$/.exec(cleaned);
9600
+ if (url) {
9601
+ host = url[1].replace(/^[^@]*@/, "").replace(/:\d+$/, "");
9602
+ path = url[2];
9603
+ }
9604
+ else if (scp) {
9605
+ host = scp[1];
9606
+ path = scp[2];
9607
+ }
9608
+ else {
9609
+ return "";
9610
+ }
9611
+ if (host.toLowerCase() !== "github.com")
9612
+ return "";
9613
+ const match = /^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)$/.exec(path);
9614
+ return match ? `${match[1]}/${match[2]}` : "";
9615
+ }
8896
9616
  function attributedGatewayUrl(gw, agent) {
8897
9617
  return appendUrlPath(gw, `/w/${agent.id}`);
8898
9618
  }
@@ -8914,6 +9634,22 @@ function mergeAnthropicCustomHeader(raw, name, value) {
8914
9634
  kept.push(`${name}: ${value}`);
8915
9635
  return kept.join("\n");
8916
9636
  }
9637
+ // existingCustomHeader returns the value of one header inside the newline-
9638
+ // separated ANTHROPIC_CUSTOM_HEADERS block ("" when present but empty), or
9639
+ // undefined when absent.
9640
+ function existingCustomHeader(raw, name) {
9641
+ const target = name.toLowerCase();
9642
+ for (const line of (raw ?? "").split(/\r\n|\n|\r/)) {
9643
+ const colon = line.indexOf(":");
9644
+ if (colon > 0 && line.slice(0, colon).trim().toLowerCase() === target)
9645
+ return line.slice(colon + 1).trim();
9646
+ }
9647
+ return undefined;
9648
+ }
9649
+ // workTagsOff: CAVEMAN_WORK_TAGS=0 (or false/off/no) stops the repo/branch tags.
9650
+ export function workTagsOff(value) {
9651
+ return /^(0|false|off|no)$/i.test((value ?? "").trim());
9652
+ }
8917
9653
  function bedrockCredentialEnvValue(env, name) {
8918
9654
  const raw = env[name];
8919
9655
  if (typeof raw !== "string" || !raw.trim())
@@ -9102,6 +9838,16 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentAr
9102
9838
  }
9103
9839
  if (agent.id === "hermes")
9104
9840
  applyHermesAuthEnv(env, renderedGw, gw);
9841
+ if (agent.id === "claude" && wrapMode(gw) === "managed") {
9842
+ // Repository and branch ride every request as x-cave-tags so the managed
9843
+ // gateway can join this session's spend to the change it ships. A user's
9844
+ // own x-cave-tags is sent exactly as set (even empty), and CAVEMAN_WORK_TAGS=0 sends none.
9845
+ const tags = workTagsOff(env.CAVEMAN_WORK_TAGS) || existingCustomHeader(env.ANTHROPIC_CUSTOM_HEADERS, "x-cave-tags") !== undefined
9846
+ ? ""
9847
+ : wrapWorkTags();
9848
+ if (tags)
9849
+ env.ANTHROPIC_CUSTOM_HEADERS = mergeAnthropicCustomHeader(env.ANTHROPIC_CUSTOM_HEADERS, "x-cave-tags", tags);
9850
+ }
9105
9851
  if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
9106
9852
  // Keep Claude Code's first-party capability set (1M context window /
9107
9853
  // ~600k auto-compact window) intact behind the local pass-through proxy
@@ -9236,28 +9982,59 @@ export function shouldOpenLoginBrowser(noBrowser, interactive = Boolean(process.
9236
9982
  }
9237
9983
  function validateLoginArgs(argv) {
9238
9984
  let noBrowser = false;
9985
+ const values = new Map();
9986
+ const usage = "login [--no-browser] [--instance <https-origin> | --base-url <url> [--gateway-url <url>]]";
9239
9987
  for (let index = 0; index < argv.length; index++) {
9240
9988
  const arg = argv[index];
9241
9989
  if (arg === "--no-browser") {
9242
9990
  if (noBrowser)
9243
- commandUsage("login [--no-browser] [--base-url <url>] [--gateway-url <url>]");
9991
+ commandUsage(usage);
9244
9992
  noBrowser = true;
9245
9993
  continue;
9246
9994
  }
9247
- if (arg === "--base-url" || arg === "--gateway-url") {
9248
- const value = argv[++index];
9249
- if (!value || value.startsWith("-"))
9250
- commandUsage("login [--no-browser] [--base-url <url>] [--gateway-url <url>]");
9251
- continue;
9252
- }
9253
- if (arg.startsWith("--base-url=") || arg.startsWith("--gateway-url=")) {
9254
- if (!arg.slice(arg.indexOf("=") + 1))
9255
- commandUsage("login [--no-browser] [--base-url <url>] [--gateway-url <url>]");
9995
+ const flag = arg.split("=", 1)[0];
9996
+ if (["--instance", "--base-url", "--gateway-url"].includes(flag)) {
9997
+ const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : argv[++index];
9998
+ if (!value || value.startsWith("-") || values.has(flag))
9999
+ commandUsage(usage);
10000
+ values.set(flag, value);
9256
10001
  continue;
9257
10002
  }
9258
- commandUsage("login [--no-browser] [--base-url <url>] [--gateway-url <url>]");
10003
+ commandUsage(usage);
10004
+ }
10005
+ const instance = values.get("--instance");
10006
+ if (instance === undefined)
10007
+ return { noBrowser };
10008
+ if (values.has("--base-url") || values.has("--gateway-url"))
10009
+ commandUsage(usage);
10010
+ const url = new URL(instance);
10011
+ if (!secureLoginURL(url) || url.pathname !== "/" || url.search || url.hash || url.hostname.replace(/\.$/, "") === new URL(PROD_API_URL).hostname) {
10012
+ throw new Error("--instance requires a private HTTPS origin (HTTP loopback is allowed for local development)");
10013
+ }
10014
+ return { noBrowser, instance: url.origin };
10015
+ }
10016
+ function secureLoginURL(url, allowLoopback = true) {
10017
+ return !url.username && !url.password && (url.protocol === "https:" ||
10018
+ (allowLoopback && url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)));
10019
+ }
10020
+ function privateVerificationURL(code, instance) {
10021
+ if (typeof code.device_code !== "string" || !code.device_code || code.device_code.length > 4096 ||
10022
+ typeof code.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/.test(code.user_code) ||
10023
+ typeof code.expires_in !== "number" || !Number.isFinite(code.expires_in) || code.expires_in <= 0 || code.expires_in > 3600 ||
10024
+ (code.interval !== undefined && (typeof code.interval !== "number" || !Number.isFinite(code.interval) || code.interval < 0 || code.interval > 60))) {
10025
+ throw new Error("private device authorization returned an invalid code response");
9259
10026
  }
9260
- return { noBrowser };
10027
+ const value = code.verification_uri_complete ?? code.verification_uri;
10028
+ if (typeof value !== "string")
10029
+ throw new Error("private device authorization omitted its browser URL");
10030
+ const url = new URL(value);
10031
+ if (!secureLoginURL(url, new URL(instance).protocol === "http:") || url.hash) {
10032
+ throw new Error("private device authorization returned an unsafe browser URL");
10033
+ }
10034
+ url.searchParams.set("user_code", code.user_code);
10035
+ url.searchParams.set("connection", "mcp");
10036
+ url.searchParams.set("client_name", "Caveman CLI");
10037
+ return url.href;
9261
10038
  }
9262
10039
  function openLoginBrowser(url) {
9263
10040
  const opener = loginBrowserOpener(url);
@@ -9280,6 +10057,7 @@ async function acknowledgeDeviceGrant(baseURL, accessToken, deviceCode, ackToken
9280
10057
  try {
9281
10058
  const response = await fetch(`${baseURL}/api/v1/auth/device/ack`, {
9282
10059
  method: "POST",
10060
+ redirect: "manual",
9283
10061
  headers: {
9284
10062
  authorization: `Bearer ${accessToken}`,
9285
10063
  "content-type": "application/json",
@@ -9308,17 +10086,18 @@ async function acknowledgeDeviceGrant(baseURL, accessToken, deviceCode, ackToken
9308
10086
  }
9309
10087
  // 0600 credentials file) — never in plaintext config. organization_id is bound
9310
10088
  // from the returned token, never from any local input.
9311
- // Keep device-flow implementation dormant for later beta reopening. This gate
9312
- // runs before argument parsing, network requests, browser launch, or local writes.
10089
+ // Hosted login remains gated; explicit private instances use project access.
9313
10090
  function blockCloudLoginWhileBeta() {
9314
10091
  throw new Error("Caveman Cloud platform is still in beta.");
9315
10092
  }
9316
10093
  async function login(argv = []) {
9317
- blockCloudLoginWhileBeta();
9318
- const { noBrowser } = validateLoginArgs(argv);
9319
- const baseURL = resolveLoginBaseUrl(argv);
10094
+ if (!argv.some((arg) => arg === "--instance" || arg.startsWith("--instance=")))
10095
+ blockCloudLoginWhileBeta();
10096
+ const { noBrowser, instance } = validateLoginArgs(argv);
10097
+ const baseURL = instance ?? resolveLoginBaseUrl(argv);
9320
10098
  const codeResp = await fetch(`${baseURL}/api/v1/auth/device/code`, {
9321
10099
  method: "POST",
10100
+ redirect: "error",
9322
10101
  headers: { "content-type": "application/json" },
9323
10102
  body: "{}",
9324
10103
  signal: AbortSignal.timeout(5000),
@@ -9327,8 +10106,8 @@ async function login(argv = []) {
9327
10106
  throw new Error(`device authorization failed: HTTP ${codeResp.status}`);
9328
10107
  const code = await codeResp.json();
9329
10108
  if (!code.device_code)
9330
- throw new Error(`device authorization failed: ${JSON.stringify(code)}`);
9331
- const verificationURL = code.verification_uri_complete ?? code.verification_uri;
10109
+ throw new Error("device authorization failed: missing device code");
10110
+ const verificationURL = instance ? privateVerificationURL(code, instance) : code.verification_uri_complete ?? code.verification_uri;
9332
10111
  console.error(`\n Authorize this device in your browser:`);
9333
10112
  console.error(` ${verificationURL}`);
9334
10113
  console.error(` code: ${code.user_code}\n`);
@@ -9343,6 +10122,7 @@ async function login(argv = []) {
9343
10122
  try {
9344
10123
  const tokResp = await fetch(`${baseURL}/api/v1/auth/device/token`, {
9345
10124
  method: "POST",
10125
+ redirect: "manual",
9346
10126
  headers: { "content-type": "application/json" },
9347
10127
  body: JSON.stringify({ device_code: code.device_code }),
9348
10128
  signal: AbortSignal.timeout(5000),
@@ -9354,7 +10134,7 @@ async function login(argv = []) {
9354
10134
  if (Number.isFinite(seconds) && seconds >= 0)
9355
10135
  retryAfterMs = seconds * 1000;
9356
10136
  }
9357
- tok = await tokResp.json();
10137
+ tok = tokenStatus >= 300 && tokenStatus < 400 ? {} : await tokResp.json();
9358
10138
  }
9359
10139
  catch (error) {
9360
10140
  // RFC 8628 polling is retryable: a dropped connection or malformed
@@ -9367,6 +10147,8 @@ async function login(argv = []) {
9367
10147
  await sleep(Math.max(intervalMs, retryAfterMs, 200));
9368
10148
  continue;
9369
10149
  }
10150
+ if (tokenStatus >= 300 && tokenStatus < 400)
10151
+ throw new Error("device login refused a redirected token endpoint");
9370
10152
  if (tokenStatus === 429) {
9371
10153
  // rateLimitAuth returns a nested cave error envelope rather than the RFC
9372
10154
  // `error` string. Status is the authoritative retry signal here.
@@ -9375,6 +10157,13 @@ async function login(argv = []) {
9375
10157
  }
9376
10158
  const accessToken = typeof tok.access_token === "string" ? tok.access_token : "";
9377
10159
  if (accessToken) {
10160
+ if (instance && (tokenStatus < 200 || tokenStatus >= 300 || tok.credential_kind !== "none" ||
10161
+ ["gateway_api_key", "gateway_key_id", "gateway_url"].some((key) => tok[key] != null) ||
10162
+ typeof tok.refresh_token !== "string" || !tok.refresh_token || typeof tok.project_id !== "string" || !tok.project_id ||
10163
+ typeof tok.delivery_ack_token !== "string" || !tok.delivery_ack_token || typeof tok.scope !== "string" || !tok.scope ||
10164
+ tok.scope.split(/\s+/).some((scope) => scope === "proxy:write" || scope === "sdk:write"))) {
10165
+ throw new Error("private device login requires a keyless project grant with a refresh token and delivery acknowledgement");
10166
+ }
9378
10167
  const credentials = {
9379
10168
  access_token: accessToken,
9380
10169
  ...(typeof tok.refresh_token === "string" && tok.refresh_token ? { refresh_token: tok.refresh_token } : {}),
@@ -9384,7 +10173,7 @@ async function login(argv = []) {
9384
10173
  };
9385
10174
  const tokenStore = storeCredentials(credentials);
9386
10175
  const organizationId = orgFromToken(accessToken);
9387
- const gateway = resolveLoginGatewayUrl(baseURL, tok, code, argv);
10176
+ const gateway = instance ? "" : resolveLoginGatewayUrl(baseURL, tok, code, argv);
9388
10177
  const saved = { baseURL, token: "", tokenStore };
9389
10178
  if (organizationId)
9390
10179
  saved.organizationId = organizationId;
@@ -9406,6 +10195,10 @@ async function login(argv = []) {
9406
10195
  // until the control plane has recorded that this CLI stored the bundle.
9407
10196
  await acknowledgeDeviceGrant(baseURL, credentials.access_token, code.device_code, ackToken);
9408
10197
  }
10198
+ if (instance) {
10199
+ print({ authenticated: true, baseURL, organization_id: organizationId ?? null, project_id: credentials.project_id, scope: tok.scope, credential_kind: "none", token_store: tokenStore });
10200
+ return;
10201
+ }
9409
10202
  // Mint/refresh the local-wrap entitlement for this device. Best
9410
10203
  // effort: login never fails for seats or a down entitlement service.
9411
10204
  await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);
@@ -9463,6 +10256,7 @@ async function logout() {
9463
10256
  };
9464
10257
  const request = {
9465
10258
  method: "POST",
10259
+ redirect: "manual",
9466
10260
  headers,
9467
10261
  signal: AbortSignal.timeout(5000),
9468
10262
  };
@@ -9800,7 +10594,7 @@ function localScanSyncLine(out) {
9800
10594
  return `synced 30-day local scan · inferred token summary · separate from gateway spend and verified savings${destination}`;
9801
10595
  }
9802
10596
  // syncRequestSpan converts one local `requests` row into a caveman-jsonl span
9803
- // line (public/shared/platform/importers Span shape; timestamps are already in
10597
+ // line (Caveman-Cloud public/shared/platform/importers Span shape; timestamps are already in
9804
10598
  // the ClickHouse layout because the proxy writes them that way). The basis and
9805
10599
  // per-row inferred savings ride in attributes — the spans schema has no savings
9806
10600
  // column, and imported rows must never look like verified ledger entries.
@@ -11179,6 +11973,10 @@ function qwenStringList(root, path, fallback) {
11179
11973
  return null;
11180
11974
  return resolved;
11181
11975
  }
11976
+ // Through qwenCavemanToolDenied below: ported, with changes, from Qwen Code
11977
+ // 0.22.3 (https://github.com/QwenLM/qwen-code), Copyright 2025 Google LLC and
11978
+ // Copyright 2025 Qwen, Apache License 2.0. See NOTICE.
11979
+ //
11182
11980
  // Exact wildcard matcher used by Qwen 0.22 for mcp.allowed/mcp.excluded:
11183
11981
  // `*` spans any run, `?` spans one character, everything else is literal.
11184
11982
  function qwenMcpServerPatternMatches(name, pattern) {
@@ -13186,6 +13984,8 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
13186
13984
  // unverified contract; if Codex ever honors that, caveman silently auto-approves a
13187
13985
  // command the user's `approval_policy` meant to gate. Both ends fail closed instead.
13188
13986
  async function shrinkHook() {
13987
+ // Host hooks never report command_run: the POST would hold the host's turn.
13988
+ telemetryCommandSent = true;
13189
13989
  if (nativePolicyMode() === "record" || !new Set(["full-safe", "full-max"]).has(nativeProfile()))
13190
13990
  process.exit(0);
13191
13991
  let raw;
@@ -13461,7 +14261,7 @@ function nativeRepositoryState(cwd) {
13461
14261
  try {
13462
14262
  const status = execFileSync("git", hardenedGitArgs(cwd, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=all"), {
13463
14263
  env: hardenedGitEnv(),
13464
- timeout: 100,
14264
+ timeout: 500, // same budget as nativehook.repositoryStatusBudget; 100ms emptied the state under load
13465
14265
  maxBuffer: 8 * 1024 * 1024,
13466
14266
  encoding: "buffer",
13467
14267
  stdio: ["ignore", "pipe", "ignore"],
@@ -13784,6 +14584,8 @@ function nativeWhy(argv) {
13784
14584
  // never cross the adapter boundary. Any malformed input/write failure stays
13785
14585
  // fail-open and emits no blocking decision.
13786
14586
  async function nativeHook(argv) {
14587
+ // Host hooks never report command_run: the POST would hold the host's turn.
14588
+ telemetryCommandSent = true;
13787
14589
  const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" || argv[0] === "pi" ? argv[0] : undefined;
13788
14590
  if (!agent)
13789
14591
  process.exit(0);
@@ -13818,6 +14620,9 @@ async function nativeHook(argv) {
13818
14620
  }[rawEventName] ?? rawEventName : rawEventName;
13819
14621
  const normalizedEvent = eventName && NATIVE_EVENT_NAMES.has(eventName) ? eventName : "Unknown";
13820
14622
  const sessionId = boundedHookString(event.session_id ?? event.sessionId);
14623
+ // A compaction re-fires SessionStart inside the same session; count real starts.
14624
+ if (normalizedEvent === "SessionStart" && event.source !== "compact")
14625
+ startSessionTelemetry(agent, sessionId, event.source);
13821
14626
  const toolName = boundedHookString(event.tool_name ?? event.toolName);
13822
14627
  const cwd = boundedHookString(event.cwd, 4096);
13823
14628
  const entry = {
@@ -13834,6 +14639,8 @@ async function nativeHook(argv) {
13834
14639
  entry.tool_name = toolName;
13835
14640
  if (cwd)
13836
14641
  entry.cwd_sha256 = `sha256:${createHash("sha256").update(cwd).digest("hex")}`;
14642
+ if (normalizedEvent === "SessionEnd")
14643
+ maybeSpawnAutopilot();
13837
14644
  // SessionStart revives a missing local proxy, but native routing points every
13838
14645
  // LATER turn of the session at that proxy too. Current proxies never expire,
13839
14646
  // but crashes and older binaries can still leave a dead base URL. A plain
@@ -13885,10 +14692,23 @@ async function nativeHook(argv) {
13885
14692
  // it before provider forwarding. Generated structure/order are byte-stable.
13886
14693
  const stableContext = [coreContext, marker].filter(Boolean).join("\n");
13887
14694
  const compactContext = [coreContext, runtimeContext, marker].filter(Boolean).join("\n");
13888
- if (normalizedEvent === "SessionStart" && agent !== "hermes" && stableContext) {
14695
+ // systemMessage is the user-visible channel on Claude/Codex/Gemini SessionStart;
14696
+ // additionalContext would put the nudge in model context instead.
14697
+ // Under the fast hook the parent owns the token and confirms after relaying
14698
+ // our stdout, since it may still drop the output on its own timeout.
14699
+ const relayedToken = boundedHookString(process.env.CAVEMAN_LEARN_NUDGE_TOKEN);
14700
+ const learnNudgeToken = relayedToken || randomUUID();
14701
+ const learnNudge = normalizedEvent === "SessionStart" && (agent === "claude" || agent === "codex" || agent === "gemini")
14702
+ ? claimLearnNudge(boundedHookString(event.source), learnNudgeToken)
14703
+ : undefined;
14704
+ if (normalizedEvent === "SessionStart" && agent !== "hermes" && (stableContext || learnNudge)) {
13889
14705
  process.stdout.write(JSON.stringify({
13890
- hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: stableContext },
13891
- }));
14706
+ ...(learnNudge ? { systemMessage: learnNudge } : {}),
14707
+ ...(stableContext ? { hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: stableContext } } : {}),
14708
+ }), () => {
14709
+ if (learnNudge && !relayedToken)
14710
+ confirmLearnNudge(learnNudgeToken);
14711
+ });
13892
14712
  }
13893
14713
  else if (normalizedEvent === "PostCompact" && agent !== "hermes" && compactContext) {
13894
14714
  process.stdout.write(JSON.stringify({
@@ -14169,6 +14989,8 @@ function writeRecallHookMarker(agentId) {
14169
14989
  // Fail-open by construction: any problem → exit 0 with no output (never blocks the
14170
14990
  // agent, never injects a guess).
14171
14991
  async function memRecallHook() {
14992
+ // Host hooks never report command_run: the POST would hold the host's turn.
14993
+ telemetryCommandSent = true;
14172
14994
  let raw;
14173
14995
  try {
14174
14996
  raw = await readHookStdin();
@@ -15296,6 +16118,39 @@ async function trial(rest) {
15296
16118
  const proxyResolved = which(proxyBin());
15297
16119
  if (!proxyResolved)
15298
16120
  return startMissingProxyUI(proxyBin());
16121
+ // A trial measures traffic by standing up its OWN proxy on a free port under
16122
+ // a `trial:<id>` label and pointing the child at it through the environment.
16123
+ // Native routing pins the base URL inside the agent's own config file, and an
16124
+ // agent reads its config in preference to its environment — so the child goes
16125
+ // to the persistent listener instead, which carries no trial label.
16126
+ // RecordPayload only stores payloads for a `trial:` label, so trial_payloads
16127
+ // stays empty, the replay optimizer has nothing to replay, and every number
16128
+ // in the report renders 0. Nothing errors; the trial exits 0 and reports a
16129
+ // measurement of nothing. Refuse up front instead of producing that report,
16130
+ // and refuse BEFORE `trial start` so no orphan trial row is opened. (#1068)
16131
+ const pinned = nativeRoutePinnedFor(agent?.id ?? requested);
16132
+ if (pinned) {
16133
+ console.error(pinned.pending
16134
+ ? `caveman trial cannot measure ${agent?.id ?? requested}: an interrupted native install left its routing in place.`
16135
+ : `caveman trial cannot measure ${agent?.id ?? requested} while native routing is enabled.`);
16136
+ console.error("");
16137
+ console.error(` ${pinned.file}`);
16138
+ console.error(` pins the base URL to ${pinned.route}`);
16139
+ console.error("");
16140
+ console.error("A trial runs its own proxy on its own port and points the agent at it through");
16141
+ console.error("the environment. That config file wins, so the agent would keep talking to the");
16142
+ console.error("persistent listener, the trial would capture nothing, and the report would say");
16143
+ console.error("zero requests and $0.0000 — which reads as a measurement rather than as silence.");
16144
+ console.error("");
16145
+ // invokedAs(), not invokedCommand(): invokedCommand renders the verb of the
16146
+ // CURRENT invocation, which is always "trial" here, so it would print
16147
+ // "caveman trial <agent>" for the disable and enable lines.
16148
+ console.error(`Turn native routing off for the duration of the trial, then put it back:`);
16149
+ console.error(` ${invokedAs()} disable ${agent?.id ?? requested}`);
16150
+ console.error(` ${invokedAs()} trial -- ${command.join(" ")}`);
16151
+ console.error(` ${invokedAs()} enable ${agent?.id ?? requested}`);
16152
+ process.exit(2);
16153
+ }
15299
16154
  const port = await freePort();
15300
16155
  const listen = `127.0.0.1:${port}`;
15301
16156
  const trialURL = `http://${listen}`;
@@ -15329,12 +16184,39 @@ async function trial(rest) {
15329
16184
  throw error;
15330
16185
  }
15331
16186
  }
15332
- const LEARN_EMPTY = "no Claude Code or Codex sessions found in the last 30d — the plan needs a block repeated across ≥3 sessions; run `caveman claude` a few times, then `caveman learn`";
15333
- const LEARN_DETAILED_NEXT = "next: caveman tools skills install caveman-learn (review + apply, with consent) · preview one: caveman learn apply <sink_id> --dry-run";
16187
+ // learnEmpty names the window the proxy actually scanned (plan.window.since;
16188
+ // older proxies omit it and always scanned 30d).
16189
+ function learnEmpty(plan) {
16190
+ const since = learnSince(plan.window?.since || "30d");
16191
+ return `no Claude Code, Codex, Gemini CLI, opencode or aider sessions found in the last ${since}. A score needs the same text repeated in at least 3 sessions. Use your agent a few times (for example \`caveman claude\`), then run \`caveman learn\` again`;
16192
+ }
16193
+ // learnNoScoreYet explains why there is no score: the score needs the same
16194
+ // text repeated in at least 3 sessions.
16195
+ function learnNoScoreYet(sessions) {
16196
+ return `${commaCount(sessions)} sessions read · no score yet: it needs the same text repeated in at least 3 sessions. Keep using your agent (for example \`${invokedAs()} claude\`), then run \`${invokedAs()} learn\` again`;
16197
+ }
16198
+ const LEARN_CLASS_LABELS = {
16199
+ reducible: "safe fix",
16200
+ recurring_context: "repeated text",
16201
+ behavioral: "habit",
16202
+ load_bearing: "needed",
16203
+ };
16204
+ function learnClassLabel(klass) {
16205
+ return LEARN_CLASS_LABELS[klass] ?? klass.replaceAll("_", " ");
16206
+ }
16207
+ // learnSince turns a --since value like "30d" into "30 days".
16208
+ function learnSince(since) {
16209
+ const days = /^(\d+)d$/.exec(since)?.[1];
16210
+ return days ? `${days} day${days === "1" ? "" : "s"}` : since;
16211
+ }
16212
+ function commaCount(value) {
16213
+ return Math.round(value).toLocaleString("en-US");
16214
+ }
16215
+ const LEARN_DETAILED_NEXT = "next: caveman tools skills install caveman-learn (review and apply fixes; asks first) · preview one fix: caveman learn apply <id> --dry-run";
15334
16216
  const LEARN_ALL_FOOTER = [
15335
- "advanced: caveman learn applied <sink_id> [--fix-kind <kind>] [--note <text>] record an approved, re-measured fix",
15336
- "simulate: caveman learn simulate <sink_id...> sum counterfactual scale over scanned history",
15337
- "scope: caveman learn --repo <substring> filter sessions before analysis",
16217
+ "advanced: caveman learn applied <id> [--fix-kind <kind>] [--note <text>] record a fix you approved, so later runs can measure it",
16218
+ "simulate: caveman learn simulate <id...> estimate what fixes would have saved over your past sessions",
16219
+ "scope: caveman learn --repo <substring> only read sessions from matching repositories",
15338
16220
  ];
15339
16221
  const LEARN_SUMMARY_LIMIT = 3;
15340
16222
  function learnReportPath() {
@@ -15362,14 +16244,15 @@ function renderLearnDetailedRows(plan, markdown) {
15362
16244
  const lines = [];
15363
16245
  for (const [index, sink] of plan.sinks.entries()) {
15364
16246
  const lead = markdown ? `${index + 1}. **${sink.title}**` : `${index + 1}. ${sink.title}`;
15365
- lines.push(`${lead} · ${sink.sink_id} · ${sink.class}`);
16247
+ lines.push(lead);
16248
+ lines.push(` ${learnClassLabel(sink.class)} · id: ${sink.sink_id}`);
15366
16249
  const observed = typeof sink.tokens_observed === "number" && sink.tokens_observed > 0
15367
- ? ` · ~${humanTokens(sink.tokens_observed)} tokens observed (historical)`
16250
+ ? ` · ${commaCount(sink.tokens_observed)} tokens so far`
15368
16251
  : "";
15369
16252
  const prefix = learnMeasuredPrefixSuffix(sink);
15370
- lines.push(` ~${humanTokens(sink.tokens_per_turn)} tokens/turn · ~${humanTokens(sink.tokens_per_day_rate)} tokens/day${observed} · basis: inferred${prefix}`);
16253
+ lines.push(` ${commaCount(sink.tokens_per_turn)} tokens per message · ${commaCount(sink.tokens_per_day_rate)} tokens a day${observed} · estimate${prefix}`);
15371
16254
  if (KNOWN_PRACTICE_IDS.has(sink.practice_id)) {
15372
- lines.push(` practice: ${sink.practice_id} · unmeasured — verified nowhere yet`);
16255
+ lines.push(` practice: ${sink.practice_id} · not measured or verified yet`);
15373
16256
  }
15374
16257
  if (sink.suggestion)
15375
16258
  lines.push(` ${sink.suggestion}`);
@@ -15385,7 +16268,7 @@ function learnMeasuredPrefixSuffix(sink) {
15385
16268
  return "";
15386
16269
  const measured = learnEvidenceNumber(sink, "measured_prefix_tokens");
15387
16270
  return measured && measured > 0
15388
- ? ` · provider-counted prefix ~${humanTokens(measured)} (turn-1 median)`
16271
+ ? ` · a session's first message is ~${humanTokens(measured)} tokens (typical, counted by your provider)`
15389
16272
  : "";
15390
16273
  }
15391
16274
  function compactLearnText(value, max = 108) {
@@ -15399,6 +16282,12 @@ function compactLearnText(value, max = 108) {
15399
16282
  const wordEnd = prefix.lastIndexOf(" ");
15400
16283
  return `${prefix.slice(0, wordEnd > 0 ? wordEnd : prefix.length)}…`;
15401
16284
  }
16285
+ // learnMemoryHealthLine points at the memory & rules doctor findings in one
16286
+ // line; they carry no token rate, so they rarely make the top moves.
16287
+ function learnMemoryHealthLine(plan) {
16288
+ const count = plan.sinks.filter((sink) => sink.sink_id.startsWith("memory_health:")).length;
16289
+ return count > 0 ? `memory files ${count} finding${count === 1 ? "" : "s"} — see ${invokedAs()} learn --all` : undefined;
16290
+ }
15402
16291
  export function learnSummaryMoves(plan) {
15403
16292
  const moves = [];
15404
16293
  const best = plan.portfolio?.best_next_move;
@@ -15406,17 +16295,17 @@ export function learnSummaryMoves(plan) {
15406
16295
  if (best) {
15407
16296
  const confidenceLabels = {
15408
16297
  measured_usage: "measured",
15409
- transcript_inferred: "transcript",
16298
+ transcript_inferred: "estimated from transcripts",
15410
16299
  static_estimate: "estimate",
15411
16300
  };
15412
16301
  const confidence = confidenceLabels[best.confidence] ?? best.confidence;
15413
16302
  const detail = [
15414
- `sink: ${best.top_sink_id}`,
16303
+ best.fix_label,
15415
16304
  best.combined_rate_per_day > 0
15416
- ? `~${humanTokens(best.combined_rate_per_day)} tokens/day`
16305
+ ? `~${humanTokens(best.combined_rate_per_day)} tokens a day`
15417
16306
  : "",
15418
16307
  best.combined_observed_in_window > 0
15419
- ? `~${humanTokens(best.combined_observed_in_window)} tokens observed`
16308
+ ? `~${humanTokens(best.combined_observed_in_window)} tokens so far`
15420
16309
  : "",
15421
16310
  confidence,
15422
16311
  ].filter(Boolean);
@@ -15440,28 +16329,30 @@ export function learnSummaryMoves(plan) {
15440
16329
  const largest = Math.max(0, ...recurring.map((item) => learnEvidenceNumber(item, "block_tokens") ?? 0));
15441
16330
  const sessions = Math.max(0, ...recurring.map((item) => learnEvidenceNumber(item, "recurrence_sessions") ?? 0));
15442
16331
  const facts = [
15443
- "recurring context",
16332
+ "repeated text",
15444
16333
  largest > 0 ? `largest ~${humanTokens(largest)} tokens` : "",
15445
- sessions > 0 ? `up to ${sessions} sessions` : "",
15446
- "inferred",
16334
+ sessions > 0 ? `in up to ${commaCount(sessions)} sessions` : "",
16335
+ "estimate",
15447
16336
  ].filter(Boolean);
15448
16337
  moves.push({
15449
- title: `${recurring.length} context block${recurring.length === 1 ? "" : "s"} repeat across sessions`,
15450
- kind: "recurring context",
16338
+ title: recurring.length === 1
16339
+ ? "1 piece of text gets pasted again in many sessions"
16340
+ : `${recurring.length} pieces of text get pasted again in many sessions`,
16341
+ kind: "repeated text",
15451
16342
  detail: facts.join(" · "),
15452
- action: "Review selected blocks before moving them to memory; repetition does not prove they are unnecessary.",
16343
+ action: "Check each one before moving it to Caveman memory. Repeating doesn't prove the text is unneeded.",
15453
16344
  });
15454
16345
  }
15455
16346
  else {
15456
16347
  const rates = [
15457
- sink.class.replaceAll("_", " "),
15458
- sink.tokens_per_turn > 0 ? `~${humanTokens(sink.tokens_per_turn)} tokens/turn` : "",
15459
- sink.tokens_per_day_rate > 0 ? `~${humanTokens(sink.tokens_per_day_rate)} tokens/day` : "",
15460
- "inferred",
16348
+ learnClassLabel(sink.class),
16349
+ sink.tokens_per_turn > 0 ? `~${humanTokens(sink.tokens_per_turn)} tokens in every message` : "",
16350
+ sink.tokens_per_day_rate > 0 ? `~${humanTokens(sink.tokens_per_day_rate)} tokens a day` : "",
16351
+ "estimate",
15461
16352
  ].filter(Boolean);
15462
16353
  moves.push({
15463
16354
  title: sink.title,
15464
- kind: sink.class.replaceAll("_", " "),
16355
+ kind: learnClassLabel(sink.class),
15465
16356
  detail: rates.join(" · "),
15466
16357
  ...(sink.suggestion ? { action: compactLearnText(sink.suggestion) } : {}),
15467
16358
  });
@@ -15484,23 +16375,23 @@ function renderLearnSummaryRows(plan) {
15484
16375
  function learnSourceLine(plan, sessions) {
15485
16376
  const by = plan.sessions_by_source ?? {};
15486
16377
  const sourceBits = [
15487
- by.claude ? `Claude ${by.claude}` : "",
15488
- by.codex ? `Codex ${by.codex}` : "",
15489
- by.gemini ? `Gemini ${by.gemini}` : "",
15490
- by.opencode ? `opencode ${by.opencode}` : "",
15491
- by.aider ? `aider ${by.aider}` : "",
16378
+ by.claude ? `Claude ${commaCount(by.claude)}` : "",
16379
+ by.codex ? `Codex ${commaCount(by.codex)}` : "",
16380
+ by.gemini ? `Gemini ${commaCount(by.gemini)}` : "",
16381
+ by.opencode ? `opencode ${commaCount(by.opencode)}` : "",
16382
+ by.aider ? `aider ${commaCount(by.aider)}` : "",
15492
16383
  ].filter(Boolean);
15493
- return `${sessions} sessions${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
16384
+ return `${commaCount(sessions)} sessions read${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
15494
16385
  }
15495
16386
  function learnDiffText(diff) {
15496
16387
  if (!diff)
15497
16388
  return undefined;
15498
16389
  const bits = [
15499
- diff.gone ? `${diff.gone} move${diff.gone === 1 ? "" : "s"} gone` : "",
15500
- diff.back ? `${diff.back} back` : "",
16390
+ diff.gone ? `${diff.gone} finding${diff.gone === 1 ? "" : "s"} gone` : "",
16391
+ diff.back ? `${diff.back} came back` : "",
15501
16392
  diff.fresh ? `${diff.fresh} new` : "",
15502
16393
  ].filter(Boolean);
15503
- return bits.length ? `since your last run ${diff.days}d ago: ${bits.join(" · ")}` : undefined;
16394
+ return bits.length ? `since your last run ${diff.days} day${diff.days === 1 ? "" : "s"} ago: ${bits.join(" · ")}` : undefined;
15504
16395
  }
15505
16396
  export function buildLearnTuiModel(plan, options = {}) {
15506
16397
  const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
@@ -15508,54 +16399,75 @@ export function buildLearnTuiModel(plan, options = {}) {
15508
16399
  const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
15509
16400
  const confirmed = plan.confirmed?.length ?? 0;
15510
16401
  const diffText = learnDiffText(options.diff);
16402
+ const trend = learnTrendLines(plan.trends);
16403
+ const memory = learnMemoryHealthLine(plan);
15511
16404
  const status = sessions === 0
15512
- ? LEARN_EMPTY
16405
+ ? learnEmpty(plan)
15513
16406
  : !recurring
15514
- ? `${sessions} sessions scanned · no block repeated across ≥3 sessions yet — keep running \`${invokedAs()} claude\`, then re-run \`${invokedAs()} learn\``
16407
+ ? learnNoScoreYet(sessions)
15515
16408
  : undefined;
15516
16409
  return {
15517
16410
  score: recurring ? plan.cave_score.score : null,
15518
- scope: "local setup · inferred · not billed spend · separate from org Cave Score",
16411
+ scope: LEARN_SCORE_SCOPE,
15519
16412
  sessions: learnSourceLine(plan, sessions),
15520
16413
  ...(diffText ? { diff: diffText } : {}),
16414
+ ...(trend.length ? { trend } : {}),
15521
16415
  ...(status ? { status } : {}),
15522
16416
  moves: learnSummaryMoves(plan),
15523
16417
  ...(protectedSink
15524
- ? { protected: `${protectedSink.title.replace(/^Your\s+/i, "")} · included in score, never auto-fixed${learnMeasuredPrefixSuffix(protectedSink)}` }
16418
+ ? { protected: learnProtectedText(protectedSink) }
15525
16419
  : {}),
16420
+ ...(memory ? { memory } : {}),
15526
16421
  ...(confirmed > 0 ? { confirmed } : {}),
15527
16422
  findings: plan.sinks.length,
15528
16423
  report: options.report ?? learnReportPath(),
15529
16424
  };
15530
16425
  }
16426
+ const LEARN_SCORE_SCOPE = "your setup on this computer · an estimate, not your bill · separate from Caveman Cloud's team score";
16427
+ // learnProtectedText describes the needed (load-bearing) baseline: counted in
16428
+ // the score, never changed.
16429
+ function learnProtectedText(sink) {
16430
+ return `${sink.title} · counts in the score, but Caveman never changes it${learnMeasuredPrefixSuffix(sink)}`;
16431
+ }
15531
16432
  // renderLearnSpendLines shows what the scanned window cost and, more usefully,
15532
16433
  // what a million input tokens ACTUALLY cost after the user's own cache mix.
15533
16434
  // The multiplier is the one number that decides whether every other finding in
15534
16435
  // the report is expensive or trivial, so it earns a line above the moves.
15535
- function renderLearnSpendLines(spend, markdown) {
16436
+ function renderLearnSpendLines(spend, markdown, full = true) {
15536
16437
  if (!spend)
15537
16438
  return [];
15538
16439
  const lines = [];
15539
16440
  const currency = spend.currency || "USD";
15540
- const label = markdown ? "### Window cost" : "window cost";
16441
+ const label = markdown ? "### Cost" : "cost";
15541
16442
  if (spend.usd > 0) {
15542
- const window = spend.window_days ? ` over ${spend.window_days}d` : "";
15543
- lines.push(`${label} ${fmtMoney(spend.usd, currency)}${window} · provider-counted tokens at published rates`);
16443
+ const window = spend.window_days ? ` for the last ${spend.window_days} day${spend.window_days === 1 ? "" : "s"}` : "";
16444
+ lines.push(`${label} ${fmtMoney(spend.usd, currency)}${window} · tokens your provider counted, at list prices`);
15544
16445
  }
15545
16446
  const multiplier = spend.effective_input_multiplier ?? 0;
15546
16447
  const rate = spend.effective_input_usd_per_mtok ?? 0;
15547
16448
  if (multiplier > 0 && rate > 0) {
15548
- lines.push(`effective input ${fmtMoney(rate, currency)}/Mtok · ${multiplier.toFixed(2)}x list after cache reuse`);
16449
+ const share = multiplier * 100 >= 1 ? `${Math.round(multiplier * 100)}%` : "under 1%";
16450
+ // Same thresholds as the proxy's effectiveInputSummary.
16451
+ const verdict = multiplier < 0.25 ? "caching is doing its job" : multiplier < 0.6 ? "some caching" : "little or no caching";
16452
+ lines.push(`input really costs ${fmtMoney(rate, currency)} per 1M tokens · ${share} of list price — ${verdict}`);
15549
16453
  }
15550
16454
  const components = (spend.components ?? []).filter((component) => component.usd > 0);
15551
16455
  if (components.length > 0 && spend.usd > 0) {
15552
- lines.push(components.map((component) => `${component.key.replace("_", " ")} ${Math.round(component.share_pct ?? 0)}%`).join(" · "));
16456
+ lines.push(`where it went ${components.map((component) => `${component.key.replaceAll("_", " ")} ${Math.round(component.share_pct ?? 0)}%`).join(" · ")}`);
15553
16457
  }
15554
- for (const row of spend.unpriced ?? []) {
15555
- lines.push(`unpriced ${row.provider}/${row.model} ${humanTokens(row.tokens)} tokens excluded — total is a floor`);
16458
+ const unpriced = spend.unpriced ?? [];
16459
+ if (!full && unpriced.length > 1) {
16460
+ // Compact view: one line; --all, --md, JSON and HTML keep every model.
16461
+ const tokens = unpriced.reduce((sum, row) => sum + row.tokens, 0);
16462
+ lines.push(`no price ${unpriced.length} models (${humanTokens(tokens)} tokens) left out, so the real total is higher · ${invokedAs()} learn --all lists them`);
16463
+ }
16464
+ else {
16465
+ for (const row of unpriced) {
16466
+ lines.push(`no price ${row.provider}/${row.model} ${humanTokens(row.tokens)} tokens left out, so the real total is higher`);
16467
+ }
15556
16468
  }
15557
16469
  if (lines.length > 0) {
15558
- lines.push("subscription plans have no marginal cost; the figure is then the API-equivalent value of the tokens");
16470
+ lines.push("on a subscription plan you pay nothing extra per token; the cost then shows what the tokens would cost on the API");
15559
16471
  }
15560
16472
  return lines;
15561
16473
  }
@@ -15568,56 +16480,65 @@ export function renderLearnPlan(plan, options = {}) {
15568
16480
  const lines = [];
15569
16481
  const confirmedLines = renderLearnConfirmed(plan.confirmed, markdown);
15570
16482
  if (sessions === 0) {
15571
- lines.push(LEARN_EMPTY);
16483
+ lines.push(learnEmpty(plan));
15572
16484
  if (confirmedLines.length > 0)
15573
16485
  lines.push("", ...confirmedLines);
15574
16486
  }
15575
16487
  else if (!recurring) {
15576
16488
  if (plan.sinks.length > 0) {
15577
- lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top moves", ...renderLearnSummaryRows(plan)]), "");
16489
+ lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top findings", ...renderLearnSummaryRows(plan)]), "");
16490
+ const memory = verbose ? undefined : learnMemoryHealthLine(plan);
16491
+ if (memory)
16492
+ lines.push(memory, "");
15578
16493
  }
15579
- lines.push(`${sessions} sessions scanned · no block repeated across ≥3 sessions yet — keep running \`caveman claude\`, then re-run \`caveman learn\``);
16494
+ lines.push(learnNoScoreYet(sessions));
16495
+ lines.push(...(verbose ? [] : learnTrendLines(plan.trends)));
15580
16496
  if (confirmedLines.length > 0)
15581
16497
  lines.push("", ...confirmedLines);
15582
16498
  }
15583
16499
  else {
15584
16500
  lines.push(markdown
15585
- ? `## Setup Score ${plan.cave_score.score} — basis: inferred (local sessions, not billed spend)`
16501
+ ? `## Setup Score ${plan.cave_score.score}/100 — an estimate from your local sessions, not your bill`
15586
16502
  : verbose
15587
- ? `Setup Score ${plan.cave_score.score} · basis: inferred (local sessions, not billed spend)`
16503
+ ? `Setup Score ${plan.cave_score.score}/100 · an estimate from your local sessions, not your bill`
15588
16504
  : `Setup Score ${plan.cave_score.score}/100`);
15589
16505
  if (verbose) {
15590
- lines.push("scores your local agent setup — the console's Cave Score (org) scores org traffic;");
15591
- lines.push("the two are different scales and will not match");
15592
- lines.push(`${sessions} sessions scanned${learnSourceLine(plan, sessions).replace(`${sessions} sessions`, "")}`);
16506
+ lines.push("scores your agent setup on this computer. Caveman Cloud's team score measures your team's traffic;");
16507
+ lines.push("the two use different scales and will not match");
16508
+ lines.push(learnSourceLine(plan, sessions));
15593
16509
  }
15594
16510
  else {
15595
- lines.push("local setup · inferred · not billed spend · separate from org Cave Score");
16511
+ lines.push(LEARN_SCORE_SCOPE);
15596
16512
  lines.push(learnSourceLine(plan, sessions));
15597
16513
  }
15598
16514
  const diffText = learnDiffText(options.diff);
15599
16515
  if (diffText)
15600
16516
  lines.push(diffText);
15601
- const spendLines = renderLearnSpendLines(plan.spend, markdown);
16517
+ lines.push(...(verbose ? [] : learnTrendLines(plan.trends)));
16518
+ const spendLines = renderLearnSpendLines(plan.spend, markdown, verbose);
15602
16519
  if (spendLines.length > 0)
15603
16520
  lines.push("", ...spendLines);
15604
16521
  if (confirmedLines.length > 0)
15605
16522
  lines.push("", ...confirmedLines);
15606
16523
  if (verbose) {
16524
+ const trendTable = learnTrendTable(plan.trends, markdown);
16525
+ if (trendTable.length > 0)
16526
+ lines.push("", ...trendTable);
15607
16527
  lines.push("", ...renderLearnDetailedRows(plan, markdown), "", LEARN_DETAILED_NEXT);
15608
16528
  }
15609
16529
  else {
15610
16530
  const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
15611
- lines.push("", "top moves", ...renderLearnSummaryRows(plan));
15612
- if (protectedSink) {
15613
- const title = protectedSink.title.replace(/^Your\s+/i, "");
15614
- lines.push(`protected ${title} · included in score, never auto-fixed${learnMeasuredPrefixSuffix(protectedSink)}`);
15615
- }
15616
- lines.push("", `next: ${invokedAs()} learn implement fix with Claude Code or Codex; asks before every edit`, `details: ${invokedAs()} learn --all ${plan.sinks.length} findings`);
16531
+ lines.push("", "top findings", ...renderLearnSummaryRows(plan));
16532
+ if (protectedSink)
16533
+ lines.push(`needed ${learnProtectedText(protectedSink)}`);
16534
+ const memory = learnMemoryHealthLine(plan);
16535
+ if (memory)
16536
+ lines.push(memory);
16537
+ lines.push("", `next: ${invokedAs()} learn implement fix with Claude Code or Codex; asks before every edit`, `details: ${invokedAs()} learn --all all ${plan.sinks.length} findings`);
15617
16538
  }
15618
16539
  }
15619
16540
  if (options.all === true && (plan.repos?.length ?? 0) > 0) {
15620
- lines.push("", markdown ? "### Per-repo" : "per-repo", ...renderLearnRepos(plan.repos, markdown));
16541
+ lines.push("", markdown ? "### Per repository" : "per repository", ...renderLearnRepos(plan.repos, markdown));
15621
16542
  }
15622
16543
  if (options.all === true) {
15623
16544
  lines.push("", ...(markdown ? ["### Advanced", ...LEARN_ALL_FOOTER.map((line) => `- ${line}`)] : LEARN_ALL_FOOTER));
@@ -15634,9 +16555,9 @@ function learnMeasureValue(value) {
15634
16555
  }
15635
16556
  function learnMeasureUnit(unit) {
15636
16557
  const labels = {
15637
- config_tokens_per_turn: "config tokens/turn",
15638
- turns_over_half_window_pct: "turns over half-window (%)",
15639
- recurrence_present: "recurrence present",
16558
+ config_tokens_per_turn: "setup tokens per message",
16559
+ turns_over_half_window_pct: "% of messages past half the window",
16560
+ recurrence_present: "repeated text still present",
15640
16561
  };
15641
16562
  return labels[unit] ?? unit.replaceAll("_", " ");
15642
16563
  }
@@ -15655,7 +16576,7 @@ function renderLearnConfirmed(confirmed, markdown) {
15655
16576
  const rows = confirmed.flatMap((entry) => {
15656
16577
  const applied = learnAppliedDate(entry.applied_at);
15657
16578
  if (entry.verdict === "insufficient_data") {
15658
- const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more post-fix sessions (${entry.sessions_after} sessions so far)`;
16579
+ const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more sessions after the fix (${entry.sessions_after} so far)`;
15659
16580
  return [markdown ? `- *${line}*` : line];
15660
16581
  }
15661
16582
  if (entry.after === undefined || !Number.isFinite(entry.after))
@@ -15663,17 +16584,17 @@ function renderLearnConfirmed(confirmed, markdown) {
15663
16584
  // How it was measured travels with the number. A confirmed row without its
15664
16585
  // attribution reads as stronger evidence than it is.
15665
16586
  const attribution = entry.attribution
15666
- ? ` · ${entry.attribution.method} (${entry.attribution.confidence}${entry.attribution.provenance === "intact" ? "" : `, ${entry.attribution.provenance}`})`
16587
+ ? ` · ${learnMethodLabel(entry.attribution.method)} (${entry.attribution.confidence}${entry.attribution.provenance === "intact" ? "" : `, ${learnProvenanceLabel(entry.attribution.provenance)}`})`
15667
16588
  : "";
15668
16589
  const line = `${symbols[entry.verdict]} ${entry.sink_id} — ${learnMeasureValue(entry.before)} → ${learnMeasureValue(entry.after)} ${learnMeasureUnit(entry.unit)} over ${entry.sessions_after} sessions (${entry.verdict}) · applied ${applied}${attribution}`;
15669
16590
  return [markdown ? `- ${line}` : line];
15670
16591
  });
15671
16592
  if (rows.length === 0)
15672
16593
  return [];
15673
- return [markdown ? "### Confirmed fixes" : "confirmed fixes", ...rows];
16594
+ return [markdown ? "### Fixes you applied" : "fixes you applied", ...rows];
15674
16595
  }
15675
16596
  function renderLearnRepos(repos, markdown) {
15676
- return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${repo.sessions} sessions · dumbzone ${repo.dumbzone_pct}% · median context ~${humanTokens(repo.median_context)}`);
16597
+ return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${commaCount(repo.sessions)} sessions · ${repo.dumbzone_pct}% of messages past half the window · typical message ~${humanTokens(repo.median_context)} tokens`);
15677
16598
  }
15678
16599
  function readLearnDiff(current) {
15679
16600
  const dir = join(cavemanHome(), "reports");
@@ -15746,7 +16667,7 @@ function proxyExecLearn(proxyArgs, progress) {
15746
16667
  catch (error) {
15747
16668
  const e = error;
15748
16669
  if (e.code === "ETIMEDOUT" || (e.killed && e.code !== "ENOBUFS")) {
15749
- console.error(`learn scan timed out after ${seconds}s — no score computed; re-run with \`caveman learn --json\` to capture the raw scan`);
16670
+ console.error(`learn scan timed out after ${seconds}s, so there is no score; run \`caveman learn --json\` to capture the raw scan`);
15750
16671
  process.exit(1);
15751
16672
  }
15752
16673
  if (e.stderr)
@@ -15796,7 +16717,7 @@ function proxyExecLearnAsync(proxyArgs, onProgress) {
15796
16717
  child.once("close", (code) => {
15797
16718
  clearTimeout(timer);
15798
16719
  if (timedOut) {
15799
- reject(new Error(`learn scan timed out after ${seconds}s — no score computed; re-run with \`caveman learn --json\` to capture the raw scan`));
16720
+ reject(new Error(`learn scan timed out after ${seconds}s, so there is no score; run \`caveman learn --json\` to capture the raw scan`));
15800
16721
  return;
15801
16722
  }
15802
16723
  if (code !== 0) {
@@ -15848,24 +16769,24 @@ function renderLearnApply(raw, dryRun) {
15848
16769
  const candidate = (raw.candidate && typeof raw.candidate === "object" ? raw.candidate : {});
15849
16770
  const klass = String(raw.class ?? candidate.class ?? "");
15850
16771
  if (klass === "behavioral" || klass === "load_bearing") {
15851
- return "behavioral finding — no automatic fix; the caveman-learn skill turns this into a consent-gated nudge\n";
16772
+ return "this is a habit or a needed part of your setup — there is no automatic fix; the caveman-learn skill can turn it into a reminder, with your yes\n";
15852
16773
  }
15853
16774
  const lines = [
15854
16775
  String(candidate.title ?? raw.sink_id ?? "learn candidate"),
15855
- `sink: ${String(raw.sink_id ?? candidate.sink_id ?? "")}`,
16776
+ `id: ${String(raw.sink_id ?? candidate.sink_id ?? "")}`,
15856
16777
  ];
15857
16778
  const locations = candidate.what_to_offload?.locators ?? candidate.evidence?.locators;
15858
16779
  if (locations)
15859
16780
  lines.push(`locations: ${JSON.stringify(locations)}`);
15860
16781
  if (candidate.expected_tokens_per_turn_saved != null) {
15861
- lines.push(`expected: ~${humanTokens(Number(candidate.expected_tokens_per_turn_saved))} tokens/turn`);
16782
+ lines.push(`expected: ~${humanTokens(Number(candidate.expected_tokens_per_turn_saved))} fewer tokens in every message`);
15862
16783
  }
15863
- lines.push("gates: net-token-negative · never-dumber");
16784
+ lines.push("applies only if: it uses fewer tokens overall · and answers don't get worse");
15864
16785
  if (dryRun)
15865
16786
  lines.push("nothing changed — this is a preview");
15866
16787
  else {
15867
16788
  lines.push(`prepared, not applied — ${String(raw.candidate_path ?? join(cavemanHome(), "candidates", `learn-${raw.sink_id}.json`))}`);
15868
- lines.push("the only thing that applies it: caveman tools skills install caveman-learn");
16789
+ lines.push("to apply it, use the caveman-learn skill: caveman tools skills install caveman-learn");
15869
16790
  }
15870
16791
  return `${lines.join("\n")}\n`;
15871
16792
  }
@@ -15879,7 +16800,7 @@ export function renderLearnSavings(raw) {
15879
16800
  const out = [];
15880
16801
  if (rows.length === 0) {
15881
16802
  out.push("no fix recorded yet");
15882
- out.push("apply one through the caveman-learn skill and it lands here with its attribution");
16803
+ out.push("apply one with the caveman-learn skill and it shows up here, with how it was measured");
15883
16804
  for (const caveat of (raw.caveats ?? []))
15884
16805
  out.push(dim(`· ${caveat}`));
15885
16806
  return `${out.join("\n")}\n`;
@@ -15895,8 +16816,8 @@ export function renderLearnSavings(raw) {
15895
16816
  for (const [method, group] of grouped) {
15896
16817
  const total = byRung?.[method];
15897
16818
  const head = total != null && currency
15898
- ? `${method} ${fmtMoney(total, currency)}/day`
15899
- : method;
16819
+ ? `${learnMethodLabel(method)} ${fmtMoney(total, currency)}/day`
16820
+ : learnMethodLabel(method);
15900
16821
  out.push(bold(head));
15901
16822
  for (const row of group) {
15902
16823
  const verdict = String(row.verdict ?? "");
@@ -15906,7 +16827,7 @@ export function renderLearnSavings(raw) {
15906
16827
  : verdict;
15907
16828
  const money = row.saved_usd != null && currency ? ` ${fmtMoney(Number(row.saved_usd), currency)}/day` : "";
15908
16829
  out.push(` ${badge} ${String(row.sink_id ?? "")} ${saved}${money}`);
15909
- out.push(dim(` ${String(row.attribution?.provenance ?? "")} · confidence ${String(row.attribution?.confidence ?? "")}`));
16830
+ out.push(dim(` ${learnProvenanceLabel(String(row.attribution?.provenance ?? ""))} · confidence ${String(row.attribution?.confidence ?? "")}`));
15910
16831
  for (const confounder of (row.attribution?.confounders ?? [])) {
15911
16832
  out.push(dim(` · ${confounder}`));
15912
16833
  }
@@ -15917,6 +16838,27 @@ export function renderLearnSavings(raw) {
15917
16838
  out.push(dim(`· ${caveat}`));
15918
16839
  return `${out.join("\n")}\n`;
15919
16840
  }
16841
+ // Plain names for attribution methods and provenance; the enums stay in JSON.
16842
+ const LEARN_METHOD_LABELS = {
16843
+ deterministic_remeasure: "re-counted the edited file",
16844
+ counterfactual_replay: "replayed past sessions",
16845
+ controlled_holdout: "on/off experiment",
16846
+ interrupted_time_series: "before vs after",
16847
+ unattributed: "not measured yet",
16848
+ };
16849
+ const LEARN_PROVENANCE_LABELS = {
16850
+ intact: "fix still in place",
16851
+ changed_since: "file changed since the fix",
16852
+ target_missing: "file is gone",
16853
+ not_fingerprinted: "can't confirm the fix is still there",
16854
+ not_applicable: "",
16855
+ };
16856
+ function learnMethodLabel(method) {
16857
+ return LEARN_METHOD_LABELS[method] ?? method.replaceAll("_", " ");
16858
+ }
16859
+ function learnProvenanceLabel(provenance) {
16860
+ return LEARN_PROVENANCE_LABELS[provenance] ?? provenance.replaceAll("_", " ");
16861
+ }
15920
16862
  // fmtMoney keeps sub-cent figures legible instead of rounding real spend to
15921
16863
  // $0.00, which reads as "nothing" when it is not.
15922
16864
  export function fmtMoney(value, currency) {
@@ -15924,7 +16866,7 @@ export function fmtMoney(value, currency) {
15924
16866
  if (!Number.isFinite(value))
15925
16867
  return `${symbol}0`;
15926
16868
  if (Math.abs(value) >= 1)
15927
- return `${symbol}${value.toFixed(2)}`;
16869
+ return `${symbol}${value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
15928
16870
  if (Math.abs(value) >= 0.01)
15929
16871
  return `${symbol}${value.toFixed(3)}`;
15930
16872
  return `${symbol}${value.toFixed(5)}`;
@@ -15936,11 +16878,11 @@ export function renderExperimentReport(raw) {
15936
16878
  const arms = Array.isArray(raw.arms) ? raw.arms : [];
15937
16879
  const out = [bold(`experiment ${String(raw.label ?? "")}`)];
15938
16880
  if (raw.sink_id)
15939
- out.push(dim(`sink ${String(raw.sink_id)} · ${String(raw.fix_kind ?? "")}`));
16881
+ out.push(dim(`id ${String(raw.sink_id)} · ${String(raw.fix_kind ?? "")}`));
15940
16882
  for (const arm of arms) {
15941
- out.push(` ${String(arm.arm).padEnd(4)} ${arm.sessions} sessions median ${humanTokens(Number(arm.median_session_tokens ?? 0))} tok/session ${Number(arm.error_turns_per_turn ?? 0).toFixed(2)} err/turn`);
16883
+ out.push(` ${String(arm.arm).padEnd(4)} ${arm.sessions} sessions typical session ${humanTokens(Number(arm.median_session_tokens ?? 0))} tokens ${Number(arm.error_turns_per_turn ?? 0).toFixed(2)} errors per message`);
15942
16884
  }
15943
- const verdict = String(raw.verdict ?? "insufficient_data");
16885
+ const verdict = String(raw.verdict ?? "insufficient_data").replace("insufficient_data", "not enough data yet");
15944
16886
  const badge = verdict === "improved" ? green("✓") : verdict === "regressed" ? red("✗") : yellow("~");
15945
16887
  const delta = raw.median_session_tokens_delta_pct != null
15946
16888
  ? ` ${Number(raw.median_session_tokens_delta_pct) > 0 ? "+" : ""}${Number(raw.median_session_tokens_delta_pct).toFixed(1)}%`
@@ -15950,7 +16892,7 @@ export function renderExperimentReport(raw) {
15950
16892
  : "";
15951
16893
  out.push(` ${badge} ${verdict}${delta}${money}`);
15952
16894
  if (raw.attribution?.method) {
15953
- out.push(dim(` ${String(raw.attribution.method)} · confidence ${String(raw.attribution.confidence ?? "")}`));
16895
+ out.push(dim(` ${learnMethodLabel(String(raw.attribution.method))} · confidence ${String(raw.attribution.confidence ?? "")}`));
15954
16896
  for (const confounder of (raw.attribution.confounders ?? []))
15955
16897
  out.push(dim(` · ${confounder}`));
15956
16898
  }
@@ -15958,36 +16900,83 @@ export function renderExperimentReport(raw) {
15958
16900
  out.push(dim(` · ${caveat}`));
15959
16901
  return `${out.join("\n")}\n`;
15960
16902
  }
16903
+ // renderExperiments prints start/arm/stop (one experiment) or list (many):
16904
+ // label, state, and the arm currently running.
16905
+ export function renderExperiments(raw) {
16906
+ const experiments = Array.isArray(raw) ? raw : [raw];
16907
+ if (experiments.length === 0)
16908
+ return "no experiments yet — start one: caveman learn experiment start <label>\n";
16909
+ return experiments.map((exp) => {
16910
+ const arms = Array.isArray(exp.arms) ? exp.arms : [];
16911
+ const open = arms.find((arm) => !arm.ended_at);
16912
+ const state = exp.stopped_at ? "stopped" : open ? `${String(open.arm)} since ${String(open.started_at)}` : "paused";
16913
+ const sink = exp.sink_id ? dim(` id ${String(exp.sink_id)}${exp.fix_kind ? ` · ${String(exp.fix_kind)}` : ""}`) : "";
16914
+ return `${bold(String(exp.label ?? ""))} ${state} ${arms.length} on/off period${arms.length === 1 ? "" : "s"}${sink}\n`;
16915
+ }).join("");
16916
+ }
16917
+ // renderLearnDigest names the file to inspect; the digest itself is the file.
16918
+ export function renderLearnDigest(raw) {
16919
+ return `digest written: ${String(raw.path ?? "")}\n${dim(String(raw.summary ?? ""))}\ninspect it before sharing; --json prints it\n`;
16920
+ }
16921
+ // renderLearnReconcile prints measured vs billed per model. Coverage is a token
16922
+ // comparison, never a savings claim, so there is no money column.
16923
+ export function renderLearnReconcile(raw) {
16924
+ const rows = Array.isArray(raw.models) ? raw.models : [];
16925
+ const out = [bold(`reconcile ${Number(raw.coverage_pct ?? 0).toFixed(1)}% of billed tokens seen locally`)];
16926
+ for (const row of rows) {
16927
+ out.push(` ${String(row.model ?? "")} billed ${humanTokens(Number(row.billed_tokens ?? 0))} measured ${humanTokens(Number(row.measured_tokens ?? 0))} ${Number(row.coverage_pct ?? 0).toFixed(1)}%`);
16928
+ }
16929
+ out.push(` billed but not seen here ${humanTokens(Number(raw.unattributed_tokens ?? 0))} tokens`);
16930
+ for (const caveat of (raw.caveats ?? []))
16931
+ out.push(dim(` · ${caveat}`));
16932
+ return `${out.join("\n")}\n`;
16933
+ }
15961
16934
  function learnUsage() {
15962
16935
  console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
15963
- default interactive setup score + grouped top moves
15964
- --plain compact text; no animation or keyboard menu
15965
- --all every finding, internal id, basis, and suggestion
15966
- --json|--md machine-readable or detailed Markdown output
16936
+ shows where your agent's tokens go, and what to fix first
16937
+ default interactive Setup Score + top findings
16938
+ --plain short text; no animation or keyboard menu
16939
+ --all every finding, with its id and suggested fix
16940
+ --json|--md output for tools, or a full Markdown report
15967
16941
  implement open Claude Code or Codex to review and fix findings
15968
- apply prepare one finding for consent-gated editing
16942
+ apply prepare one fix; nothing changes without your yes
16943
+ autopilot [status|on|off] refresh the report after sessions end
15969
16944
 
15970
- savings what applied fixes returned, grouped by how it was measured
15971
- experiment prove a change with an on/off holdout over your own sessions
16945
+ savings what fixes you applied saved, grouped by how it was measured
16946
+ experiment test a change by switching it on and off across your own sessions
15972
16947
  start <label> [--sink <id>] · arm <label> on|off · report <label>
15973
16948
  · list · stop <label>
15974
- export privacy-safe digest of findings (identities and magnitudes only)
16949
+ export a privacy-safe summary of findings (names and sizes only)
15975
16950
  reconcile --usage-export <csv>
15976
- compare what was measured against what the provider billed
16951
+ compare what Caveman measured with what your provider billed
15977
16952
 
15978
16953
  advanced:
15979
- applied <sink_id> [--fix-kind <kind>] [--note <text>]
15980
- record an approved, re-measured fix
15981
- simulate <sink_id...>
15982
- sum counterfactual scale over scanned history
16954
+ applied <id> [--fix-kind <kind>] [--note <text>]
16955
+ record a fix you approved, so later runs can measure it
16956
+ simulate <id...>
16957
+ estimate what fixes would have saved over your past sessions
15983
16958
  --repo <substring>
15984
- filter sessions before analysis`);
16959
+ only read sessions from matching repositories`);
16960
+ }
16961
+ // learnAutopilot: status/on/off for the SessionEnd background refresh. `run`
16962
+ // is the detached child the native hook spawns (see learn-autopilot.ts).
16963
+ function learnAutopilot(rest) {
16964
+ const sub = rest[0] ?? "status";
16965
+ if (sub === "run") {
16966
+ process.exitCode = runAutopilot(proxyBin());
16967
+ return;
16968
+ }
16969
+ if (sub === "on" || sub === "off")
16970
+ mutateRawConfig((out) => { out.learnAutopilot = sub === "on"; });
16971
+ else if (sub !== "status")
16972
+ return commandUsage("learn autopilot [status|on|off]");
16973
+ process.stdout.write(autopilotStatusText());
15985
16974
  }
15986
16975
  function learnImplementUsage() {
15987
16976
  console.log(`${invokedAs()} learn implement [claude|codex] [--prompt "<focus>"]
15988
16977
  opens an interactive agent with the current local learn report
15989
16978
  installs the caveman-learn safety guide when missing
15990
- never edits load-bearing findings; asks before every edit`);
16979
+ never edits findings marked needed; asks before every edit`);
15991
16980
  }
15992
16981
  function learnImplementPrompt(focus) {
15993
16982
  const lines = [
@@ -15995,7 +16984,7 @@ function learnImplementPrompt(focus) {
15995
16984
  "Run `caveman learn report --json`; if no current report exists, run `caveman learn --json` once and retry. Then present a short list of actionable findings.",
15996
16985
  "Work through selected fixes one at a time. Never edit load_bearing findings.",
15997
16986
  "Show the proposed diff and before → after token count, ask before every edit, apply only approved changes, then verify the reduction and any recall path.",
15998
- "Keep every local savings claim labeled inferred and never attach currency.",
16987
+ "Keep every local savings claim labeled inferred. Attach currency only where the report itself carries it (the spend block and priced savings rows), with that block's framing: window-bounded, never projected, never verified.",
15999
16988
  ];
16000
16989
  if (focus)
16001
16990
  lines.push(`User focus: ${focus}`);
@@ -16094,20 +17083,20 @@ async function learn(rest) {
16094
17083
  return learnUsage();
16095
17084
  if (sub === "implement")
16096
17085
  return learnImplement(rest.slice(1));
16097
- if (sub === "export" || sub === "reconcile") {
16098
- // Both are inspect-before-you-act surfaces, so they stay machine-readable:
16099
- // the digest is a file the user reads before deciding to share it, and a
16100
- // reconciliation is a table, not a headline.
16101
- process.stdout.write(formatLearnProxyJSON(proxyExecLearn(["learn", ...rest], false)));
16102
- return;
16103
- }
16104
- if (sub === "experiment") {
17086
+ if (sub === "autopilot")
17087
+ return learnAutopilot(rest.slice(1));
17088
+ if (sub === "export" || sub === "reconcile" || sub === "experiment") {
16105
17089
  const rawText = proxyExecLearn(["learn", ...rest], false);
16106
- if (rest.includes("--json") || !["report"].includes(String(rest[1] ?? ""))) {
17090
+ if (rest.includes("--json")) {
16107
17091
  process.stdout.write(formatLearnProxyJSON(rawText));
16108
17092
  return;
16109
17093
  }
16110
- process.stdout.write(renderExperimentReport(JSON.parse(rawText)));
17094
+ const parsed = JSON.parse(rawText);
17095
+ const render = sub === "export" ? renderLearnDigest
17096
+ : sub === "reconcile" ? renderLearnReconcile
17097
+ : rest[1] === "report" ? renderExperimentReport
17098
+ : renderExperiments;
17099
+ process.stdout.write(render(parsed));
16111
17100
  return;
16112
17101
  }
16113
17102
  if (sub === "savings") {
@@ -16149,7 +17138,13 @@ async function learn(rest) {
16149
17138
  if (tui) {
16150
17139
  const learnTui = await import("./learn-tui.js");
16151
17140
  const progress = learnTui.createLearnProgress();
16152
- progress.start("Reading Claude Code and Codex sessions");
17141
+ const flag = (name) => {
17142
+ const at = forwarded.findIndex((arg) => arg === name || arg.startsWith(`${name}=`));
17143
+ if (at < 0)
17144
+ return undefined;
17145
+ return forwarded[at].includes("=") ? forwarded[at].split("=")[1] : forwarded[at + 1];
17146
+ };
17147
+ progress.start(`Reading ${flag("--sources") ?? "local agent"} sessions from the last ${flag("--since") ?? "30d"}`);
16153
17148
  try {
16154
17149
  const scanRaw = await proxyExecLearnAsync(["learn", "scan", "--write-report", "--write-report-token", reportToken, ...forwarded], progress.update);
16155
17150
  // Pre-bundled proxies ignore unknown flags. Fall back once when report
@@ -16931,7 +17926,7 @@ export function renderStatus(view) {
16931
17926
  lines.push(statusRow("plan", `${String(view.plan.plan)} · ${humanTokens(Number(view.plan.used))} of ${humanTokens(Number(view.plan.allowance))} optimized tokens this week · resets Mon 00:00 UTC · connected traffic only`));
16932
17927
  }
16933
17928
  lines.push(statusRow("config", `think: ${view.config_sources.think} · remember: ${view.config_sources.remember} · execute: ${view.config_sources.execute}`));
16934
- lines.push(statusRow("telemetry", `${view.telemetry.state} · anonymous usage ping · change: ${view.telemetry.change}`));
17929
+ lines.push(statusRow("telemetry", `${view.telemetry.state} · usage ping · change: ${view.telemetry.change}`));
16935
17930
  if (view.next)
16936
17931
  lines.push("", `next: ${view.next}`);
16937
17932
  return `${lines.join("\n")}\n`;
@@ -17000,7 +17995,7 @@ async function status(argv) {
17000
17995
  const plan = entitlement && allowance !== null && entitlement.optimized_tokens_week !== undefined
17001
17996
  ? { plan: entitlement.plan, used: entitlement.optimized_tokens_week, allowance }
17002
17997
  : null;
17003
- const telemetry = telemetryState();
17998
+ const telemetry = sessionTelemetryState();
17004
17999
  const view = {
17005
18000
  mode: runningMode ?? resolvedMode,
17006
18001
  mode_source: runningMode ? "running" : "resolved",
@@ -17888,7 +18883,7 @@ function renderRecipe(recipe, baseURL, app) {
17888
18883
  }
17889
18884
  function renderRecipeTemplate(value, baseURL, app) {
17890
18885
  return value
17891
- .replaceAll("{{baseURL}}", baseURL.replace(/\/+$/, ""))
18886
+ .replaceAll("{{baseURL}}", trimTrailingSlashes(baseURL))
17892
18887
  .replaceAll("{{app}}", app);
17893
18888
  }
17894
18889
  function recipeCommentPrefix(lang) {
@@ -18081,12 +19076,11 @@ async function readRawConfig() {
18081
19076
  }
18082
19077
  async function writeRawConfig(out) {
18083
19078
  await mkdir(dirname(configPath()), { recursive: true });
18084
- try {
18085
- chmodSync(configPath(), 0o600);
18086
- }
18087
- catch { /* created below */ }
18088
- await writeFile(configPath(), JSON.stringify(out, null, 2), { mode: 0o600 });
18089
- chmodSync(configPath(), 0o600);
19079
+ const target = configWriteTarget();
19080
+ const tmp = `${target}.${process.pid}.tmp`;
19081
+ await writeFile(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
19082
+ await rename(tmp, target);
19083
+ chmodSync(target, 0o600);
18090
19084
  }
18091
19085
  async function saveConfig(cfg) {
18092
19086
  const out = await readRawConfig();
@@ -18209,6 +19203,7 @@ async function refreshCLIConfig(cfg) {
18209
19203
  try {
18210
19204
  const response = await fetch(`${cfg.baseURL}/api/v1/auth/refresh`, {
18211
19205
  method: "POST",
19206
+ redirect: "manual",
18212
19207
  headers: { "content-type": "application/json", "x-cave-client": "cli" },
18213
19208
  body: JSON.stringify({ refresh_token: cfg.refreshToken }),
18214
19209
  signal: AbortSignal.timeout(5000),