@use-aistack/cli 0.16.4 → 0.16.7

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.7" : "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",
@@ -22557,6 +22663,7 @@ function buildSyncBody(built, syncConfig, autoSync, trigger = "manual", measured
22557
22663
  measuredDays: {
22558
22664
  aggregateVersion: MEASURED_DAYS_V1,
22559
22665
  utcOffsetMinutes: measuredDays.utcOffsetMinutes,
22666
+ ...measuredDays.partial ? { partial: true } : {},
22560
22667
  days: applyDayConsent(measuredDays.days, syncConfig)
22561
22668
  }
22562
22669
  } : base;
@@ -23507,7 +23614,9 @@ async function* walkJsonl(dir) {
23507
23614
  let entries;
23508
23615
  try {
23509
23616
  entries = await readdir2(dir, { withFileTypes: true });
23510
- } catch {
23617
+ } catch (error) {
23618
+ if (error?.code !== "ENOENT")
23619
+ traceError("claude transcript discovery", error, "warn");
23511
23620
  return;
23512
23621
  }
23513
23622
  for (const e of entries) {
@@ -23527,7 +23636,9 @@ async function scan(agg, opts = {}) {
23527
23636
  let resolved;
23528
23637
  try {
23529
23638
  resolved = await realpath(file);
23530
- } catch {
23639
+ } catch (error) {
23640
+ if (error?.code !== "ENOENT")
23641
+ traceError("claude transcript path resolution", error, "warn");
23531
23642
  resolved = file;
23532
23643
  }
23533
23644
  if (visited.has(resolved)) {
@@ -23542,7 +23653,9 @@ async function scan(agg, opts = {}) {
23542
23653
  stats.filesSkippedByMtime++;
23543
23654
  continue;
23544
23655
  }
23545
- } catch {
23656
+ } catch (error) {
23657
+ if (error?.code !== "ENOENT")
23658
+ traceError("claude transcript stat", error, "warn");
23546
23659
  }
23547
23660
  }
23548
23661
  const rel = path2.relative(root, file);
@@ -23558,7 +23671,8 @@ async function scan(agg, opts = {}) {
23558
23671
  projectWorkspaces,
23559
23672
  opts.sinceMs
23560
23673
  );
23561
- } catch {
23674
+ } catch (error) {
23675
+ traceError("claude transcript read", error);
23562
23676
  stats.filesUnreadable++;
23563
23677
  stats.filesRead--;
23564
23678
  }
@@ -23570,7 +23684,9 @@ async function exists(p8) {
23570
23684
  try {
23571
23685
  await stat2(p8);
23572
23686
  return true;
23573
- } catch {
23687
+ } catch (error) {
23688
+ if (error?.code !== "ENOENT")
23689
+ traceError("claude source stat", error, "warn");
23574
23690
  return false;
23575
23691
  }
23576
23692
  }
@@ -23586,7 +23702,9 @@ async function ingestFile(agg, file, projectDir, projectWorkspaces, sinceMs) {
23586
23702
  let rec;
23587
23703
  try {
23588
23704
  rec = JSON.parse(line);
23589
- } catch {
23705
+ } catch (error) {
23706
+ if (agg.parseErrors === 0)
23707
+ traceError("claude transcript JSON (first failure)", error, "warn");
23590
23708
  agg.parseErrors++;
23591
23709
  continue;
23592
23710
  }
@@ -23911,7 +24029,9 @@ async function* walkRollouts(dir) {
23911
24029
  let entries;
23912
24030
  try {
23913
24031
  entries = await readdir3(dir, { withFileTypes: true });
23914
- } catch {
24032
+ } catch (error) {
24033
+ if (error?.code !== "ENOENT")
24034
+ traceError("codex rollout discovery", error, "warn");
23915
24035
  return;
23916
24036
  }
23917
24037
  for (const e of entries) {
@@ -23931,7 +24051,9 @@ async function scan2(agg, opts = {}) {
23931
24051
  let resolved;
23932
24052
  try {
23933
24053
  resolved = await realpath2(file);
23934
- } catch {
24054
+ } catch (error) {
24055
+ if (error?.code !== "ENOENT")
24056
+ traceError("codex rollout path resolution", error, "warn");
23935
24057
  resolved = file;
23936
24058
  }
23937
24059
  const dedupKey = resolved.endsWith(".zst") ? resolved.slice(0, -".zst".length) : resolved;
@@ -23947,7 +24069,9 @@ async function scan2(agg, opts = {}) {
23947
24069
  stats.filesSkippedByMtime++;
23948
24070
  continue;
23949
24071
  }
23950
- } catch {
24072
+ } catch (error) {
24073
+ if (error?.code !== "ENOENT")
24074
+ traceError("codex rollout stat", error, "warn");
23951
24075
  }
23952
24076
  }
23953
24077
  agg.files++;
@@ -23977,7 +24101,9 @@ async function exists2(p8) {
23977
24101
  try {
23978
24102
  await stat3(p8);
23979
24103
  return true;
23980
- } catch {
24104
+ } catch (error) {
24105
+ if (error?.code !== "ENOENT")
24106
+ traceError("codex source stat", error, "warn");
23981
24107
  return false;
23982
24108
  }
23983
24109
  }
@@ -23991,10 +24117,12 @@ function ingestWithRetry(agg, file, opts) {
23991
24117
  try {
23992
24118
  return ingestFile2(agg, file, opts);
23993
24119
  } catch (e) {
24120
+ traceError("codex rollout read", e);
23994
24121
  if (errorClass(e) === "ENOENT" && !file.endsWith(".zst")) {
23995
24122
  try {
23996
24123
  return ingestFile2(agg, `${file}.zst`, opts);
23997
24124
  } catch (e2) {
24125
+ traceError("codex compressed rollout retry", e2);
23998
24126
  return { ok: false, reason: errorClass(e2) };
23999
24127
  }
24000
24128
  }
@@ -24003,50 +24131,58 @@ function ingestWithRetry(agg, file, opts) {
24003
24131
  }
24004
24132
  function ingestFile2(agg, file, opts) {
24005
24133
  const readFile4 = opts.readFileImpl ?? readFileSync6;
24006
- let text;
24134
+ const raw = readFile4(file);
24135
+ let bytes = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
24007
24136
  if (file.endsWith(".zst")) {
24008
24137
  if (zstdDecompress === null) throw readError("zstd-unsupported");
24009
- const raw = readFile4(file);
24010
24138
  try {
24011
- text = zstdDecompress(
24012
- Buffer.isBuffer(raw) ? raw : Buffer.from(raw)
24013
- ).toString("utf8");
24014
- } catch {
24139
+ bytes = zstdDecompress(bytes);
24140
+ } catch (error) {
24141
+ traceError("codex zstd decompression", error);
24015
24142
  throw readError("zstd-corrupt");
24016
24143
  }
24017
- } else {
24018
- text = readFile4(file).toString("utf8");
24019
24144
  }
24020
- const records = [];
24021
24145
  let nonEmptyLines = 0;
24022
24146
  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++;
24147
+ function* records() {
24148
+ for (let start = 0; start < bytes.length; ) {
24149
+ const newline = bytes.indexOf(10, start);
24150
+ const end = newline < 0 ? bytes.length : newline;
24151
+ const line = bytes.subarray(start, end).toString("utf8");
24152
+ start = end + 1;
24153
+ if (!line) continue;
24154
+ nonEmptyLines++;
24155
+ let record;
24156
+ try {
24157
+ record = JSON.parse(line);
24158
+ } catch (error) {
24159
+ if (parseErrors === 0)
24160
+ traceError("codex rollout JSON (first failure)", error, "warn");
24161
+ parseErrors++;
24162
+ continue;
24163
+ }
24164
+ yield record;
24030
24165
  }
24031
24166
  }
24032
- const verdict = classifyRollout(records);
24167
+ const verdict = classifyRollout(records());
24033
24168
  if (!verdict.genuine) return { ok: true, ...verdict };
24034
24169
  agg.lines += nonEmptyLines;
24035
24170
  agg.parseErrors += parseErrors;
24036
24171
  const state = createFileState();
24037
- for (const rec of records) ingestLine(agg, rec, state, opts.sinceMs);
24172
+ for (const rec of records()) ingestLine(agg, rec, state, opts.sinceMs);
24038
24173
  return { ok: true, genuine: true };
24039
24174
  }
24040
24175
  function classifyRollout(records) {
24041
24176
  let originator = null;
24042
24177
  let sawTurnContext = false;
24043
24178
  let sawTokenCount = false;
24044
- let genuine = records.length > 0;
24045
- for (const [i, raw] of records.entries()) {
24179
+ let genuine = true;
24180
+ let count2 = 0;
24181
+ for (const raw of records) {
24046
24182
  const rec = asObj(raw);
24047
24183
  const type = rec ? asStr(rec.type) : null;
24048
24184
  const payload = rec ? asObj(rec.payload) : null;
24049
- if (i === 0 && type !== "session_meta") genuine = false;
24185
+ if (count2++ === 0 && type !== "session_meta") genuine = false;
24050
24186
  if (type === "session_meta" && payload && originator === null) {
24051
24187
  originator = asStr(payload.originator);
24052
24188
  } else if (type === "turn_context") {
@@ -24055,7 +24191,7 @@ function classifyRollout(records) {
24055
24191
  sawTokenCount = true;
24056
24192
  }
24057
24193
  }
24058
- if (sawTokenCount && !sawTurnContext) genuine = false;
24194
+ if (count2 === 0 || sawTokenCount && !sawTurnContext) genuine = false;
24059
24195
  if (genuine) return { genuine: true };
24060
24196
  return { genuine: false, originator: originator ?? "(none)" };
24061
24197
  }
@@ -24068,7 +24204,9 @@ function readConfiguredMcpServers(agg, configFile) {
24068
24204
  if (servers && typeof servers === "object" && !Array.isArray(servers)) {
24069
24205
  names = Object.keys(servers);
24070
24206
  }
24071
- } catch {
24207
+ } catch (error) {
24208
+ if (error?.code !== "ENOENT")
24209
+ traceError("codex MCP configuration", error, "warn");
24072
24210
  return;
24073
24211
  }
24074
24212
  noteConfiguredMcpServers(agg, names);
@@ -24405,13 +24543,24 @@ async function readLocalOffThread(root, before, onProgress) {
24405
24543
  fallback();
24406
24544
  });
24407
24545
  });
24408
- worker.on("error", () => settle(fallback));
24546
+ worker.on(
24547
+ "error",
24548
+ (error) => settle(() => {
24549
+ traceError("cursor worker", error);
24550
+ fallback();
24551
+ })
24552
+ );
24409
24553
  worker.on("exit", (code) => {
24410
- if (code !== 0) settle(fallback);
24554
+ if (code !== 0)
24555
+ settle(() => {
24556
+ trace(`cursor worker exited \xB7 code=${code}; reading inline`, "warn");
24557
+ fallback();
24558
+ });
24411
24559
  });
24412
24560
  });
24413
24561
  }
24414
- async function readLocalOnce(root, before, onProgress) {
24562
+ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24563
+ before ??= await sourceStamp(root);
24415
24564
  const stats = emptyScanStats();
24416
24565
  const out = { sessions: [], complete: true, stats };
24417
24566
  if (!await hasLocalSource(root)) {
@@ -24421,17 +24570,22 @@ async function readLocalOnce(root, before, onProgress) {
24421
24570
  trace(`cursor \xB7 global database ${await globalDbSize(root)}`);
24422
24571
  const readDone = traceTimer("cursor history read");
24423
24572
  let context;
24573
+ let retrySmallPage = false;
24574
+ let unresolved = 0;
24575
+ let corrupted = 0;
24576
+ let ambiguous = 0;
24424
24577
  try {
24425
24578
  const reader = await Promise.resolve().then(() => (init_lib(), lib_exports));
24426
24579
  const options = {
24427
24580
  dataPath: root,
24428
24581
  sqliteDriver: "node:sqlite",
24429
- onDiagnostic: () => {
24582
+ onDiagnostic: (diagnostic) => {
24583
+ traceError("cursor source diagnostic", diagnostic, "warn");
24430
24584
  out.complete = false;
24431
24585
  },
24432
24586
  signal: AbortSignal.timeout(12e4)
24433
24587
  };
24434
- context = reader.createSessionReadContext(options);
24588
+ context = reader.createSessionReadContext({ ...options, sourceReadLimits });
24435
24589
  const config = { ...options, readContext: context };
24436
24590
  let offset = 0;
24437
24591
  while (true) {
@@ -24452,13 +24606,20 @@ async function readLocalOnce(root, before, onProgress) {
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
+ if (session.resolutionState !== "complete") unresolved++;
24611
+ if (session.messages.some((m) => m.metadata?.corrupted))
24612
+ corrupted++;
24456
24613
  out.complete = false;
24614
+ }
24457
24615
  const tokens = await readTokenEvidence(root, session);
24458
24616
  out.sessions.push({ session, tokens });
24459
24617
  stats.filesRead++;
24460
24618
  onProgress?.(stats.filesRead, page.pagination.total);
24461
- } catch {
24619
+ } catch (error) {
24620
+ if (isPageByteLimit(error)) throw error;
24621
+ if (traceErrorCode(error) === "SESSION_AMBIGUOUS") ambiguous++;
24622
+ else traceError("cursor session skipped", error, "warn");
24462
24623
  out.complete = false;
24463
24624
  stats.filesUnreadable++;
24464
24625
  } finally {
@@ -24467,24 +24628,58 @@ 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
+ }
24674
+ if (unresolved || corrupted || ambiguous) {
24675
+ trace(
24676
+ `cursor partial history \xB7 ${unresolved} sessions unresolved, ${corrupted} with corrupted messages, ${ambiguous} skipped with conflicting copies${ambiguous ? " (SESSION_AMBIGUOUS)" : ""} \xB7 available dated usage retained`,
24677
+ "warn"
24678
+ );
24679
+ }
24486
24680
  readDone(
24487
- `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`
24681
+ `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`,
24682
+ out.complete ? "success" : "warn"
24488
24683
  );
24489
24684
  return out;
24490
24685
  }
@@ -24496,6 +24691,10 @@ async function globalDbSize(root) {
24496
24691
  return "absent";
24497
24692
  }
24498
24693
  }
24694
+ function isPageByteLimit(error) {
24695
+ const details = asObj(asObj(error)?.details);
24696
+ return traceErrorCode(error) === "SOURCE_LIMIT_EXCEEDED" && details?.sourceKind === "sqlite" && details.bound === "sqlite-page-bytes";
24697
+ }
24499
24698
 
24500
24699
  // src/harness/cursor/account.ts
24501
24700
  var digest = (value) => createHash6("sha256").update(value).digest("hex");
@@ -24518,7 +24717,8 @@ async function existingAccount(root) {
24518
24717
  const user = subject.split("|").at(-1);
24519
24718
  if (!user) return null;
24520
24719
  return { scope: digest(subject), cookie: `${user}%3A%3A${token}` };
24521
- } catch {
24720
+ } catch (error) {
24721
+ traceError("cursor account lookup", error, "warn");
24522
24722
  return null;
24523
24723
  } finally {
24524
24724
  db?.close();
@@ -24526,12 +24726,18 @@ async function existingAccount(root) {
24526
24726
  }
24527
24727
  function apiContribution(value) {
24528
24728
  const raw = asObj(value);
24529
- if (!raw) throw new Error("Invalid Cursor event");
24729
+ if (!raw)
24730
+ throw Object.assign(new Error("Invalid Cursor event"), {
24731
+ code: "CURSOR_INVALID_EVENT"
24732
+ });
24530
24733
  const session = asStr(raw.conversationId);
24531
24734
  if (!session || raw.cloudAgentId || session.startsWith("bc-")) return null;
24532
24735
  const tsMs = timestamp(raw.timestamp);
24533
24736
  const usage = raw.tokenUsage == null ? {} : asObj(raw.tokenUsage);
24534
- if (tsMs === null || !usage) throw new Error("Invalid Cursor event");
24737
+ if (tsMs === null || !usage)
24738
+ throw Object.assign(new Error("Invalid Cursor event"), {
24739
+ code: "CURSOR_INVALID_EVENT"
24740
+ });
24535
24741
  const buckets = {};
24536
24742
  for (const [key2, field] of [
24537
24743
  ["input", "inputTokens"],
@@ -24541,7 +24747,10 @@ function apiContribution(value) {
24541
24747
  ]) {
24542
24748
  if (usage[field] === void 0 || usage[field] === null) continue;
24543
24749
  const value2 = count(usage[field]);
24544
- if (value2 === void 0) throw new Error("Invalid Cursor token bucket");
24750
+ if (value2 === void 0)
24751
+ throw Object.assign(new Error("Invalid Cursor token bucket"), {
24752
+ code: "CURSOR_INVALID_TOKEN_BUCKET"
24753
+ });
24545
24754
  buckets[key2] = value2;
24546
24755
  }
24547
24756
  const id = asStr(raw.id) ?? asStr(raw.eventId);
@@ -24581,20 +24790,34 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24581
24790
  })
24582
24791
  }
24583
24792
  );
24584
- if (!response.ok) throw new Error("Cursor usage unavailable");
24793
+ if (!response.ok)
24794
+ throw Object.assign(new Error("Cursor usage unavailable"), {
24795
+ status: response.status
24796
+ });
24585
24797
  const payload = asObj(await response.json());
24586
24798
  const events = payload?.usageEventsDisplay;
24587
- if (!Array.isArray(events) || events.length > pageSize)
24588
- throw new Error("Invalid Cursor page");
24799
+ if (!Array.isArray(events))
24800
+ throw Object.assign(new Error("Invalid Cursor page"), {
24801
+ code: "CURSOR_INVALID_PAGE_SHAPE"
24802
+ });
24803
+ if (events.length > pageSize)
24804
+ throw Object.assign(new Error("Cursor page exceeds requested size"), {
24805
+ code: "CURSOR_PAGE_TOO_LARGE"
24806
+ });
24589
24807
  if (payload?.totalUsageEventsCount !== void 0) {
24590
24808
  const reported = count(payload.totalUsageEventsCount);
24591
24809
  if (reported === void 0 || !Number.isInteger(reported) || total !== void 0 && total !== reported)
24592
- throw new Error("Cursor page count changed");
24810
+ throw Object.assign(new Error("Cursor page count changed"), {
24811
+ code: "CURSOR_PAGE_COUNT_CHANGED"
24812
+ });
24593
24813
  total = reported;
24594
24814
  }
24595
24815
  if (events.length) {
24596
24816
  const key2 = digest(JSON.stringify(events));
24597
- if (pages.has(key2)) throw new Error("Repeated Cursor page");
24817
+ if (pages.has(key2))
24818
+ throw Object.assign(new Error("Repeated Cursor page"), {
24819
+ code: "CURSOR_REPEATED_PAGE"
24820
+ });
24598
24821
  pages.add(key2);
24599
24822
  }
24600
24823
  retrieved += events.length;
@@ -24602,18 +24825,27 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24602
24825
  const event = apiContribution(value);
24603
24826
  if (!event) continue;
24604
24827
  if (event.tsMs < from || event.tsMs >= to)
24605
- throw new Error("Cursor event outside query");
24828
+ throw Object.assign(new Error("Cursor event outside query"), {
24829
+ code: "CURSOR_EVENT_OUTSIDE_QUERY"
24830
+ });
24606
24831
  if (event.id && eventIds.has(event.id)) continue;
24607
24832
  if (event.id) eventIds.add(event.id);
24608
24833
  out.push(event);
24609
24834
  }
24610
24835
  if (total !== void 0 && retrieved > total)
24611
- throw new Error("Invalid Cursor page count");
24836
+ throw Object.assign(new Error("Invalid Cursor page count"), {
24837
+ code: "CURSOR_INVALID_PAGE_COUNT"
24838
+ });
24612
24839
  if (total !== void 0 && retrieved === total || total === void 0 && events.length < pageSize)
24613
24840
  return out;
24614
- if (!events.length) throw new Error("Incomplete Cursor pages");
24841
+ if (!events.length)
24842
+ throw Object.assign(new Error("Incomplete Cursor pages"), {
24843
+ code: "CURSOR_INCOMPLETE_PAGES"
24844
+ });
24615
24845
  }
24616
- throw new Error("Cursor page limit");
24846
+ throw Object.assign(new Error("Cursor page limit"), {
24847
+ code: "CURSOR_PAGE_LIMIT"
24848
+ });
24617
24849
  }
24618
24850
 
24619
24851
  // src/harness/cursor/cache.ts
@@ -24643,14 +24875,20 @@ async function loadCache(file) {
24643
24875
  const raw = asObj(JSON.parse(await readFile(file, "utf8")));
24644
24876
  const windows = asObj(raw?.windows);
24645
24877
  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");
24878
+ throw Object.assign(new Error("Invalid cache"), {
24879
+ code: "CURSOR_INVALID_CACHE"
24880
+ });
24647
24881
  for (const value of Object.values(windows)) {
24648
24882
  const w = asObj(value);
24649
24883
  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");
24884
+ throw Object.assign(new Error("Invalid window"), {
24885
+ code: "CURSOR_INVALID_WINDOW"
24886
+ });
24651
24887
  }
24652
24888
  return { value: raw, complete: true };
24653
24889
  } catch (error) {
24890
+ if (error.code !== "ENOENT")
24891
+ traceError("cursor cache read", error);
24654
24892
  return {
24655
24893
  value: emptyCache(),
24656
24894
  complete: error.code === "ENOENT"
@@ -24682,7 +24920,12 @@ async function refreshAccount(input) {
24682
24920
  const events = (await fetchWindow(account, from, to, input.fetchImpl)).filter((e) => sessionIds.has(e.session));
24683
24921
  if (previous?.events.length && events.length === 0 && to <= now) continue;
24684
24922
  next.windows[key2] = { from, to, fetchedAt: now, events };
24685
- } catch {
24923
+ } catch (error) {
24924
+ traceError(
24925
+ "cursor account usage refresh (using local and previously cached usage)",
24926
+ error,
24927
+ "warn"
24928
+ );
24686
24929
  break;
24687
24930
  }
24688
24931
  }
@@ -24854,8 +25097,13 @@ async function scan3(options) {
24854
25097
  if ([
24855
25098
  ...loaded.value.local,
24856
25099
  ...Object.values(loaded.value.windows).flatMap((w) => w.events)
24857
- ].some((row) => row.tsMs >= options.sinceMs && !ids.has(row.session)))
25100
+ ].some((row) => row.tsMs >= options.sinceMs && !ids.has(row.session))) {
25101
+ trace(
25102
+ "cursor history incomplete \xB7 previously dated source is missing or no longer dated",
25103
+ "warn"
25104
+ );
24858
25105
  complete = false;
25106
+ }
24859
25107
  const account = await (options.accountImpl ?? existingAccount)(root);
24860
25108
  const cache = await refreshAccount({
24861
25109
  cache: loaded.value,
@@ -24876,8 +25124,13 @@ async function scan3(options) {
24876
25124
  const dated = new Set(contributions.map((row) => row.session));
24877
25125
  if (loaded.value.local.some(
24878
25126
  (row) => row.tsMs >= options.sinceMs && !dated.has(row.session)
24879
- ))
25127
+ )) {
25128
+ trace(
25129
+ "cursor history incomplete \xB7 previously dated source is missing or no longer dated",
25130
+ "warn"
25131
+ );
24880
25132
  complete = false;
25133
+ }
24881
25134
  const previousDates = /* @__PURE__ */ new Map();
24882
25135
  for (const row of [
24883
25136
  ...loaded.value.local,
@@ -24892,7 +25145,8 @@ async function scan3(options) {
24892
25145
  cache.sessions = [...ids].sort();
24893
25146
  try {
24894
25147
  await saveCache(file, cache);
24895
- } catch {
25148
+ } catch (error) {
25149
+ traceError("cursor cache save", error);
24896
25150
  complete = false;
24897
25151
  }
24898
25152
  }
@@ -25319,11 +25573,15 @@ async function retainedContextCalls(root, sessions, cacheDir = contextCacheDirec
25319
25573
  }
25320
25574
  const raw2 = await optionalRead(path8.join(cacheDir, file));
25321
25575
  if (raw2 && !raw2.endsWith("\n"))
25322
- throw new Error("Incomplete Grok context cache");
25576
+ throw Object.assign(new Error("Incomplete Grok context cache"), {
25577
+ code: "GROK_INCOMPLETE_CONTEXT_CACHE"
25578
+ });
25323
25579
  for (const line of raw2.split("\n").filter(Boolean)) {
25324
25580
  const call = asObj(JSON.parse(line));
25325
25581
  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");
25582
+ throw Object.assign(new Error("Invalid Grok context cache"), {
25583
+ code: "GROK_INVALID_CONTEXT_CACHE"
25584
+ });
25327
25585
  if (call.tsMs >= cutoff && call.tsMs <= now)
25328
25586
  calls.set(call.id, {
25329
25587
  id: call.id,
@@ -25395,7 +25653,9 @@ async function stableRead(file, jsonl) {
25395
25653
  if (!line.trim()) continue;
25396
25654
  try {
25397
25655
  lines2.push(JSON.parse(line));
25398
- } catch {
25656
+ } catch (error) {
25657
+ if (!lines2.includes(null))
25658
+ traceError("grok evidence JSON (first failure)", error, "warn");
25399
25659
  lines2.push(null);
25400
25660
  }
25401
25661
  }
@@ -25408,9 +25668,11 @@ async function stableRead(file, jsonl) {
25408
25668
  if (before.size === after.size && before.mtimeMs === after.mtimeMs)
25409
25669
  return { json: JSON.parse(raw), complete: true };
25410
25670
  }
25411
- } catch {
25671
+ } catch (error) {
25672
+ traceError("grok evidence read (will retry)", error, "warn");
25412
25673
  }
25413
25674
  }
25675
+ trace("grok evidence incomplete \xB7 retries exhausted", "error");
25414
25676
  return { complete: false };
25415
25677
  }
25416
25678
  async function directories(root) {
@@ -25429,6 +25691,8 @@ async function directories(root) {
25429
25691
  }
25430
25692
  return out.sort();
25431
25693
  } catch (error) {
25694
+ if (error.code !== "ENOENT")
25695
+ traceError("grok session discovery", error);
25432
25696
  return error.code === "ENOENT" ? [] : null;
25433
25697
  }
25434
25698
  }
@@ -25469,7 +25733,8 @@ async function scan4(agg, opts = {}) {
25469
25733
  let entries;
25470
25734
  try {
25471
25735
  entries = await readdir5(dir, { withFileTypes: true });
25472
- } catch {
25736
+ } catch (error) {
25737
+ traceError("grok session listing", error);
25473
25738
  complete = false;
25474
25739
  continue;
25475
25740
  }
@@ -25610,7 +25875,8 @@ async function scan4(agg, opts = {}) {
25610
25875
  dates.add(new Date(call.tsMs).toISOString().slice(0, 10));
25611
25876
  sessionDates.set(call.session, dates);
25612
25877
  }
25613
- } catch {
25878
+ } catch (error) {
25879
+ traceError("grok retained context", error);
25614
25880
  complete = false;
25615
25881
  stats.filesUnreadable++;
25616
25882
  }
@@ -25859,7 +26125,9 @@ async function dbFilesIn(root) {
25859
26125
  try {
25860
26126
  const entries = await readdir6(root, { withFileTypes: true });
25861
26127
  return entries.filter((e) => e.isFile() && isStoreFile(e.name)).map((e) => path10.join(root, e.name)).sort();
25862
- } catch {
26128
+ } catch (error) {
26129
+ if (error?.code !== "ENOENT")
26130
+ traceError("opencode database discovery", error, "warn");
25863
26131
  return [];
25864
26132
  }
25865
26133
  }
@@ -25868,7 +26136,9 @@ async function loadSqlite() {
25868
26136
  const mod = await import("node:sqlite");
25869
26137
  if (typeof mod.DatabaseSync !== "function") return null;
25870
26138
  return (file) => new mod.DatabaseSync(file, { readOnly: true });
25871
- } catch {
26139
+ } catch (error) {
26140
+ if (error?.code !== "ENOENT")
26141
+ traceError("opencode SQLite initialization", error, "warn");
25872
26142
  return null;
25873
26143
  }
25874
26144
  }
@@ -25893,6 +26163,7 @@ async function scan5(agg, opts = {}) {
25893
26163
  readDb(agg, state, open3, file, sinceMs);
25894
26164
  stats.filesRead++;
25895
26165
  } catch (e) {
26166
+ traceError("opencode database read", e);
25896
26167
  stats.filesUnreadable++;
25897
26168
  stats.unreadableFiles.push({
25898
26169
  path: path10.basename(file),
@@ -25908,7 +26179,9 @@ function checkMigrationCeiling(db) {
25908
26179
  let newest;
25909
26180
  try {
25910
26181
  newest = db.prepare("select max(id) as id from migration").get()?.id;
25911
- } catch {
26182
+ } catch (error) {
26183
+ if (error?.code !== "ENOENT")
26184
+ traceError("opencode database close", error, "warn");
25912
26185
  throw readError2("schema-unversioned");
25913
26186
  }
25914
26187
  const prefix = Number.parseInt(String(newest ?? ""), 10);
@@ -26043,12 +26316,15 @@ function readDb(agg, state, open3, file, sinceMs) {
26043
26316
  messageId: r.message_id
26044
26317
  });
26045
26318
  }
26046
- } catch {
26319
+ } catch (error) {
26320
+ traceError("opencode v2 content", error, "warn");
26047
26321
  }
26048
26322
  } finally {
26049
26323
  try {
26050
26324
  db.close();
26051
- } catch {
26325
+ } catch (error) {
26326
+ if (error?.code !== "ENOENT")
26327
+ traceError("opencode MCP configuration", error, "warn");
26052
26328
  }
26053
26329
  }
26054
26330
  }
@@ -26073,7 +26349,9 @@ function readConfiguredMcpServers2(agg, state, configFile) {
26073
26349
  if (mcp && typeof mcp === "object" && !Array.isArray(mcp)) {
26074
26350
  noteConfiguredMcpServers2(agg, state, Object.keys(mcp));
26075
26351
  }
26076
- } catch {
26352
+ } catch (error) {
26353
+ if (error?.code !== "ENOENT")
26354
+ traceError("opencode detection database close", error, "warn");
26077
26355
  return;
26078
26356
  }
26079
26357
  }
@@ -26124,11 +26402,14 @@ async function detectOpencode(opts) {
26124
26402
  `select 1 as hit from ${table} where time_created >= ? limit 1`
26125
26403
  ).get(opts.sinceMs) !== void 0;
26126
26404
  if (probe("message") || probe("session_message")) return true;
26127
- } catch {
26405
+ } catch (error) {
26406
+ traceError("opencode detection", error, "warn");
26128
26407
  } finally {
26129
26408
  try {
26130
26409
  db?.close();
26131
- } catch {
26410
+ } catch (error) {
26411
+ if (error?.code !== "ENOENT")
26412
+ traceError("opencode source stat", error, "warn");
26132
26413
  }
26133
26414
  }
26134
26415
  }
@@ -26139,7 +26420,9 @@ async function exists4(p8) {
26139
26420
  try {
26140
26421
  await stat6(p8);
26141
26422
  return true;
26142
- } catch {
26423
+ } catch (error) {
26424
+ if (error?.code !== "ENOENT")
26425
+ traceError("opencode source discovery or metadata", error, "warn");
26143
26426
  return false;
26144
26427
  }
26145
26428
  }
@@ -26385,7 +26668,9 @@ async function* walkSessions(dir) {
26385
26668
  let entries;
26386
26669
  try {
26387
26670
  entries = await readdir7(dir, { withFileTypes: true });
26388
- } catch {
26671
+ } catch (error) {
26672
+ if (error?.code !== "ENOENT")
26673
+ traceError("pi transcript discovery", error, "warn");
26389
26674
  return;
26390
26675
  }
26391
26676
  for (const e of entries) {
@@ -26405,7 +26690,9 @@ async function scan6(agg, opts = {}) {
26405
26690
  let resolved;
26406
26691
  try {
26407
26692
  resolved = await realpath3(file);
26408
- } catch {
26693
+ } catch (error) {
26694
+ if (error?.code !== "ENOENT")
26695
+ traceError("pi transcript path resolution", error, "warn");
26409
26696
  resolved = file;
26410
26697
  }
26411
26698
  if (visited.has(resolved)) {
@@ -26420,7 +26707,9 @@ async function scan6(agg, opts = {}) {
26420
26707
  stats.filesSkippedByMtime++;
26421
26708
  continue;
26422
26709
  }
26423
- } catch {
26710
+ } catch (error) {
26711
+ if (error?.code !== "ENOENT")
26712
+ traceError("pi transcript stat", error, "warn");
26424
26713
  }
26425
26714
  }
26426
26715
  agg.files++;
@@ -26441,7 +26730,8 @@ async function scan6(agg, opts = {}) {
26441
26730
  reason: "version-too-new"
26442
26731
  });
26443
26732
  }
26444
- } catch {
26733
+ } catch (error) {
26734
+ traceError("pi transcript read", error);
26445
26735
  stats.filesUnreadable++;
26446
26736
  stats.filesRead--;
26447
26737
  stats.unreadableFiles.push({
@@ -26457,7 +26747,9 @@ async function exists5(p8) {
26457
26747
  try {
26458
26748
  await stat7(p8);
26459
26749
  return true;
26460
- } catch {
26750
+ } catch (error) {
26751
+ if (error?.code !== "ENOENT")
26752
+ traceError("pi source stat", error, "warn");
26461
26753
  return false;
26462
26754
  }
26463
26755
  }
@@ -26475,7 +26767,9 @@ async function ingestFile3(agg, fold, file, sinceMs) {
26475
26767
  let entry;
26476
26768
  try {
26477
26769
  entry = JSON.parse(line);
26478
- } catch {
26770
+ } catch (error) {
26771
+ if (agg.parseErrors === 0)
26772
+ traceError("pi transcript JSON (first failure)", error, "warn");
26479
26773
  agg.parseErrors++;
26480
26774
  continue;
26481
26775
  }
@@ -27736,23 +28030,57 @@ function selectDaysToPublish(input) {
27736
28030
 
27737
28031
  // src/workflow/git.ts
27738
28032
  import { execFile, execFileSync as execFileSync2 } from "node:child_process";
28033
+ import { existsSync as existsSync17 } from "node:fs";
27739
28034
  import path12 from "node:path";
27740
28035
  var TEST_FILE_RULE_VERSION = "test-files/v2";
27741
28036
  var FILE_TYPE_RULE_VERSION = "file-types/v3";
27742
28037
  var COMMIT_SET_RULE_VERSION = "commit-set/v1";
27743
- var defaultRunner = (cwd, args) => {
28038
+ function gitDiagnostics() {
28039
+ let missing = 0;
28040
+ let nonRepositories = 0;
28041
+ const report = (error, cwd, args, stderr) => {
28042
+ const details = error;
28043
+ if (args[0] === "rev-parse") {
28044
+ if (details.code === "ENOENT" && !existsSync17(cwd)) {
28045
+ missing++;
28046
+ return;
28047
+ }
28048
+ const message = stderr ?? (typeof details.stderr === "string" ? details.stderr : "");
28049
+ if (/not a git repository/i.test(message)) {
28050
+ nonRepositories++;
28051
+ return;
28052
+ }
28053
+ }
28054
+ traceError(
28055
+ args.includes("log") ? "git history" : "git repository discovery",
28056
+ error,
28057
+ "warn"
28058
+ );
28059
+ };
28060
+ return {
28061
+ report,
28062
+ finish: () => {
28063
+ if (missing || nonRepositories)
28064
+ trace(
28065
+ `git discovery \xB7 skipped ${missing} missing directories, ${nonRepositories} non-repository directories`
28066
+ );
28067
+ }
28068
+ };
28069
+ }
28070
+ var defaultRunner = (cwd, args, report) => {
27744
28071
  try {
27745
28072
  return execFileSync2("git", [...args], {
27746
28073
  cwd,
27747
28074
  encoding: "utf8",
27748
- stdio: ["ignore", "pipe", "ignore"],
28075
+ stdio: ["ignore", "pipe", "pipe"],
27749
28076
  maxBuffer: 64 * 1024 * 1024
27750
28077
  });
27751
- } catch {
28078
+ } catch (error) {
28079
+ report(error, cwd, args);
27752
28080
  return null;
27753
28081
  }
27754
28082
  };
27755
- var defaultAsyncRunner = (cwd, args) => new Promise((resolve3) => {
28083
+ var defaultAsyncRunner = (cwd, args, report) => new Promise((resolve3) => {
27756
28084
  execFile(
27757
28085
  "git",
27758
28086
  [...args],
@@ -27761,7 +28089,10 @@ var defaultAsyncRunner = (cwd, args) => new Promise((resolve3) => {
27761
28089
  encoding: "utf8",
27762
28090
  maxBuffer: 64 * 1024 * 1024
27763
28091
  },
27764
- (error, stdout) => resolve3(error ? null : stdout)
28092
+ (error, stdout, stderr) => {
28093
+ if (error) report(error, cwd, args, stderr);
28094
+ resolve3(error ? null : stdout);
28095
+ }
27765
28096
  );
27766
28097
  });
27767
28098
  var emptyGitDay = () => ({
@@ -27914,12 +28245,14 @@ function isLateNight(hour) {
27914
28245
  return hour >= 23 || hour < 3;
27915
28246
  }
27916
28247
  function extractGitWorkflow(options) {
27917
- const run = options.run ?? defaultRunner;
28248
+ const diagnostics = gitDiagnostics();
28249
+ const run = options.run ?? ((cwd, args) => defaultRunner(cwd, args, diagnostics.report));
27918
28250
  const roots = /* @__PURE__ */ new Map();
27919
28251
  for (const directory of options.workingDirectories) {
27920
28252
  const root = parseRepositoryRoot(run(directory, gitRevParseArgs()));
27921
28253
  if (root && !roots.has(root.key)) roots.set(root.key, root.cwd);
27922
28254
  }
28255
+ diagnostics.finish();
27923
28256
  const histories = [];
27924
28257
  let index = 0;
27925
28258
  for (const cwd of roots.values()) {
@@ -27931,12 +28264,14 @@ function extractGitWorkflow(options) {
27931
28264
  return reduceGitHistories(histories, options);
27932
28265
  }
27933
28266
  async function extractGitWorkflowAsync(options) {
27934
- const run = options.run ?? defaultAsyncRunner;
28267
+ const diagnostics = gitDiagnostics();
28268
+ const run = options.run ?? ((cwd, args) => defaultAsyncRunner(cwd, args, diagnostics.report));
27935
28269
  const roots = /* @__PURE__ */ new Map();
27936
28270
  for (const directory of options.workingDirectories) {
27937
28271
  const root = parseRepositoryRoot(await run(directory, gitRevParseArgs()));
27938
28272
  if (root && !roots.has(root.key)) roots.set(root.key, root.cwd);
27939
28273
  }
28274
+ diagnostics.finish();
27940
28275
  const queue = [...roots.values()];
27941
28276
  const total = queue.length;
27942
28277
  const histories = [];
@@ -28186,7 +28521,7 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
28186
28521
 
28187
28522
  // src/sync/grokDateCache.ts
28188
28523
  import { createHash as createHash9 } from "node:crypto";
28189
- import { existsSync as existsSync17, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
28524
+ import { existsSync as existsSync18, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
28190
28525
  import { homedir as homedir21 } from "node:os";
28191
28526
  import path13 from "node:path";
28192
28527
  var defaultFile = path13.join(
@@ -28199,7 +28534,7 @@ function grokCacheScope(baseUrl, stack, token) {
28199
28534
  return createHash9("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
28200
28535
  }
28201
28536
  function read2(file) {
28202
- if (!existsSync17(file)) return {};
28537
+ if (!existsSync18(file)) return {};
28203
28538
  try {
28204
28539
  const value = JSON.parse(readFileSync18(file, "utf8"));
28205
28540
  return value && typeof value === "object" ? value : {};
@@ -28573,6 +28908,12 @@ function buildGateSummary(ctx) {
28573
28908
  if (body.measuredDays) {
28574
28909
  out.push(...daysBlock(body.measuredDays, ctx.days));
28575
28910
  }
28911
+ if (ctx.incompleteDayScan) {
28912
+ out.push(
28913
+ "coverage partial history: publishing the dated evidence available",
28914
+ " Previously recorded evidence is retained; missing usage is not estimated."
28915
+ );
28916
+ }
28576
28917
  const workflowDays = (body.measuredDays?.days ?? []).flatMap(
28577
28918
  (d) => d.workflow ? [d.workflow] : []
28578
28919
  );
@@ -28637,10 +28978,20 @@ async function stageSync(deps) {
28637
28978
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
28638
28979
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
28639
28980
  const emit2 = (event) => deps.onEvent?.(event);
28640
- const step = (id, label, state, note) => {
28981
+ const step = (id, label, state, note, level) => {
28641
28982
  if (state !== "waiting")
28642
- trace(`${label} \xB7 ${state}${note ? ` \xB7 ${note}` : ""}`);
28643
- emit2({ kind: "step", id, label, state, ...note ? { note } : {} });
28983
+ trace(
28984
+ `${label} \xB7 ${state}${note ? ` \xB7 ${note}` : ""}`,
28985
+ level ?? (state === "failed" ? "error" : state === "done" ? "success" : state === "skipped" ? "warn" : "info")
28986
+ );
28987
+ emit2({
28988
+ kind: "step",
28989
+ id,
28990
+ label,
28991
+ state,
28992
+ ...note ? { note } : {},
28993
+ ...level ? { level } : {}
28994
+ });
28644
28995
  };
28645
28996
  let prices = {
28646
28997
  id: BUNDLED_PRICE_TABLE_ID,
@@ -28664,9 +29015,10 @@ async function stageSync(deps) {
28664
29015
  step("prices", "Prices", "done", "bundled table");
28665
29016
  }
28666
29017
  } catch (error) {
29018
+ traceError("price table fetch", error, "warn");
28667
29019
  setActivePricer(null);
28668
- done(`fetch failed (${describeError(error)}), bundled table`);
28669
- step("prices", "Prices", "done", "unreachable, bundled table");
29020
+ done("fetch failed, bundled table", "warn");
29021
+ step("prices", "Prices", "done", "unreachable, bundled table", "warn");
28670
29022
  }
28671
29023
  };
28672
29024
  const readSettings = async () => {
@@ -28705,8 +29057,15 @@ async function stageSync(deps) {
28705
29057
  );
28706
29058
  return manifest2;
28707
29059
  } catch (error) {
28708
- done(`fetch failed (${describeError(error)}), whole window goes`);
28709
- step("manifest", "Synced days", "done", "unreachable, whole window");
29060
+ traceError("day manifest fetch", error, "warn");
29061
+ done("fetch failed, whole window goes", "warn");
29062
+ step(
29063
+ "manifest",
29064
+ "Synced days",
29065
+ "done",
29066
+ "unreachable, whole window",
29067
+ "warn"
29068
+ );
28710
29069
  return null;
28711
29070
  }
28712
29071
  };
@@ -28768,7 +29127,10 @@ async function stageSync(deps) {
28768
29127
  publishWorkflow: false,
28769
29128
  onProgress: progress("recent usage")
28770
29129
  });
28771
- scanDone2(describeScan(reading.recent.stats));
29130
+ scanDone2(
29131
+ describeScan(reading.recent.stats),
29132
+ reading.recent.stats.filesUnreadable ? "warn" : "success"
29133
+ );
28772
29134
  }
28773
29135
  step(id, label, "running", "history");
28774
29136
  const scanDone = traceTimer(`scan ${adapter.name} (historical)`);
@@ -28778,14 +29140,16 @@ async function stageSync(deps) {
28778
29140
  onProgress: progress("history")
28779
29141
  });
28780
29142
  scanDone(
28781
- `${describeScan(reading.history.stats)}${reading.history.scanComplete === false ? ", incomplete" : ""}`
29143
+ `${describeScan(reading.history.stats)}${reading.history.scanComplete === false ? ", incomplete" : ""}`,
29144
+ reading.history.scanComplete === false || reading.history.stats.filesUnreadable > 0 ? "warn" : "success"
28782
29145
  );
28783
29146
  const files = Math.max(seen, reading.history.stats.filesRead);
28784
29147
  step(
28785
29148
  id,
28786
29149
  label,
28787
29150
  "done",
28788
- `${files} ${files === 1 ? "file" : "files"} \xB7 ${elapsed()}`
29151
+ `${files} ${files === 1 ? "file" : "files"} \xB7 ${elapsed()}`,
29152
+ reading.history.scanComplete === false || reading.history.stats.filesUnreadable > 0 ? "warn" : "success"
28789
29153
  );
28790
29154
  return reading;
28791
29155
  }
@@ -28819,7 +29183,8 @@ async function stageSync(deps) {
28819
29183
  for (const { adapter, history } of readings) {
28820
29184
  if (!history) continue;
28821
29185
  const { aggregate, workflow: workflow2, workflowLocal, scanComplete, sessionDates } = history;
28822
- if (scanComplete === false) dayScansComplete = false;
29186
+ if (scanComplete === false || history.stats.filesUnreadable > 0 || aggregate.parseErrors > 0)
29187
+ dayScansComplete = false;
28823
29188
  if (adapter.name === "grok-build" || adapter.name === "cursor")
28824
29189
  sessionDatesByHarness.set(adapter.name, sessionDates ?? /* @__PURE__ */ new Map());
28825
29190
  workflowScans.push({ aggregate: workflow2, local: workflowLocal });
@@ -28875,7 +29240,7 @@ async function stageSync(deps) {
28875
29240
  dayScansComplete = false;
28876
29241
  acknowledgements.push(() => saveGrokDateHints(scope, current));
28877
29242
  }
28878
- if (acknowledgements.length)
29243
+ if (acknowledgements.length && dayScansComplete)
28879
29244
  acknowledgePublish = () => {
28880
29245
  for (const acknowledge of acknowledgements) acknowledge();
28881
29246
  };
@@ -28885,12 +29250,13 @@ async function stageSync(deps) {
28885
29250
  ...workflow ? { workflow: workflow.days } : {},
28886
29251
  from: utcDate2(daysSinceMs),
28887
29252
  to: utcDate2(now),
28888
- includeDates: correctionDates
29253
+ // A partial scan cannot prove that a formerly dated session disappeared.
29254
+ includeDates: dayScansComplete ? correctionDates : /* @__PURE__ */ new Set()
28889
29255
  }),
28890
29256
  config
28891
29257
  );
28892
29258
  const days = selectDaysToPublish({
28893
- local: dayScansComplete ? localDays : [],
29259
+ local: localDays,
28894
29260
  manifest,
28895
29261
  todayUtc: utcDate2(now)
28896
29262
  });
@@ -28899,8 +29265,9 @@ async function stageSync(deps) {
28899
29265
  config,
28900
29266
  settings.autoSync,
28901
29267
  deps.trigger,
28902
- historical.length > 0 && dayScansComplete ? {
29268
+ historical.length > 0 ? {
28903
29269
  aggregateVersion: MEASURED_DAYS_V1,
29270
+ ...!dayScansComplete ? { partial: true } : {},
28904
29271
  utcOffsetMinutes: workflow?.utcOffsetMinutes ?? machineUtcOffsetMinutes(),
28905
29272
  days: days.send
28906
29273
  } : void 0,
@@ -28909,10 +29276,17 @@ async function stageSync(deps) {
28909
29276
  step("review", "Review", "running");
28910
29277
  const bodyJson = JSON.stringify(body);
28911
29278
  trace(
28912
- `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (a scan was incomplete, no day rows go)"}`
29279
+ `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (partial history; publishing available evidence)"}`,
29280
+ dayScansComplete ? "success" : "warn"
28913
29281
  );
28914
29282
  trace(`body \xB7 ${bodyJson.length} bytes, ${built.length} harness payloads`);
28915
- step("review", "Review", "done", `${days.send.length} days to send`);
29283
+ step(
29284
+ "review",
29285
+ "Review",
29286
+ "done",
29287
+ `${days.send.length} days to send${dayScansComplete ? "" : " \xB7 partial history"}`,
29288
+ dayScansComplete ? "success" : "warn"
29289
+ );
28916
29290
  const keptPrivate = mergeKeptPrivate(built.map((b) => b.keptPrivate));
28917
29291
  const ctx = {
28918
29292
  body,
@@ -28921,6 +29295,7 @@ async function stageSync(deps) {
28921
29295
  source,
28922
29296
  baseUrl: deps.baseUrl,
28923
29297
  scanStats,
29298
+ incompleteDayScan: !dayScansComplete,
28924
29299
  days,
28925
29300
  prices,
28926
29301
  // The real terminal, so the inventory rows break where this window ends
@@ -28951,12 +29326,6 @@ async function stageSync(deps) {
28951
29326
  ...acknowledgePublish ? { acknowledgePublish } : {}
28952
29327
  };
28953
29328
  }
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
29329
  function describeScan(stats) {
28961
29330
  return `${stats.filesRead}/${stats.filesFound} files read, ${stats.filesUnreadable} unreadable`;
28962
29331
  }
@@ -29062,6 +29431,7 @@ async function runAutoSync(deps) {
29062
29431
  }
29063
29432
  }
29064
29433
  } catch (e) {
29434
+ traceError("auto-sync", e);
29065
29435
  failure2 = e instanceof Error ? e.message : String(e);
29066
29436
  }
29067
29437
  if (revoked) {
@@ -29132,6 +29502,7 @@ function applyEvent(rows, event, now) {
29132
29502
  row.label = event.label;
29133
29503
  row.state = event.state;
29134
29504
  row.note = event.note;
29505
+ row.level = event.level;
29135
29506
  if (event.state === "running" && row.startedAt === void 0)
29136
29507
  row.startedAt = now;
29137
29508
  if (event.state === "done" || event.state === "failed") row.endedAt = now;
@@ -29189,7 +29560,7 @@ function renderRows(rows, opts) {
29189
29560
  break;
29190
29561
  }
29191
29562
  case "done":
29192
- icon = lime("\u25CF");
29563
+ icon = row.level === "warn" ? yellow("\u26A0") : lime("\u25CF");
29193
29564
  body = dim(row.note ?? "done");
29194
29565
  break;
29195
29566
  case "skipped":
@@ -29224,14 +29595,14 @@ function fit(line, width) {
29224
29595
  function createBoard(opts) {
29225
29596
  const rows = /* @__PURE__ */ new Map();
29226
29597
  const now = opts.now ?? (() => Date.now());
29227
- const columns = opts.columns ?? (() => process.stdout.columns ?? 80);
29598
+ const columns2 = opts.columns ?? (() => process.stdout.columns ?? 80);
29228
29599
  let painted = 0;
29229
29600
  let frame = 0;
29230
29601
  let stopped = false;
29231
29602
  const paint = () => {
29232
29603
  const lines2 = renderRows([...rows.values()], {
29233
29604
  now: now(),
29234
- width: columns(),
29605
+ width: columns2(),
29235
29606
  frame
29236
29607
  });
29237
29608
  frame++;
@@ -29253,7 +29624,7 @@ function createBoard(opts) {
29253
29624
  if (opts.interactive) paint();
29254
29625
  else
29255
29626
  opts.write(
29256
- `${renderRows([...rows.values()], { now: now(), width: columns(), frame: 0 }).join("\n")}
29627
+ `${renderRows([...rows.values()], { now: now(), width: columns2(), frame: 0 }).join("\n")}
29257
29628
  `
29258
29629
  );
29259
29630
  }
@@ -29376,6 +29747,7 @@ async function syncCommand(options = {}) {
29376
29747
  onEvent: board.handle
29377
29748
  });
29378
29749
  } catch (e) {
29750
+ traceError("sync scan", e);
29379
29751
  board.stop();
29380
29752
  outroError(e instanceof Error ? e.message : String(e));
29381
29753
  process.exitCode = 1;
@@ -29435,6 +29807,7 @@ async function syncCommand(options = {}) {
29435
29807
  if (!asked) await offerConnectUpsell();
29436
29808
  outro2("done");
29437
29809
  } catch (e) {
29810
+ traceError("sync publish", e);
29438
29811
  s.stop("Publish failed");
29439
29812
  outroError(e instanceof Error ? e.message : String(e));
29440
29813
  process.exitCode = 1;
@@ -29547,6 +29920,7 @@ function createSyncServer(deps, send) {
29547
29920
  try {
29548
29921
  staged = await stage({ baseUrl: deps.baseUrl, now });
29549
29922
  } catch (e) {
29923
+ traceError("sync server request", e);
29550
29924
  staged = null;
29551
29925
  const message = e instanceof Error ? e.message : String(e);
29552
29926
  return ok(id, textResult(`Preview failed: ${message}`, true));
@@ -29732,6 +30106,7 @@ function runStdioSyncServer(deps) {
29732
30106
  try {
29733
30107
  server.handle(JSON.parse(line));
29734
30108
  } catch (e) {
30109
+ traceError("sync server request", e);
29735
30110
  deps.log?.(`parse error: ${String(e)}`);
29736
30111
  }
29737
30112
  }