@use-aistack/cli 0.16.4 → 0.16.6

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
@@ -982,10 +982,10 @@ function canonicalize(value, ancestors, arrayElement) {
982
982
  if (prototype !== Object.prototype && prototype !== null) {
983
983
  return unsupportedCanonicalValue(value);
984
984
  }
985
- const object = value;
985
+ const object2 = value;
986
986
  const members = [];
987
- for (const key2 of Object.keys(object).sort(compareCodePoints2)) {
988
- const member = object[key2];
987
+ for (const key2 of Object.keys(object2).sort(compareCodePoints2)) {
988
+ const member = object2[key2];
989
989
  if (member === void 0)
990
990
  continue;
991
991
  members.push(`${JSON.stringify(key2)}:${canonicalize(member, ancestors, false)}`);
@@ -7983,9 +7983,9 @@ function readMessages(db, rootId, budget, failureOutcome, onDiagnostic, signal)
7983
7983
  };
7984
7984
  walk(rootId);
7985
7985
  const toolResults = { byId: /* @__PURE__ */ new Map(), usedIds: /* @__PURE__ */ new Set() };
7986
- for (const { object } of reachableLeaves) {
7986
+ for (const { object: object2 } of reachableLeaves) {
7987
7987
  throwIfAborted4(signal);
7988
- for (const [callId, stored] of extractToolResults(object)) {
7988
+ for (const [callId, stored] of extractToolResults(object2)) {
7989
7989
  toolResults.byId.set(callId, stored);
7990
7990
  }
7991
7991
  }
@@ -7993,8 +7993,8 @@ function readMessages(db, rootId, budget, failureOutcome, onDiagnostic, signal)
7993
7993
  let encounteredUnkeyedToolResult = false;
7994
7994
  for (let traversalOrdinal = 0; traversalOrdinal < reachableLeaves.length; traversalOrdinal++) {
7995
7995
  throwIfAborted4(signal);
7996
- const { hash: hash2, object } = reachableLeaves[traversalOrdinal];
7997
- const leaf = classifyLeaf(object, toolResults);
7996
+ const { hash: hash2, object: object2 } = reachableLeaves[traversalOrdinal];
7997
+ const leaf = classifyLeaf(object2, toolResults);
7998
7998
  rawContentBlockEvidence.push(...leaf.rawContentBlocks);
7999
7999
  if (leaf.kind === "message") {
8000
8000
  messages.push(leaf.message);
@@ -17695,8 +17695,8 @@ function splitOriginalSourceLines(content) {
17695
17695
  const lines2 = content.split("\n");
17696
17696
  return lines2.map((line, index) => index < lines2.length - 1 && line.endsWith("\r") ? line.slice(0, -1) : line);
17697
17697
  }
17698
- function hasOwn(object, key2) {
17699
- return object !== void 0 && Object.prototype.hasOwnProperty.call(object, key2);
17698
+ function hasOwn(object2, key2) {
17699
+ return object2 !== void 0 && Object.prototype.hasOwnProperty.call(object2, key2);
17700
17700
  }
17701
17701
  function unwrapPublicReadContext(value) {
17702
17702
  const issued = publicReadContexts.get(value);
@@ -18891,7 +18891,7 @@ function apiEquivalentCost(modelKey, t, atMs) {
18891
18891
  }
18892
18892
 
18893
18893
  // src/version.ts
18894
- var CLI_VERSION = true ? "0.16.4" : "0.0.0-dev";
18894
+ var CLI_VERSION = true ? "0.16.6" : "0.0.0-dev";
18895
18895
 
18896
18896
  // src/api.ts
18897
18897
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
@@ -18957,7 +18957,10 @@ async function stackCollect(token, data) {
18957
18957
  "Authentication expired. Run `npx @use-aistack/cli login` again."
18958
18958
  );
18959
18959
  if (!res.ok) {
18960
- throw new Error(await formatHttpError(res, "Collect failed"));
18960
+ throw Object.assign(
18961
+ new Error(await formatHttpError(res, "Collect failed")),
18962
+ { status: res.status }
18963
+ );
18961
18964
  }
18962
18965
  return res.json();
18963
18966
  }
@@ -19010,7 +19013,9 @@ async function syncPublish(token, bodyJson) {
19010
19013
  if (res.status === 403 || res.status === 429)
19011
19014
  throw failure("Sync failed", res);
19012
19015
  if (!res.ok) {
19013
- throw new Error(await formatHttpError(res, "Sync failed"));
19016
+ throw Object.assign(new Error(await formatHttpError(res, "Sync failed")), {
19017
+ status: res.status
19018
+ });
19014
19019
  }
19015
19020
  return res.json();
19016
19021
  }
@@ -19027,7 +19032,10 @@ async function fetchDayManifest(baseUrl, token) {
19027
19032
  if (res.status === 403 || res.status === 429)
19028
19033
  throw failure("Manifest fetch failed", res);
19029
19034
  if (!res.ok) {
19030
- throw new Error(await formatHttpError(res, "Manifest fetch failed"));
19035
+ throw Object.assign(
19036
+ new Error(await formatHttpError(res, "Manifest fetch failed")),
19037
+ { status: res.status }
19038
+ );
19031
19039
  }
19032
19040
  const body = await res.json();
19033
19041
  const retentionDays = typeof body.retentionDays === "number" && body.retentionDays > 0 ? body.retentionDays : 400;
@@ -19062,7 +19070,10 @@ async function setAutoSync(token, flag) {
19062
19070
  if (res.status === 403 || res.status === 429)
19063
19071
  throw failure("Auto-sync update failed", res);
19064
19072
  if (!res.ok) {
19065
- throw new Error(await formatHttpError(res, "Auto-sync update failed"));
19073
+ throw Object.assign(
19074
+ new Error(await formatHttpError(res, "Auto-sync update failed")),
19075
+ { status: res.status }
19076
+ );
19066
19077
  }
19067
19078
  return res.json();
19068
19079
  }
@@ -20367,19 +20378,30 @@ import { fileURLToPath } from "node:url";
20367
20378
  import * as p3 from "@clack/prompts";
20368
20379
 
20369
20380
  // src/trace.ts
20381
+ var levelLabels = {
20382
+ info: "INFO ",
20383
+ success: " OK ",
20384
+ warn: "WARN ",
20385
+ error: "ERROR"
20386
+ };
20387
+ var levelColors = { info: bold, success: lime, warn: yellow, error: red };
20370
20388
  var sink = null;
20371
20389
  var startedAtMs = 0;
20372
- var stderrSink = (line) => {
20373
- process.stderr.write(`${line}
20390
+ var clock = () => Date.now();
20391
+ var colored = false;
20392
+ var columns;
20393
+ var stderrSink = (line) => process.stderr.write(`${line}
20374
20394
  `);
20375
- };
20376
20395
  function traceRequestedByEnv(env = process.env) {
20377
20396
  const value = env.AISTACK_DEBUG?.trim().toLowerCase();
20378
20397
  return value === "1" || value === "true" || value === "yes";
20379
20398
  }
20380
- function enableTrace(write = stderrSink, startedAt = Date.now()) {
20399
+ function enableTrace(write = stderrSink, startedAt = Date.now(), options = {}) {
20381
20400
  sink = write;
20401
+ columns = options.columns ?? (process.stderr.isTTY ? process.stderr.columns : void 0);
20402
+ clock = options.now ?? (() => Date.now());
20382
20403
  startedAtMs = startedAt;
20404
+ colored = options.color ?? (Boolean(process.stderr.isTTY) && process.env.NO_COLOR === void 0 && process.env.TERM !== "dumb");
20383
20405
  }
20384
20406
  function traceStartedAt() {
20385
20407
  return startedAtMs;
@@ -20387,22 +20409,95 @@ function traceStartedAt() {
20387
20409
  function traceEnabled() {
20388
20410
  return sink !== null;
20389
20411
  }
20390
- function elapsedLabel() {
20391
- const seconds2 = (Date.now() - startedAtMs) / 1e3;
20392
- return `+${seconds2.toFixed(seconds2 < 10 ? 2 : 1)}s`;
20393
- }
20394
- function trace(message) {
20412
+ function trace(message, level = "info") {
20395
20413
  if (!sink) return;
20396
- sink(`[aistack ${elapsedLabel().padStart(7)}] ${message}`);
20414
+ const seconds2 = Math.max(0, (clock() - startedAtMs) / 1e3);
20415
+ const time = `+${seconds2.toFixed(2)}s`.padStart(10);
20416
+ const prefix = `[aistack ${time}]`;
20417
+ const label = levelLabels[level];
20418
+ const width = columns ? Math.max(16, columns - prefix.length - 7) : void 0;
20419
+ const lines2 = message.split(/\r?\n/).flatMap((line) => {
20420
+ if (!width) return [line];
20421
+ const result = [];
20422
+ let rest = line;
20423
+ while (rest.length > width) {
20424
+ const space = rest.lastIndexOf(" ", width);
20425
+ const cut = space > 0 ? space : width;
20426
+ result.push(rest.slice(0, cut));
20427
+ rest = rest.slice(cut).trimStart();
20428
+ }
20429
+ return [...result, rest];
20430
+ });
20431
+ for (const [index, line] of lines2.entries()) {
20432
+ const head = index === 0 ? `${prefix} ${label} ` : " ".repeat(prefix.length + 7);
20433
+ const styledHead = index === 0 && colored ? `${dim(prefix)} ${levelColors[level](label)} ` : head;
20434
+ sink(
20435
+ `${styledHead}${colored && (level === "error" || level === "warn") ? levelColors[level](line) : line}`
20436
+ );
20437
+ }
20397
20438
  }
20398
20439
  function traceTimer(label) {
20399
20440
  if (!sink) return () => {
20400
20441
  };
20401
- const started = performance.now();
20402
- return (note) => {
20403
- const ms = Math.round(performance.now() - started);
20404
- trace(`${label} \xB7 ${ms} ms${note ? ` \xB7 ${note}` : ""}`);
20405
- };
20442
+ const started = clock();
20443
+ return (note, level = "success") => trace(
20444
+ `${label} \xB7 ${Math.round(clock() - started)} ms${note ? ` \xB7 ${note}` : ""}`,
20445
+ level
20446
+ );
20447
+ }
20448
+ var knownNames = /* @__PURE__ */ new Set([
20449
+ "Error",
20450
+ "TypeError",
20451
+ "RangeError",
20452
+ "SyntaxError",
20453
+ "ReferenceError",
20454
+ "URIError",
20455
+ "EvalError",
20456
+ "AggregateError",
20457
+ "AbortError",
20458
+ "TimeoutError"
20459
+ ]);
20460
+ var object = (value) => value !== null && typeof value === "object" ? value : null;
20461
+ function traceErrorCode(error) {
20462
+ const value = object(error);
20463
+ const code = value?.code;
20464
+ if (typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code))
20465
+ return code;
20466
+ return typeof value?.name === "string" && knownNames.has(value.name) ? value.name : "unknown";
20467
+ }
20468
+ function traceError(operation, error, level = "error") {
20469
+ if (!sink) return;
20470
+ const seen = /* @__PURE__ */ new Set();
20471
+ function describe(value, depth = 0) {
20472
+ if (depth >= 4 || seen.has(value)) return "[cause omitted]";
20473
+ seen.add(value);
20474
+ const row = object(value);
20475
+ const code = traceErrorCode(value);
20476
+ const name = row?.name;
20477
+ const fields = typeof name === "string" && knownNames.has(name) && name !== code ? [name, code] : [code];
20478
+ const details = object(row?.details);
20479
+ if (code === "SOURCE_LIMIT_EXCEEDED" && details) {
20480
+ if (typeof details.bound === "string" && /^(sqlite|jsonl|zip)-[a-z-]{1,32}$/.test(details.bound))
20481
+ fields.push(details.bound);
20482
+ for (const key2 of ["limit", "observedAtLeast"]) {
20483
+ const n = details[key2];
20484
+ if (typeof n === "number" && Number.isSafeInteger(n) && n >= 0)
20485
+ fields.push(`${key2}=${n}`);
20486
+ }
20487
+ }
20488
+ for (const key2 of ["status", "statusCode", "errno", "errcode", "code"]) {
20489
+ const n = row?.[key2];
20490
+ if (typeof n === "number" && Number.isSafeInteger(n))
20491
+ fields.push(`${key2}=${n}`);
20492
+ }
20493
+ if (row?.cause !== void 0)
20494
+ fields.push(`cause: ${describe(row.cause, depth + 1)}`);
20495
+ if (value instanceof AggregateError)
20496
+ for (const child of value.errors.slice(0, 4))
20497
+ fields.push(`cause: ${describe(child, depth + 1)}`);
20498
+ return fields.join(" \xB7 ");
20499
+ }
20500
+ trace(`${operation} failed \xB7 ${describe(error)}`, level);
20406
20501
  }
20407
20502
  function traceEnvironment(facts) {
20408
20503
  trace(
@@ -20954,6 +21049,11 @@ async function loadSyncConfig(opts) {
20954
21049
  }
20955
21050
  });
20956
21051
  if (!res.ok) {
21052
+ traceError(
21053
+ "stack settings fetch",
21054
+ { code: "HTTP_ERROR", status: res.status },
21055
+ "warn"
21056
+ );
20957
21057
  return {
20958
21058
  config: BUNDLED_SYNC_CONFIG,
20959
21059
  source: "bundled",
@@ -20962,6 +21062,11 @@ async function loadSyncConfig(opts) {
20962
21062
  }
20963
21063
  const parsed = readSyncConfig(await res.json());
20964
21064
  if (!parsed) {
21065
+ traceError(
21066
+ "stack settings response",
21067
+ { code: "INVALID_RESPONSE" },
21068
+ "warn"
21069
+ );
20965
21070
  return {
20966
21071
  config: BUNDLED_SYNC_CONFIG,
20967
21072
  source: "bundled",
@@ -20970,6 +21075,7 @@ async function loadSyncConfig(opts) {
20970
21075
  }
20971
21076
  return { config: parsed, source: "fetched" };
20972
21077
  } catch (err) {
21078
+ traceError("stack settings fetch", err, "warn");
20973
21079
  return {
20974
21080
  config: BUNDLED_SYNC_CONFIG,
20975
21081
  source: "bundled",
@@ -23507,7 +23613,9 @@ async function* walkJsonl(dir) {
23507
23613
  let entries;
23508
23614
  try {
23509
23615
  entries = await readdir2(dir, { withFileTypes: true });
23510
- } catch {
23616
+ } catch (error) {
23617
+ if (error?.code !== "ENOENT")
23618
+ traceError("claude transcript discovery", error, "warn");
23511
23619
  return;
23512
23620
  }
23513
23621
  for (const e of entries) {
@@ -23527,7 +23635,9 @@ async function scan(agg, opts = {}) {
23527
23635
  let resolved;
23528
23636
  try {
23529
23637
  resolved = await realpath(file);
23530
- } catch {
23638
+ } catch (error) {
23639
+ if (error?.code !== "ENOENT")
23640
+ traceError("claude transcript path resolution", error, "warn");
23531
23641
  resolved = file;
23532
23642
  }
23533
23643
  if (visited.has(resolved)) {
@@ -23542,7 +23652,9 @@ async function scan(agg, opts = {}) {
23542
23652
  stats.filesSkippedByMtime++;
23543
23653
  continue;
23544
23654
  }
23545
- } catch {
23655
+ } catch (error) {
23656
+ if (error?.code !== "ENOENT")
23657
+ traceError("claude transcript stat", error, "warn");
23546
23658
  }
23547
23659
  }
23548
23660
  const rel = path2.relative(root, file);
@@ -23558,7 +23670,8 @@ async function scan(agg, opts = {}) {
23558
23670
  projectWorkspaces,
23559
23671
  opts.sinceMs
23560
23672
  );
23561
- } catch {
23673
+ } catch (error) {
23674
+ traceError("claude transcript read", error);
23562
23675
  stats.filesUnreadable++;
23563
23676
  stats.filesRead--;
23564
23677
  }
@@ -23570,7 +23683,9 @@ async function exists(p8) {
23570
23683
  try {
23571
23684
  await stat2(p8);
23572
23685
  return true;
23573
- } catch {
23686
+ } catch (error) {
23687
+ if (error?.code !== "ENOENT")
23688
+ traceError("claude source stat", error, "warn");
23574
23689
  return false;
23575
23690
  }
23576
23691
  }
@@ -23586,7 +23701,9 @@ async function ingestFile(agg, file, projectDir, projectWorkspaces, sinceMs) {
23586
23701
  let rec;
23587
23702
  try {
23588
23703
  rec = JSON.parse(line);
23589
- } catch {
23704
+ } catch (error) {
23705
+ if (agg.parseErrors === 0)
23706
+ traceError("claude transcript JSON (first failure)", error, "warn");
23590
23707
  agg.parseErrors++;
23591
23708
  continue;
23592
23709
  }
@@ -23911,7 +24028,9 @@ async function* walkRollouts(dir) {
23911
24028
  let entries;
23912
24029
  try {
23913
24030
  entries = await readdir3(dir, { withFileTypes: true });
23914
- } catch {
24031
+ } catch (error) {
24032
+ if (error?.code !== "ENOENT")
24033
+ traceError("codex rollout discovery", error, "warn");
23915
24034
  return;
23916
24035
  }
23917
24036
  for (const e of entries) {
@@ -23931,7 +24050,9 @@ async function scan2(agg, opts = {}) {
23931
24050
  let resolved;
23932
24051
  try {
23933
24052
  resolved = await realpath2(file);
23934
- } catch {
24053
+ } catch (error) {
24054
+ if (error?.code !== "ENOENT")
24055
+ traceError("codex rollout path resolution", error, "warn");
23935
24056
  resolved = file;
23936
24057
  }
23937
24058
  const dedupKey = resolved.endsWith(".zst") ? resolved.slice(0, -".zst".length) : resolved;
@@ -23947,7 +24068,9 @@ async function scan2(agg, opts = {}) {
23947
24068
  stats.filesSkippedByMtime++;
23948
24069
  continue;
23949
24070
  }
23950
- } catch {
24071
+ } catch (error) {
24072
+ if (error?.code !== "ENOENT")
24073
+ traceError("codex rollout stat", error, "warn");
23951
24074
  }
23952
24075
  }
23953
24076
  agg.files++;
@@ -23977,7 +24100,9 @@ async function exists2(p8) {
23977
24100
  try {
23978
24101
  await stat3(p8);
23979
24102
  return true;
23980
- } catch {
24103
+ } catch (error) {
24104
+ if (error?.code !== "ENOENT")
24105
+ traceError("codex source stat", error, "warn");
23981
24106
  return false;
23982
24107
  }
23983
24108
  }
@@ -23991,10 +24116,12 @@ function ingestWithRetry(agg, file, opts) {
23991
24116
  try {
23992
24117
  return ingestFile2(agg, file, opts);
23993
24118
  } catch (e) {
24119
+ traceError("codex rollout read", e);
23994
24120
  if (errorClass(e) === "ENOENT" && !file.endsWith(".zst")) {
23995
24121
  try {
23996
24122
  return ingestFile2(agg, `${file}.zst`, opts);
23997
24123
  } catch (e2) {
24124
+ traceError("codex compressed rollout retry", e2);
23998
24125
  return { ok: false, reason: errorClass(e2) };
23999
24126
  }
24000
24127
  }
@@ -24003,50 +24130,58 @@ function ingestWithRetry(agg, file, opts) {
24003
24130
  }
24004
24131
  function ingestFile2(agg, file, opts) {
24005
24132
  const readFile4 = opts.readFileImpl ?? readFileSync6;
24006
- let text;
24133
+ const raw = readFile4(file);
24134
+ let bytes = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
24007
24135
  if (file.endsWith(".zst")) {
24008
24136
  if (zstdDecompress === null) throw readError("zstd-unsupported");
24009
- const raw = readFile4(file);
24010
24137
  try {
24011
- text = zstdDecompress(
24012
- Buffer.isBuffer(raw) ? raw : Buffer.from(raw)
24013
- ).toString("utf8");
24014
- } catch {
24138
+ bytes = zstdDecompress(bytes);
24139
+ } catch (error) {
24140
+ traceError("codex zstd decompression", error);
24015
24141
  throw readError("zstd-corrupt");
24016
24142
  }
24017
- } else {
24018
- text = readFile4(file).toString("utf8");
24019
24143
  }
24020
- const records = [];
24021
24144
  let nonEmptyLines = 0;
24022
24145
  let parseErrors = 0;
24023
- for (const line of text.split("\n")) {
24024
- if (!line) continue;
24025
- nonEmptyLines++;
24026
- try {
24027
- records.push(JSON.parse(line));
24028
- } catch {
24029
- parseErrors++;
24146
+ function* records() {
24147
+ for (let start = 0; start < bytes.length; ) {
24148
+ const newline = bytes.indexOf(10, start);
24149
+ const end = newline < 0 ? bytes.length : newline;
24150
+ const line = bytes.subarray(start, end).toString("utf8");
24151
+ start = end + 1;
24152
+ if (!line) continue;
24153
+ nonEmptyLines++;
24154
+ let record;
24155
+ try {
24156
+ record = JSON.parse(line);
24157
+ } catch (error) {
24158
+ if (parseErrors === 0)
24159
+ traceError("codex rollout JSON (first failure)", error, "warn");
24160
+ parseErrors++;
24161
+ continue;
24162
+ }
24163
+ yield record;
24030
24164
  }
24031
24165
  }
24032
- const verdict = classifyRollout(records);
24166
+ const verdict = classifyRollout(records());
24033
24167
  if (!verdict.genuine) return { ok: true, ...verdict };
24034
24168
  agg.lines += nonEmptyLines;
24035
24169
  agg.parseErrors += parseErrors;
24036
24170
  const state = createFileState();
24037
- for (const rec of records) ingestLine(agg, rec, state, opts.sinceMs);
24171
+ for (const rec of records()) ingestLine(agg, rec, state, opts.sinceMs);
24038
24172
  return { ok: true, genuine: true };
24039
24173
  }
24040
24174
  function classifyRollout(records) {
24041
24175
  let originator = null;
24042
24176
  let sawTurnContext = false;
24043
24177
  let sawTokenCount = false;
24044
- let genuine = records.length > 0;
24045
- for (const [i, raw] of records.entries()) {
24178
+ let genuine = true;
24179
+ let count2 = 0;
24180
+ for (const raw of records) {
24046
24181
  const rec = asObj(raw);
24047
24182
  const type = rec ? asStr(rec.type) : null;
24048
24183
  const payload = rec ? asObj(rec.payload) : null;
24049
- if (i === 0 && type !== "session_meta") genuine = false;
24184
+ if (count2++ === 0 && type !== "session_meta") genuine = false;
24050
24185
  if (type === "session_meta" && payload && originator === null) {
24051
24186
  originator = asStr(payload.originator);
24052
24187
  } else if (type === "turn_context") {
@@ -24055,7 +24190,7 @@ function classifyRollout(records) {
24055
24190
  sawTokenCount = true;
24056
24191
  }
24057
24192
  }
24058
- if (sawTokenCount && !sawTurnContext) genuine = false;
24193
+ if (count2 === 0 || sawTokenCount && !sawTurnContext) genuine = false;
24059
24194
  if (genuine) return { genuine: true };
24060
24195
  return { genuine: false, originator: originator ?? "(none)" };
24061
24196
  }
@@ -24068,7 +24203,9 @@ function readConfiguredMcpServers(agg, configFile) {
24068
24203
  if (servers && typeof servers === "object" && !Array.isArray(servers)) {
24069
24204
  names = Object.keys(servers);
24070
24205
  }
24071
- } catch {
24206
+ } catch (error) {
24207
+ if (error?.code !== "ENOENT")
24208
+ traceError("codex MCP configuration", error, "warn");
24072
24209
  return;
24073
24210
  }
24074
24211
  noteConfiguredMcpServers(agg, names);
@@ -24405,13 +24542,24 @@ async function readLocalOffThread(root, before, onProgress) {
24405
24542
  fallback();
24406
24543
  });
24407
24544
  });
24408
- worker.on("error", () => settle(fallback));
24545
+ worker.on(
24546
+ "error",
24547
+ (error) => settle(() => {
24548
+ traceError("cursor worker", error);
24549
+ fallback();
24550
+ })
24551
+ );
24409
24552
  worker.on("exit", (code) => {
24410
- if (code !== 0) settle(fallback);
24553
+ if (code !== 0)
24554
+ settle(() => {
24555
+ trace(`cursor worker exited \xB7 code=${code}; reading inline`, "warn");
24556
+ fallback();
24557
+ });
24411
24558
  });
24412
24559
  });
24413
24560
  }
24414
- async function readLocalOnce(root, before, onProgress) {
24561
+ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24562
+ before ??= await sourceStamp(root);
24415
24563
  const stats = emptyScanStats();
24416
24564
  const out = { sessions: [], complete: true, stats };
24417
24565
  if (!await hasLocalSource(root)) {
@@ -24421,17 +24569,19 @@ async function readLocalOnce(root, before, onProgress) {
24421
24569
  trace(`cursor \xB7 global database ${await globalDbSize(root)}`);
24422
24570
  const readDone = traceTimer("cursor history read");
24423
24571
  let context;
24572
+ let retrySmallPage = false;
24424
24573
  try {
24425
24574
  const reader = await Promise.resolve().then(() => (init_lib(), lib_exports));
24426
24575
  const options = {
24427
24576
  dataPath: root,
24428
24577
  sqliteDriver: "node:sqlite",
24429
- onDiagnostic: () => {
24578
+ onDiagnostic: (diagnostic) => {
24579
+ traceError("cursor source diagnostic", diagnostic, "warn");
24430
24580
  out.complete = false;
24431
24581
  },
24432
24582
  signal: AbortSignal.timeout(12e4)
24433
24583
  };
24434
- context = reader.createSessionReadContext(options);
24584
+ context = reader.createSessionReadContext({ ...options, sourceReadLimits });
24435
24585
  const config = { ...options, readContext: context };
24436
24586
  let offset = 0;
24437
24587
  while (true) {
@@ -24448,17 +24598,28 @@ async function readLocalOnce(root, before, onProgress) {
24448
24598
  for (const summary of page.data) {
24449
24599
  stats.filesFound++;
24450
24600
  if (summary.resolutionState === "ambiguous") {
24601
+ trace(
24602
+ "cursor session resolution incomplete \xB7 ambiguous source",
24603
+ "warn"
24604
+ );
24451
24605
  out.complete = false;
24452
24606
  }
24453
24607
  try {
24454
24608
  const session = await reader.getSession(summary.id, config);
24455
- if (session.resolutionState !== "complete" || session.messages.some((m) => m.metadata?.corrupted))
24609
+ if (session.resolutionState !== "complete" || session.messages.some((m) => m.metadata?.corrupted)) {
24610
+ trace(
24611
+ "cursor session incomplete \xB7 unresolved or corrupted messages",
24612
+ "warn"
24613
+ );
24456
24614
  out.complete = false;
24615
+ }
24457
24616
  const tokens = await readTokenEvidence(root, session);
24458
24617
  out.sessions.push({ session, tokens });
24459
24618
  stats.filesRead++;
24460
24619
  onProgress?.(stats.filesRead, page.pagination.total);
24461
- } catch {
24620
+ } catch (error) {
24621
+ if (isPageByteLimit(error)) throw error;
24622
+ traceError("cursor history", error);
24462
24623
  out.complete = false;
24463
24624
  stats.filesUnreadable++;
24464
24625
  } finally {
@@ -24467,24 +24628,52 @@ async function readLocalOnce(root, before, onProgress) {
24467
24628
  }
24468
24629
  if (!page.pagination.hasMore) break;
24469
24630
  if (page.data.length === 0 || offset >= 1e5) {
24631
+ trace(
24632
+ "cursor listing incomplete \xB7 empty page or pagination limit",
24633
+ "warn"
24634
+ );
24470
24635
  out.complete = false;
24471
24636
  break;
24472
24637
  }
24473
24638
  offset += page.data.length;
24474
24639
  }
24475
- } catch {
24640
+ } catch (error) {
24641
+ traceError("cursor history", error);
24642
+ retrySmallPage = isPageByteLimit(error) && sourceReadLimits?.sqlitePageRows !== 1;
24643
+ stats.unreadableFiles.push({
24644
+ path: "history",
24645
+ reason: traceErrorCode(error)
24646
+ });
24476
24647
  out.complete = false;
24477
24648
  stats.filesUnreadable++;
24478
24649
  } finally {
24479
24650
  try {
24480
24651
  await context?.dispose();
24481
- } catch {
24652
+ } catch (error) {
24653
+ traceError("cursor reader disposal", error);
24482
24654
  out.complete = false;
24483
24655
  }
24484
24656
  }
24485
- if (before !== await sourceStamp(root)) out.complete = false;
24657
+ if (retrySmallPage) {
24658
+ readDone(
24659
+ "page byte limit reached; retrying with one SQLite row per page",
24660
+ "warn"
24661
+ );
24662
+ return readLocalOnce(root, before, onProgress, {
24663
+ ...sourceReadLimits,
24664
+ sqlitePageRows: 1
24665
+ });
24666
+ }
24667
+ if (before !== await sourceStamp(root)) {
24668
+ trace(
24669
+ "cursor history incomplete \xB7 database changed during the read",
24670
+ "warn"
24671
+ );
24672
+ out.complete = false;
24673
+ }
24486
24674
  readDone(
24487
- `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`
24675
+ `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`,
24676
+ out.complete ? "success" : "warn"
24488
24677
  );
24489
24678
  return out;
24490
24679
  }
@@ -24496,6 +24685,10 @@ async function globalDbSize(root) {
24496
24685
  return "absent";
24497
24686
  }
24498
24687
  }
24688
+ function isPageByteLimit(error) {
24689
+ const details = asObj(asObj(error)?.details);
24690
+ return traceErrorCode(error) === "SOURCE_LIMIT_EXCEEDED" && details?.sourceKind === "sqlite" && details.bound === "sqlite-page-bytes";
24691
+ }
24499
24692
 
24500
24693
  // src/harness/cursor/account.ts
24501
24694
  var digest = (value) => createHash6("sha256").update(value).digest("hex");
@@ -24518,7 +24711,8 @@ async function existingAccount(root) {
24518
24711
  const user = subject.split("|").at(-1);
24519
24712
  if (!user) return null;
24520
24713
  return { scope: digest(subject), cookie: `${user}%3A%3A${token}` };
24521
- } catch {
24714
+ } catch (error) {
24715
+ traceError("cursor account lookup", error, "warn");
24522
24716
  return null;
24523
24717
  } finally {
24524
24718
  db?.close();
@@ -24526,12 +24720,18 @@ async function existingAccount(root) {
24526
24720
  }
24527
24721
  function apiContribution(value) {
24528
24722
  const raw = asObj(value);
24529
- if (!raw) throw new Error("Invalid Cursor event");
24723
+ if (!raw)
24724
+ throw Object.assign(new Error("Invalid Cursor event"), {
24725
+ code: "CURSOR_INVALID_EVENT"
24726
+ });
24530
24727
  const session = asStr(raw.conversationId);
24531
24728
  if (!session || raw.cloudAgentId || session.startsWith("bc-")) return null;
24532
24729
  const tsMs = timestamp(raw.timestamp);
24533
24730
  const usage = raw.tokenUsage == null ? {} : asObj(raw.tokenUsage);
24534
- if (tsMs === null || !usage) throw new Error("Invalid Cursor event");
24731
+ if (tsMs === null || !usage)
24732
+ throw Object.assign(new Error("Invalid Cursor event"), {
24733
+ code: "CURSOR_INVALID_EVENT"
24734
+ });
24535
24735
  const buckets = {};
24536
24736
  for (const [key2, field] of [
24537
24737
  ["input", "inputTokens"],
@@ -24541,7 +24741,10 @@ function apiContribution(value) {
24541
24741
  ]) {
24542
24742
  if (usage[field] === void 0 || usage[field] === null) continue;
24543
24743
  const value2 = count(usage[field]);
24544
- if (value2 === void 0) throw new Error("Invalid Cursor token bucket");
24744
+ if (value2 === void 0)
24745
+ throw Object.assign(new Error("Invalid Cursor token bucket"), {
24746
+ code: "CURSOR_INVALID_TOKEN_BUCKET"
24747
+ });
24545
24748
  buckets[key2] = value2;
24546
24749
  }
24547
24750
  const id = asStr(raw.id) ?? asStr(raw.eventId);
@@ -24581,20 +24784,30 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24581
24784
  })
24582
24785
  }
24583
24786
  );
24584
- if (!response.ok) throw new Error("Cursor usage unavailable");
24787
+ if (!response.ok)
24788
+ throw Object.assign(new Error("Cursor usage unavailable"), {
24789
+ status: response.status
24790
+ });
24585
24791
  const payload = asObj(await response.json());
24586
24792
  const events = payload?.usageEventsDisplay;
24587
24793
  if (!Array.isArray(events) || events.length > pageSize)
24588
- throw new Error("Invalid Cursor page");
24794
+ throw Object.assign(new Error("Invalid Cursor page"), {
24795
+ code: "CURSOR_INVALID_PAGE"
24796
+ });
24589
24797
  if (payload?.totalUsageEventsCount !== void 0) {
24590
24798
  const reported = count(payload.totalUsageEventsCount);
24591
24799
  if (reported === void 0 || !Number.isInteger(reported) || total !== void 0 && total !== reported)
24592
- throw new Error("Cursor page count changed");
24800
+ throw Object.assign(new Error("Cursor page count changed"), {
24801
+ code: "CURSOR_PAGE_COUNT_CHANGED"
24802
+ });
24593
24803
  total = reported;
24594
24804
  }
24595
24805
  if (events.length) {
24596
24806
  const key2 = digest(JSON.stringify(events));
24597
- if (pages.has(key2)) throw new Error("Repeated Cursor page");
24807
+ if (pages.has(key2))
24808
+ throw Object.assign(new Error("Repeated Cursor page"), {
24809
+ code: "CURSOR_REPEATED_PAGE"
24810
+ });
24598
24811
  pages.add(key2);
24599
24812
  }
24600
24813
  retrieved += events.length;
@@ -24602,18 +24815,27 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24602
24815
  const event = apiContribution(value);
24603
24816
  if (!event) continue;
24604
24817
  if (event.tsMs < from || event.tsMs >= to)
24605
- throw new Error("Cursor event outside query");
24818
+ throw Object.assign(new Error("Cursor event outside query"), {
24819
+ code: "CURSOR_EVENT_OUTSIDE_QUERY"
24820
+ });
24606
24821
  if (event.id && eventIds.has(event.id)) continue;
24607
24822
  if (event.id) eventIds.add(event.id);
24608
24823
  out.push(event);
24609
24824
  }
24610
24825
  if (total !== void 0 && retrieved > total)
24611
- throw new Error("Invalid Cursor page count");
24826
+ throw Object.assign(new Error("Invalid Cursor page count"), {
24827
+ code: "CURSOR_INVALID_PAGE_COUNT"
24828
+ });
24612
24829
  if (total !== void 0 && retrieved === total || total === void 0 && events.length < pageSize)
24613
24830
  return out;
24614
- if (!events.length) throw new Error("Incomplete Cursor pages");
24831
+ if (!events.length)
24832
+ throw Object.assign(new Error("Incomplete Cursor pages"), {
24833
+ code: "CURSOR_INCOMPLETE_PAGES"
24834
+ });
24615
24835
  }
24616
- throw new Error("Cursor page limit");
24836
+ throw Object.assign(new Error("Cursor page limit"), {
24837
+ code: "CURSOR_PAGE_LIMIT"
24838
+ });
24617
24839
  }
24618
24840
 
24619
24841
  // src/harness/cursor/cache.ts
@@ -24643,14 +24865,20 @@ async function loadCache(file) {
24643
24865
  const raw = asObj(JSON.parse(await readFile(file, "utf8")));
24644
24866
  const windows = asObj(raw?.windows);
24645
24867
  if (raw?.version !== 1 || !(raw.account === null || typeof raw.account === "string") || !Array.isArray(raw.sessions) || !raw.sessions.every((id) => typeof id === "string") || !Array.isArray(raw.local) || !raw.local.every(validContribution) || !windows)
24646
- throw new Error("Invalid cache");
24868
+ throw Object.assign(new Error("Invalid cache"), {
24869
+ code: "CURSOR_INVALID_CACHE"
24870
+ });
24647
24871
  for (const value of Object.values(windows)) {
24648
24872
  const w = asObj(value);
24649
24873
  if (!w || timestamp(w.from) === null || timestamp(w.to) === null || timestamp(w.fetchedAt) === null || !Array.isArray(w.events) || !w.events.every(validContribution))
24650
- throw new Error("Invalid window");
24874
+ throw Object.assign(new Error("Invalid window"), {
24875
+ code: "CURSOR_INVALID_WINDOW"
24876
+ });
24651
24877
  }
24652
24878
  return { value: raw, complete: true };
24653
24879
  } catch (error) {
24880
+ if (error.code !== "ENOENT")
24881
+ traceError("cursor cache read", error);
24654
24882
  return {
24655
24883
  value: emptyCache(),
24656
24884
  complete: error.code === "ENOENT"
@@ -24682,7 +24910,8 @@ async function refreshAccount(input) {
24682
24910
  const events = (await fetchWindow(account, from, to, input.fetchImpl)).filter((e) => sessionIds.has(e.session));
24683
24911
  if (previous?.events.length && events.length === 0 && to <= now) continue;
24684
24912
  next.windows[key2] = { from, to, fetchedAt: now, events };
24685
- } catch {
24913
+ } catch (error) {
24914
+ traceError("cursor account enrichment", error, "warn");
24686
24915
  break;
24687
24916
  }
24688
24917
  }
@@ -24854,8 +25083,13 @@ async function scan3(options) {
24854
25083
  if ([
24855
25084
  ...loaded.value.local,
24856
25085
  ...Object.values(loaded.value.windows).flatMap((w) => w.events)
24857
- ].some((row) => row.tsMs >= options.sinceMs && !ids.has(row.session)))
25086
+ ].some((row) => row.tsMs >= options.sinceMs && !ids.has(row.session))) {
25087
+ trace(
25088
+ "cursor history incomplete \xB7 previously dated source is missing or no longer dated",
25089
+ "warn"
25090
+ );
24858
25091
  complete = false;
25092
+ }
24859
25093
  const account = await (options.accountImpl ?? existingAccount)(root);
24860
25094
  const cache = await refreshAccount({
24861
25095
  cache: loaded.value,
@@ -24876,8 +25110,13 @@ async function scan3(options) {
24876
25110
  const dated = new Set(contributions.map((row) => row.session));
24877
25111
  if (loaded.value.local.some(
24878
25112
  (row) => row.tsMs >= options.sinceMs && !dated.has(row.session)
24879
- ))
25113
+ )) {
25114
+ trace(
25115
+ "cursor history incomplete \xB7 previously dated source is missing or no longer dated",
25116
+ "warn"
25117
+ );
24880
25118
  complete = false;
25119
+ }
24881
25120
  const previousDates = /* @__PURE__ */ new Map();
24882
25121
  for (const row of [
24883
25122
  ...loaded.value.local,
@@ -24892,7 +25131,8 @@ async function scan3(options) {
24892
25131
  cache.sessions = [...ids].sort();
24893
25132
  try {
24894
25133
  await saveCache(file, cache);
24895
- } catch {
25134
+ } catch (error) {
25135
+ traceError("cursor cache save", error);
24896
25136
  complete = false;
24897
25137
  }
24898
25138
  }
@@ -25319,11 +25559,15 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
25319
25559
  }
25320
25560
  const raw2 = await optionalRead(path8.join(cacheDir, file));
25321
25561
  if (raw2 && !raw2.endsWith("\n"))
25322
- throw new Error("Incomplete Grok context cache");
25562
+ throw Object.assign(new Error("Incomplete Grok context cache"), {
25563
+ code: "GROK_INCOMPLETE_CONTEXT_CACHE"
25564
+ });
25323
25565
  for (const line of raw2.split("\n").filter(Boolean)) {
25324
25566
  const call = asObj(JSON.parse(line));
25325
25567
  if (!call || typeof call.id !== "string" || !/^[a-f0-9]{64}$/.test(call.id) || typeof call.session !== "string" || typeof call.tsMs !== "number" || !Number.isFinite(call.tsMs) || typeof call.tokens !== "number" || !Number.isSafeInteger(call.tokens) || call.tokens < 0)
25326
- throw new Error("Invalid Grok context cache");
25568
+ throw Object.assign(new Error("Invalid Grok context cache"), {
25569
+ code: "GROK_INVALID_CONTEXT_CACHE"
25570
+ });
25327
25571
  if (call.tsMs >= cutoff && call.tsMs <= now)
25328
25572
  calls.set(call.id, {
25329
25573
  id: call.id,
@@ -25395,7 +25639,9 @@ async function stableRead(file, jsonl) {
25395
25639
  if (!line.trim()) continue;
25396
25640
  try {
25397
25641
  lines2.push(JSON.parse(line));
25398
- } catch {
25642
+ } catch (error) {
25643
+ if (!lines2.includes(null))
25644
+ traceError("grok evidence JSON (first failure)", error, "warn");
25399
25645
  lines2.push(null);
25400
25646
  }
25401
25647
  }
@@ -25408,9 +25654,11 @@ async function stableRead(file, jsonl) {
25408
25654
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
25409
25655
  return { json: JSON.parse(raw), complete: true };
25410
25656
  }
25411
- } catch {
25657
+ } catch (error) {
25658
+ traceError("grok evidence read (will retry)", error, "warn");
25412
25659
  }
25413
25660
  }
25661
+ trace("grok evidence incomplete \xB7 retries exhausted", "error");
25414
25662
  return { complete: false };
25415
25663
  }
25416
25664
  async function directories(root) {
@@ -25429,6 +25677,8 @@ async function directories(root) {
25429
25677
  }
25430
25678
  return out.sort();
25431
25679
  } catch (error) {
25680
+ if (error.code !== "ENOENT")
25681
+ traceError("grok session discovery", error);
25432
25682
  return error.code === "ENOENT" ? [] : null;
25433
25683
  }
25434
25684
  }
@@ -25469,7 +25719,8 @@ async function scan4(agg, opts = {}) {
25469
25719
  let entries;
25470
25720
  try {
25471
25721
  entries = await readdir5(dir, { withFileTypes: true });
25472
- } catch {
25722
+ } catch (error) {
25723
+ traceError("grok session listing", error);
25473
25724
  complete = false;
25474
25725
  continue;
25475
25726
  }
@@ -25610,7 +25861,8 @@ async function scan4(agg, opts = {}) {
25610
25861
  dates.add(new Date(call.tsMs).toISOString().slice(0, 10));
25611
25862
  sessionDates.set(call.session, dates);
25612
25863
  }
25613
- } catch {
25864
+ } catch (error) {
25865
+ traceError("grok retained context", error);
25614
25866
  complete = false;
25615
25867
  stats.filesUnreadable++;
25616
25868
  }
@@ -25859,7 +26111,9 @@ async function dbFilesIn(root) {
25859
26111
  try {
25860
26112
  const entries = await readdir6(root, { withFileTypes: true });
25861
26113
  return entries.filter((e) => e.isFile() && isStoreFile(e.name)).map((e) => path10.join(root, e.name)).sort();
25862
- } catch {
26114
+ } catch (error) {
26115
+ if (error?.code !== "ENOENT")
26116
+ traceError("opencode database discovery", error, "warn");
25863
26117
  return [];
25864
26118
  }
25865
26119
  }
@@ -25868,7 +26122,9 @@ async function loadSqlite() {
25868
26122
  const mod = await import("node:sqlite");
25869
26123
  if (typeof mod.DatabaseSync !== "function") return null;
25870
26124
  return (file) => new mod.DatabaseSync(file, { readOnly: true });
25871
- } catch {
26125
+ } catch (error) {
26126
+ if (error?.code !== "ENOENT")
26127
+ traceError("opencode SQLite initialization", error, "warn");
25872
26128
  return null;
25873
26129
  }
25874
26130
  }
@@ -25893,6 +26149,7 @@ async function scan5(agg, opts = {}) {
25893
26149
  readDb(agg, state, open3, file, sinceMs);
25894
26150
  stats.filesRead++;
25895
26151
  } catch (e) {
26152
+ traceError("opencode database read", e);
25896
26153
  stats.filesUnreadable++;
25897
26154
  stats.unreadableFiles.push({
25898
26155
  path: path10.basename(file),
@@ -25908,7 +26165,9 @@ function checkMigrationCeiling(db) {
25908
26165
  let newest;
25909
26166
  try {
25910
26167
  newest = db.prepare("select max(id) as id from migration").get()?.id;
25911
- } catch {
26168
+ } catch (error) {
26169
+ if (error?.code !== "ENOENT")
26170
+ traceError("opencode database close", error, "warn");
25912
26171
  throw readError2("schema-unversioned");
25913
26172
  }
25914
26173
  const prefix = Number.parseInt(String(newest ?? ""), 10);
@@ -26043,12 +26302,15 @@ function readDb(agg, state, open3, file, sinceMs) {
26043
26302
  messageId: r.message_id
26044
26303
  });
26045
26304
  }
26046
- } catch {
26305
+ } catch (error) {
26306
+ traceError("opencode v2 content", error, "warn");
26047
26307
  }
26048
26308
  } finally {
26049
26309
  try {
26050
26310
  db.close();
26051
- } catch {
26311
+ } catch (error) {
26312
+ if (error?.code !== "ENOENT")
26313
+ traceError("opencode MCP configuration", error, "warn");
26052
26314
  }
26053
26315
  }
26054
26316
  }
@@ -26073,7 +26335,9 @@ function readConfiguredMcpServers2(agg, state, configFile) {
26073
26335
  if (mcp && typeof mcp === "object" && !Array.isArray(mcp)) {
26074
26336
  noteConfiguredMcpServers2(agg, state, Object.keys(mcp));
26075
26337
  }
26076
- } catch {
26338
+ } catch (error) {
26339
+ if (error?.code !== "ENOENT")
26340
+ traceError("opencode detection database close", error, "warn");
26077
26341
  return;
26078
26342
  }
26079
26343
  }
@@ -26124,11 +26388,14 @@ async function detectOpencode(opts) {
26124
26388
  `select 1 as hit from ${table} where time_created >= ? limit 1`
26125
26389
  ).get(opts.sinceMs) !== void 0;
26126
26390
  if (probe("message") || probe("session_message")) return true;
26127
- } catch {
26391
+ } catch (error) {
26392
+ traceError("opencode detection", error, "warn");
26128
26393
  } finally {
26129
26394
  try {
26130
26395
  db?.close();
26131
- } catch {
26396
+ } catch (error) {
26397
+ if (error?.code !== "ENOENT")
26398
+ traceError("opencode source stat", error, "warn");
26132
26399
  }
26133
26400
  }
26134
26401
  }
@@ -26139,7 +26406,9 @@ async function exists4(p8) {
26139
26406
  try {
26140
26407
  await stat6(p8);
26141
26408
  return true;
26142
- } catch {
26409
+ } catch (error) {
26410
+ if (error?.code !== "ENOENT")
26411
+ traceError("opencode source discovery or metadata", error, "warn");
26143
26412
  return false;
26144
26413
  }
26145
26414
  }
@@ -26385,7 +26654,9 @@ async function* walkSessions(dir) {
26385
26654
  let entries;
26386
26655
  try {
26387
26656
  entries = await readdir7(dir, { withFileTypes: true });
26388
- } catch {
26657
+ } catch (error) {
26658
+ if (error?.code !== "ENOENT")
26659
+ traceError("pi transcript discovery", error, "warn");
26389
26660
  return;
26390
26661
  }
26391
26662
  for (const e of entries) {
@@ -26405,7 +26676,9 @@ async function scan6(agg, opts = {}) {
26405
26676
  let resolved;
26406
26677
  try {
26407
26678
  resolved = await realpath3(file);
26408
- } catch {
26679
+ } catch (error) {
26680
+ if (error?.code !== "ENOENT")
26681
+ traceError("pi transcript path resolution", error, "warn");
26409
26682
  resolved = file;
26410
26683
  }
26411
26684
  if (visited.has(resolved)) {
@@ -26420,7 +26693,9 @@ async function scan6(agg, opts = {}) {
26420
26693
  stats.filesSkippedByMtime++;
26421
26694
  continue;
26422
26695
  }
26423
- } catch {
26696
+ } catch (error) {
26697
+ if (error?.code !== "ENOENT")
26698
+ traceError("pi transcript stat", error, "warn");
26424
26699
  }
26425
26700
  }
26426
26701
  agg.files++;
@@ -26441,7 +26716,8 @@ async function scan6(agg, opts = {}) {
26441
26716
  reason: "version-too-new"
26442
26717
  });
26443
26718
  }
26444
- } catch {
26719
+ } catch (error) {
26720
+ traceError("pi transcript read", error);
26445
26721
  stats.filesUnreadable++;
26446
26722
  stats.filesRead--;
26447
26723
  stats.unreadableFiles.push({
@@ -26457,7 +26733,9 @@ async function exists5(p8) {
26457
26733
  try {
26458
26734
  await stat7(p8);
26459
26735
  return true;
26460
- } catch {
26736
+ } catch (error) {
26737
+ if (error?.code !== "ENOENT")
26738
+ traceError("pi source stat", error, "warn");
26461
26739
  return false;
26462
26740
  }
26463
26741
  }
@@ -26475,7 +26753,9 @@ async function ingestFile3(agg, fold, file, sinceMs) {
26475
26753
  let entry;
26476
26754
  try {
26477
26755
  entry = JSON.parse(line);
26478
- } catch {
26756
+ } catch (error) {
26757
+ if (agg.parseErrors === 0)
26758
+ traceError("pi transcript JSON (first failure)", error, "warn");
26479
26759
  agg.parseErrors++;
26480
26760
  continue;
26481
26761
  }
@@ -27748,7 +28028,12 @@ var defaultRunner = (cwd, args) => {
27748
28028
  stdio: ["ignore", "pipe", "ignore"],
27749
28029
  maxBuffer: 64 * 1024 * 1024
27750
28030
  });
27751
- } catch {
28031
+ } catch (error) {
28032
+ traceError(
28033
+ args[0] === "log" ? "git history" : "git repository discovery",
28034
+ error,
28035
+ "warn"
28036
+ );
27752
28037
  return null;
27753
28038
  }
27754
28039
  };
@@ -27761,7 +28046,15 @@ var defaultAsyncRunner = (cwd, args) => new Promise((resolve3) => {
27761
28046
  encoding: "utf8",
27762
28047
  maxBuffer: 64 * 1024 * 1024
27763
28048
  },
27764
- (error, stdout) => resolve3(error ? null : stdout)
28049
+ (error, stdout) => {
28050
+ if (error)
28051
+ traceError(
28052
+ args[0] === "log" ? "git history" : "git repository discovery",
28053
+ error,
28054
+ "warn"
28055
+ );
28056
+ resolve3(error ? null : stdout);
28057
+ }
27765
28058
  );
27766
28059
  });
27767
28060
  var emptyGitDay = () => ({
@@ -28572,6 +28865,11 @@ function buildGateSummary(ctx) {
28572
28865
  out.push("", DIVIDER, "", "ALSO PUBLISHING");
28573
28866
  if (body.measuredDays) {
28574
28867
  out.push(...daysBlock(body.measuredDays, ctx.days));
28868
+ } else if (ctx.incompleteDayScan) {
28869
+ out.push(
28870
+ "days not published: a historical scan was incomplete",
28871
+ " Model breakdown and daily statistics will not update."
28872
+ );
28575
28873
  }
28576
28874
  const workflowDays = (body.measuredDays?.days ?? []).flatMap(
28577
28875
  (d) => d.workflow ? [d.workflow] : []
@@ -28637,9 +28935,12 @@ async function stageSync(deps) {
28637
28935
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
28638
28936
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
28639
28937
  const emit2 = (event) => deps.onEvent?.(event);
28640
- const step = (id, label, state, note) => {
28938
+ const step = (id, label, state, note, level) => {
28641
28939
  if (state !== "waiting")
28642
- trace(`${label} \xB7 ${state}${note ? ` \xB7 ${note}` : ""}`);
28940
+ trace(
28941
+ `${label} \xB7 ${state}${note ? ` \xB7 ${note}` : ""}`,
28942
+ level ?? (state === "failed" ? "error" : state === "done" ? "success" : state === "skipped" ? "warn" : "info")
28943
+ );
28643
28944
  emit2({ kind: "step", id, label, state, ...note ? { note } : {} });
28644
28945
  };
28645
28946
  let prices = {
@@ -28664,9 +28965,10 @@ async function stageSync(deps) {
28664
28965
  step("prices", "Prices", "done", "bundled table");
28665
28966
  }
28666
28967
  } catch (error) {
28968
+ traceError("price table fetch", error, "warn");
28667
28969
  setActivePricer(null);
28668
- done(`fetch failed (${describeError(error)}), bundled table`);
28669
- step("prices", "Prices", "done", "unreachable, bundled table");
28970
+ done("fetch failed, bundled table", "warn");
28971
+ step("prices", "Prices", "done", "unreachable, bundled table", "warn");
28670
28972
  }
28671
28973
  };
28672
28974
  const readSettings = async () => {
@@ -28705,8 +29007,15 @@ async function stageSync(deps) {
28705
29007
  );
28706
29008
  return manifest2;
28707
29009
  } catch (error) {
28708
- done(`fetch failed (${describeError(error)}), whole window goes`);
28709
- step("manifest", "Synced days", "done", "unreachable, whole window");
29010
+ traceError("day manifest fetch", error, "warn");
29011
+ done("fetch failed, whole window goes", "warn");
29012
+ step(
29013
+ "manifest",
29014
+ "Synced days",
29015
+ "done",
29016
+ "unreachable, whole window",
29017
+ "warn"
29018
+ );
28710
29019
  return null;
28711
29020
  }
28712
29021
  };
@@ -28768,7 +29077,10 @@ async function stageSync(deps) {
28768
29077
  publishWorkflow: false,
28769
29078
  onProgress: progress("recent usage")
28770
29079
  });
28771
- scanDone2(describeScan(reading.recent.stats));
29080
+ scanDone2(
29081
+ describeScan(reading.recent.stats),
29082
+ reading.recent.stats.filesUnreadable ? "warn" : "success"
29083
+ );
28772
29084
  }
28773
29085
  step(id, label, "running", "history");
28774
29086
  const scanDone = traceTimer(`scan ${adapter.name} (historical)`);
@@ -28778,14 +29090,16 @@ async function stageSync(deps) {
28778
29090
  onProgress: progress("history")
28779
29091
  });
28780
29092
  scanDone(
28781
- `${describeScan(reading.history.stats)}${reading.history.scanComplete === false ? ", incomplete" : ""}`
29093
+ `${describeScan(reading.history.stats)}${reading.history.scanComplete === false ? ", incomplete" : ""}`,
29094
+ reading.history.scanComplete === false || reading.history.stats.filesUnreadable > 0 ? "warn" : "success"
28782
29095
  );
28783
29096
  const files = Math.max(seen, reading.history.stats.filesRead);
28784
29097
  step(
28785
29098
  id,
28786
29099
  label,
28787
29100
  "done",
28788
- `${files} ${files === 1 ? "file" : "files"} \xB7 ${elapsed()}`
29101
+ `${files} ${files === 1 ? "file" : "files"} \xB7 ${elapsed()}`,
29102
+ reading.history.scanComplete === false || reading.history.stats.filesUnreadable > 0 ? "warn" : "success"
28789
29103
  );
28790
29104
  return reading;
28791
29105
  }
@@ -28909,7 +29223,8 @@ async function stageSync(deps) {
28909
29223
  step("review", "Review", "running");
28910
29224
  const bodyJson = JSON.stringify(body);
28911
29225
  trace(
28912
- `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (a scan was incomplete, no day rows go)"}`
29226
+ `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (a scan was incomplete, no day rows go)"}`,
29227
+ dayScansComplete ? "success" : "warn"
28913
29228
  );
28914
29229
  trace(`body \xB7 ${bodyJson.length} bytes, ${built.length} harness payloads`);
28915
29230
  step("review", "Review", "done", `${days.send.length} days to send`);
@@ -28921,6 +29236,7 @@ async function stageSync(deps) {
28921
29236
  source,
28922
29237
  baseUrl: deps.baseUrl,
28923
29238
  scanStats,
29239
+ incompleteDayScan: !dayScansComplete,
28924
29240
  days,
28925
29241
  prices,
28926
29242
  // The real terminal, so the inventory rows break where this window ends
@@ -28951,12 +29267,6 @@ async function stageSync(deps) {
28951
29267
  ...acknowledgePublish ? { acknowledgePublish } : {}
28952
29268
  };
28953
29269
  }
28954
- function describeError(error) {
28955
- if (error instanceof Error) {
28956
- return error.name === "TimeoutError" ? "timed out" : error.message;
28957
- }
28958
- return String(error);
28959
- }
28960
29270
  function describeScan(stats) {
28961
29271
  return `${stats.filesRead}/${stats.filesFound} files read, ${stats.filesUnreadable} unreadable`;
28962
29272
  }
@@ -29062,6 +29372,7 @@ async function runAutoSync(deps) {
29062
29372
  }
29063
29373
  }
29064
29374
  } catch (e) {
29375
+ traceError("auto-sync", e);
29065
29376
  failure2 = e instanceof Error ? e.message : String(e);
29066
29377
  }
29067
29378
  if (revoked) {
@@ -29224,14 +29535,14 @@ function fit(line, width) {
29224
29535
  function createBoard(opts) {
29225
29536
  const rows = /* @__PURE__ */ new Map();
29226
29537
  const now = opts.now ?? (() => Date.now());
29227
- const columns = opts.columns ?? (() => process.stdout.columns ?? 80);
29538
+ const columns2 = opts.columns ?? (() => process.stdout.columns ?? 80);
29228
29539
  let painted = 0;
29229
29540
  let frame = 0;
29230
29541
  let stopped = false;
29231
29542
  const paint = () => {
29232
29543
  const lines2 = renderRows([...rows.values()], {
29233
29544
  now: now(),
29234
- width: columns(),
29545
+ width: columns2(),
29235
29546
  frame
29236
29547
  });
29237
29548
  frame++;
@@ -29253,7 +29564,7 @@ function createBoard(opts) {
29253
29564
  if (opts.interactive) paint();
29254
29565
  else
29255
29566
  opts.write(
29256
- `${renderRows([...rows.values()], { now: now(), width: columns(), frame: 0 }).join("\n")}
29567
+ `${renderRows([...rows.values()], { now: now(), width: columns2(), frame: 0 }).join("\n")}
29257
29568
  `
29258
29569
  );
29259
29570
  }
@@ -29376,6 +29687,7 @@ async function syncCommand(options = {}) {
29376
29687
  onEvent: board.handle
29377
29688
  });
29378
29689
  } catch (e) {
29690
+ traceError("sync scan", e);
29379
29691
  board.stop();
29380
29692
  outroError(e instanceof Error ? e.message : String(e));
29381
29693
  process.exitCode = 1;
@@ -29435,6 +29747,7 @@ async function syncCommand(options = {}) {
29435
29747
  if (!asked) await offerConnectUpsell();
29436
29748
  outro2("done");
29437
29749
  } catch (e) {
29750
+ traceError("sync publish", e);
29438
29751
  s.stop("Publish failed");
29439
29752
  outroError(e instanceof Error ? e.message : String(e));
29440
29753
  process.exitCode = 1;
@@ -29547,6 +29860,7 @@ function createSyncServer(deps, send) {
29547
29860
  try {
29548
29861
  staged = await stage({ baseUrl: deps.baseUrl, now });
29549
29862
  } catch (e) {
29863
+ traceError("sync server request", e);
29550
29864
  staged = null;
29551
29865
  const message = e instanceof Error ? e.message : String(e);
29552
29866
  return ok(id, textResult(`Preview failed: ${message}`, true));
@@ -29732,6 +30046,7 @@ function runStdioSyncServer(deps) {
29732
30046
  try {
29733
30047
  server.handle(JSON.parse(line));
29734
30048
  } catch (e) {
30049
+ traceError("sync server request", e);
29735
30050
  deps.log?.(`parse error: ${String(e)}`);
29736
30051
  }
29737
30052
  }