@use-aistack/cli 0.16.6 → 0.16.8

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
@@ -2586,11 +2586,11 @@ function isKeyValueStatement(sql) {
2586
2586
  function emit(context, operation, identity, adapter = "sqlite") {
2587
2587
  observeAdapterIo(context, { adapter, operation, ...identity });
2588
2588
  }
2589
- function openObservedDatabase(context, request2, open3) {
2589
+ function openObservedDatabase(context, request2, open4) {
2590
2590
  if (!context)
2591
- return open3();
2591
+ return open4();
2592
2592
  emit(context, "open", requestIdentity(request2));
2593
- return new ObservedDatabase(open3(), context, request2);
2593
+ return new ObservedDatabase(open4(), context, request2);
2594
2594
  }
2595
2595
  function observeDatabaseBackup(request2) {
2596
2596
  if (!request2.io)
@@ -4036,8 +4036,8 @@ var init_source_read_limits = __esm({
4036
4036
 
4037
4037
  // ../../node_modules/.pnpm/cursor-history@0.18.0_patch_hash=8c02b8ff8b7820637beb3f0d25856ca4f632932000105288ff64b66ffbbd8cf5/node_modules/cursor-history/dist/core/zip-stream.js
4038
4038
  import { createHash as createHash2 } from "node:crypto";
4039
- import { open, unlink } from "node:fs/promises";
4040
- import { Readable, Transform, Writable } from "node:stream";
4039
+ import { open as open2, unlink } from "node:fs/promises";
4040
+ import { Readable as Readable2, Transform, Writable } from "node:stream";
4041
4041
  import { pipeline } from "node:stream/promises";
4042
4042
  import { createInflateRaw } from "node:zlib";
4043
4043
  function zipEntryIoIdentity(name) {
@@ -4150,7 +4150,7 @@ function readHandleRange(handle, position, length, signal) {
4150
4150
  yield buffer.subarray(0, bytesRead);
4151
4151
  }
4152
4152
  }
4153
- return Readable.from(chunks(), { objectMode: false });
4153
+ return Readable2.from(chunks(), { objectMode: false });
4154
4154
  }
4155
4155
  function writeToHandle(handle) {
4156
4156
  let position = 0;
@@ -4540,7 +4540,7 @@ async function prepareZipFileInputs(inputs, options = {}) {
4540
4540
  for (const input of inputs) {
4541
4541
  throwIfAborted(options.signal);
4542
4542
  const normalized = validateWriteName(input.name, portableNames);
4543
- const handle = await open(input.sourcePath, "r");
4543
+ const handle = await open2(input.sourcePath, "r");
4544
4544
  try {
4545
4545
  const before = await handle.stat({ bigint: true });
4546
4546
  if (!before.isFile())
@@ -4701,7 +4701,7 @@ async function writeBoundedZipArchive(destinationPath, inputs, options = {}) {
4701
4701
  const limits = resolveSourceReadLimits(options.sourceReadLimits);
4702
4702
  throwIfAborted(options.signal);
4703
4703
  const plan = planWriteEntries(inputs, limits);
4704
- const destination = await open(destinationPath, "wx", 384);
4704
+ const destination = await open2(destinationPath, "wx", 384);
4705
4705
  try {
4706
4706
  await destination.chmod(384);
4707
4707
  let position = 0;
@@ -4723,7 +4723,7 @@ async function writeBoundedZipArchive(destinationPath, inputs, options = {}) {
4723
4723
  }
4724
4724
  if (!entry.sourcePath || !entry.checksum)
4725
4725
  throw formatError("Prepared ZIP input is incomplete.");
4726
- const source = await open(entry.sourcePath, "r");
4726
+ const source = await open2(entry.sourcePath, "r");
4727
4727
  try {
4728
4728
  const metadata = await source.stat({ bigint: true });
4729
4729
  if (!metadata.isFile() || metadata.size !== BigInt(entry.size)) {
@@ -4973,7 +4973,7 @@ var init_zip_stream = __esm({
4973
4973
  resourceClass: "backup-central-directory"
4974
4974
  });
4975
4975
  }
4976
- const handle = await open(path14, "r");
4976
+ const handle = await open2(path14, "r");
4977
4977
  try {
4978
4978
  if (options.io) {
4979
4979
  observeAdapterIo(options.io, {
@@ -5127,7 +5127,7 @@ var init_zip_stream = __esm({
5127
5127
  const entry = this.getEntry(name);
5128
5128
  if (!entry)
5129
5129
  throw formatError(`ZIP entry was not found: ${name}`);
5130
- const destination = await open(destinationPath, "r+");
5130
+ const destination = await open2(destinationPath, "r+");
5131
5131
  try {
5132
5132
  await destination.chmod(384);
5133
5133
  await destination.truncate(0);
@@ -5144,7 +5144,7 @@ var init_zip_stream = __esm({
5144
5144
  const entry = this.getEntry(name);
5145
5145
  if (!entry)
5146
5146
  throw formatError(`ZIP entry was not found: ${name}`);
5147
- const destination = await open(destinationPath, "r+");
5147
+ const destination = await open2(destinationPath, "r+");
5148
5148
  try {
5149
5149
  await destination.chmod(384);
5150
5150
  await destination.truncate(0);
@@ -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.6" : "0.0.0-dev";
18894
+ var CLI_VERSION = true ? "0.16.8" : "0.0.0-dev";
18895
18895
 
18896
18896
  // src/api.ts
18897
18897
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
@@ -22663,6 +22663,7 @@ function buildSyncBody(built, syncConfig, autoSync, trigger = "manual", measured
22663
22663
  measuredDays: {
22664
22664
  aggregateVersion: MEASURED_DAYS_V1,
22665
22665
  utcOffsetMinutes: measuredDays.utcOffsetMinutes,
22666
+ ...measuredDays.partial ? { partial: true } : {},
22666
22667
  days: applyDayConsent(measuredDays.days, syncConfig)
22667
22668
  }
22668
22669
  } : base;
@@ -24009,9 +24010,10 @@ function noteConfiguredMcpServers(agg, serverNames) {
24009
24010
 
24010
24011
  // src/harness/codex/scan.ts
24011
24012
  import { readFileSync as readFileSync6 } from "node:fs";
24012
- import { readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
24013
+ import { open, readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
24013
24014
  import { homedir as homedir7 } from "node:os";
24014
24015
  import path3 from "node:path";
24016
+ import { Readable } from "node:stream";
24015
24017
  import * as zlib from "node:zlib";
24016
24018
  import { parse as parseToml2 } from "smol-toml";
24017
24019
  function codexHome() {
@@ -24039,7 +24041,8 @@ async function* walkRollouts(dir) {
24039
24041
  else if (e.isFile() && isRolloutFile(e.name)) yield full;
24040
24042
  }
24041
24043
  }
24042
- var zstdDecompress = typeof zlib.zstdDecompressSync === "function" ? (buf) => zlib.zstdDecompressSync(buf) : null;
24044
+ var createZstdDecompress2 = typeof zlib.createZstdDecompress === "function" ? zlib.createZstdDecompress : null;
24045
+ var MAX_LINE_BYTES = 64 * 1024 * 1024;
24043
24046
  async function scan2(agg, opts = {}) {
24044
24047
  const stats = emptyScanStats();
24045
24048
  const visited = /* @__PURE__ */ new Set();
@@ -24076,7 +24079,7 @@ async function scan2(agg, opts = {}) {
24076
24079
  agg.files++;
24077
24080
  stats.filesRead++;
24078
24081
  if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
24079
- const outcome = ingestWithRetry(agg, file, opts);
24082
+ const outcome = await ingestWithRetry(agg, file, opts);
24080
24083
  if (!outcome.ok) {
24081
24084
  stats.filesUnreadable++;
24082
24085
  stats.filesRead--;
@@ -24112,14 +24115,14 @@ function errorClass(e) {
24112
24115
  return e instanceof Error ? e.constructor.name : "unknown";
24113
24116
  }
24114
24117
  var readError = (reason) => Object.assign(new Error(reason), { code: reason });
24115
- function ingestWithRetry(agg, file, opts) {
24118
+ async function ingestWithRetry(agg, file, opts) {
24116
24119
  try {
24117
- return ingestFile2(agg, file, opts);
24120
+ return await ingestFile2(agg, file, opts);
24118
24121
  } catch (e) {
24119
24122
  traceError("codex rollout read", e);
24120
24123
  if (errorClass(e) === "ENOENT" && !file.endsWith(".zst")) {
24121
24124
  try {
24122
- return ingestFile2(agg, `${file}.zst`, opts);
24125
+ return await ingestFile2(agg, `${file}.zst`, opts);
24123
24126
  } catch (e2) {
24124
24127
  traceError("codex compressed rollout retry", e2);
24125
24128
  return { ok: false, reason: errorClass(e2) };
@@ -24128,56 +24131,125 @@ function ingestWithRetry(agg, file, opts) {
24128
24131
  return { ok: false, reason: errorClass(e) };
24129
24132
  }
24130
24133
  }
24131
- function ingestFile2(agg, file, opts) {
24132
- const readFile4 = opts.readFileImpl ?? readFileSync6;
24133
- const raw = readFile4(file);
24134
- let bytes = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
24135
- if (file.endsWith(".zst")) {
24136
- if (zstdDecompress === null) throw readError("zstd-unsupported");
24137
- try {
24138
- bytes = zstdDecompress(bytes);
24139
- } catch (error) {
24140
- traceError("codex zstd decompression", error);
24141
- throw readError("zstd-corrupt");
24142
- }
24134
+ async function ingestFile2(agg, file, opts) {
24135
+ const compressed = file.endsWith(".zst");
24136
+ if (compressed && !createZstdDecompress2) throw readError("zstd-unsupported");
24137
+ const handle = await open(file, "r");
24138
+ try {
24139
+ const { size } = await handle.stat();
24140
+ let nonEmptyLines = 0;
24141
+ let parseErrors = 0;
24142
+ async function* records(count2) {
24143
+ if (size === 0) return;
24144
+ async function* chunks() {
24145
+ for (let position = 0; position < size; ) {
24146
+ const buffer = Buffer.allocUnsafe(
24147
+ Math.min(opts.chunkBytes ?? 64 * 1024, size - position)
24148
+ );
24149
+ const { bytesRead } = await handle.read(
24150
+ buffer,
24151
+ 0,
24152
+ buffer.length,
24153
+ position
24154
+ );
24155
+ if (bytesRead === 0) throw readError("rollout-truncated");
24156
+ position += bytesRead;
24157
+ yield buffer.subarray(0, bytesRead);
24158
+ }
24159
+ }
24160
+ const source = opts.readStreamImpl ? opts.readStreamImpl(file, {
24161
+ start: 0,
24162
+ end: size - 1,
24163
+ highWaterMark: opts.chunkBytes ?? 64 * 1024
24164
+ }) : Readable.from(chunks(), { objectMode: false });
24165
+ let sourceError;
24166
+ const decoder = compressed ? createZstdDecompress2?.() : void 0;
24167
+ source.on("error", (error) => {
24168
+ sourceError = error;
24169
+ decoder?.destroy(error);
24170
+ });
24171
+ const stream = decoder ? source.pipe(decoder) : source;
24172
+ try {
24173
+ for await (const line of boundedLines(
24174
+ stream,
24175
+ opts.maxLineBytes ?? MAX_LINE_BYTES
24176
+ )) {
24177
+ if (line === "") continue;
24178
+ if (count2) nonEmptyLines++;
24179
+ let record;
24180
+ try {
24181
+ if (line === null) throw readError("record-too-large");
24182
+ record = JSON.parse(line);
24183
+ } catch (error) {
24184
+ if (count2) {
24185
+ if (parseErrors === 0)
24186
+ traceError("codex rollout JSON (first failure)", error, "warn");
24187
+ parseErrors++;
24188
+ }
24189
+ continue;
24190
+ }
24191
+ yield record;
24192
+ }
24193
+ } catch (error) {
24194
+ if (decoder && !sourceError) {
24195
+ traceError("codex zstd decompression", error);
24196
+ throw readError("zstd-corrupt");
24197
+ }
24198
+ throw sourceError ?? error;
24199
+ } finally {
24200
+ source.destroy();
24201
+ decoder?.destroy();
24202
+ }
24203
+ }
24204
+ const verdict = await classifyRollout(records(true));
24205
+ if (!verdict.genuine) return { ok: true, ...verdict };
24206
+ agg.lines += nonEmptyLines;
24207
+ agg.parseErrors += parseErrors;
24208
+ const state = createFileState();
24209
+ for await (const rec of records(false))
24210
+ ingestLine(agg, rec, state, opts.sinceMs);
24211
+ return { ok: true, genuine: true };
24212
+ } finally {
24213
+ await handle.close();
24143
24214
  }
24144
- let nonEmptyLines = 0;
24145
- let parseErrors = 0;
24146
- function* records() {
24147
- for (let start = 0; start < bytes.length; ) {
24215
+ }
24216
+ async function* boundedLines(stream, limit) {
24217
+ let parts = [];
24218
+ let length = 0;
24219
+ let oversized = false;
24220
+ for await (const chunk of stream) {
24221
+ const bytes = chunk;
24222
+ let start = 0;
24223
+ while (start < bytes.length) {
24148
24224
  const newline = bytes.indexOf(10, start);
24149
24225
  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;
24226
+ const part = bytes.subarray(start, end);
24227
+ if (!oversized) {
24228
+ length += part.length;
24229
+ if (length > limit) {
24230
+ oversized = true;
24231
+ parts = [];
24232
+ } else parts.push(part);
24233
+ }
24234
+ if (newline >= 0) {
24235
+ yield oversized ? null : Buffer.concat(parts, length).toString("utf8");
24236
+ parts = [];
24237
+ length = 0;
24238
+ oversized = false;
24162
24239
  }
24163
- yield record;
24240
+ start = end + 1;
24164
24241
  }
24165
24242
  }
24166
- const verdict = classifyRollout(records());
24167
- if (!verdict.genuine) return { ok: true, ...verdict };
24168
- agg.lines += nonEmptyLines;
24169
- agg.parseErrors += parseErrors;
24170
- const state = createFileState();
24171
- for (const rec of records()) ingestLine(agg, rec, state, opts.sinceMs);
24172
- return { ok: true, genuine: true };
24243
+ if (oversized || length > 0)
24244
+ yield oversized ? null : Buffer.concat(parts, length).toString("utf8");
24173
24245
  }
24174
- function classifyRollout(records) {
24246
+ async function classifyRollout(records) {
24175
24247
  let originator = null;
24176
24248
  let sawTurnContext = false;
24177
24249
  let sawTokenCount = false;
24178
24250
  let genuine = true;
24179
24251
  let count2 = 0;
24180
- for (const raw of records) {
24252
+ for await (const raw of records) {
24181
24253
  const rec = asObj(raw);
24182
24254
  const type = rec ? asStr(rec.type) : null;
24183
24255
  const payload = rec ? asObj(rec.payload) : null;
@@ -24570,6 +24642,11 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24570
24642
  const readDone = traceTimer("cursor history read");
24571
24643
  let context;
24572
24644
  let retrySmallPage = false;
24645
+ let unresolved = 0;
24646
+ let corrupted = 0;
24647
+ let ambiguous = 0;
24648
+ let stage = "reader setup";
24649
+ const signal = AbortSignal.timeout(12e4);
24573
24650
  try {
24574
24651
  const reader = await Promise.resolve().then(() => (init_lib(), lib_exports));
24575
24652
  const options = {
@@ -24579,7 +24656,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24579
24656
  traceError("cursor source diagnostic", diagnostic, "warn");
24580
24657
  out.complete = false;
24581
24658
  },
24582
- signal: AbortSignal.timeout(12e4)
24659
+ signal
24583
24660
  };
24584
24661
  context = reader.createSessionReadContext({ ...options, sourceReadLimits });
24585
24662
  const config = { ...options, readContext: context };
@@ -24588,6 +24665,7 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24588
24665
  const pageDone = traceTimer(
24589
24666
  offset === 0 ? "cursor session listing" : "cursor session page"
24590
24667
  );
24668
+ stage = "session listing";
24591
24669
  const page = await reader.listSessionSummaries({
24592
24670
  ...config,
24593
24671
  offset,
@@ -24598,28 +24676,26 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24598
24676
  for (const summary of page.data) {
24599
24677
  stats.filesFound++;
24600
24678
  if (summary.resolutionState === "ambiguous") {
24601
- trace(
24602
- "cursor session resolution incomplete \xB7 ambiguous source",
24603
- "warn"
24604
- );
24605
24679
  out.complete = false;
24606
24680
  }
24607
24681
  try {
24682
+ stage = "session read";
24608
24683
  const session = await reader.getSession(summary.id, config);
24609
24684
  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
- );
24685
+ if (session.resolutionState !== "complete") unresolved++;
24686
+ if (session.messages.some((m) => m.metadata?.corrupted))
24687
+ corrupted++;
24614
24688
  out.complete = false;
24615
24689
  }
24690
+ stage = "token evidence";
24616
24691
  const tokens = await readTokenEvidence(root, session);
24617
24692
  out.sessions.push({ session, tokens });
24618
24693
  stats.filesRead++;
24619
24694
  onProgress?.(stats.filesRead, page.pagination.total);
24620
24695
  } catch (error) {
24621
24696
  if (isPageByteLimit(error)) throw error;
24622
- traceError("cursor history", error);
24697
+ if (traceErrorCode(error) === "SESSION_AMBIGUOUS") ambiguous++;
24698
+ else traceError(`cursor ${stage}`, error, "warn");
24623
24699
  out.complete = false;
24624
24700
  stats.filesUnreadable++;
24625
24701
  } finally {
@@ -24638,7 +24714,9 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24638
24714
  offset += page.data.length;
24639
24715
  }
24640
24716
  } catch (error) {
24641
- traceError("cursor history", error);
24717
+ traceError(`cursor ${stage}`, error);
24718
+ if (signal.aborted)
24719
+ traceError("cursor read deadline", signal.reason, "warn");
24642
24720
  retrySmallPage = isPageByteLimit(error) && sourceReadLimits?.sqlitePageRows !== 1;
24643
24721
  stats.unreadableFiles.push({
24644
24722
  path: "history",
@@ -24671,6 +24749,12 @@ async function readLocalOnce(root, before, onProgress, sourceReadLimits) {
24671
24749
  );
24672
24750
  out.complete = false;
24673
24751
  }
24752
+ if (unresolved || corrupted || ambiguous) {
24753
+ trace(
24754
+ `cursor partial history \xB7 ${unresolved} sessions unresolved, ${corrupted} with corrupted messages, ${ambiguous} skipped with conflicting copies${ambiguous ? " (SESSION_AMBIGUOUS)" : ""} \xB7 available dated usage retained`,
24755
+ "warn"
24756
+ );
24757
+ }
24674
24758
  readDone(
24675
24759
  `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`,
24676
24760
  out.complete ? "success" : "warn"
@@ -24758,6 +24842,23 @@ function apiContribution(value) {
24758
24842
  };
24759
24843
  }
24760
24844
  async function fetchWindow(account, from, to, fetchImpl = fetch) {
24845
+ const budget = { requests: 0, signal: AbortSignal.timeout(3e5) };
24846
+ async function read3(start, end) {
24847
+ try {
24848
+ return await fetchPages(account, start, end, fetchImpl, budget);
24849
+ } catch (error) {
24850
+ if (traceErrorCode(error) !== "CURSOR_PAGE_LIMIT" || end - start <= 1)
24851
+ throw error;
24852
+ const middle = start + Math.floor((end - start) / 2);
24853
+ trace("cursor account usage \xB7 splitting capped date window");
24854
+ const left = await read3(start, middle);
24855
+ const right = await read3(middle, end);
24856
+ return [...left, ...right];
24857
+ }
24858
+ }
24859
+ return read3(from, to);
24860
+ }
24861
+ async function fetchPages(account, from, to, fetchImpl, budget) {
24761
24862
  const out = [];
24762
24863
  const pages = /* @__PURE__ */ new Set();
24763
24864
  const eventIds = /* @__PURE__ */ new Set();
@@ -24765,12 +24866,17 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24765
24866
  let retrieved = 0;
24766
24867
  const pageSize = 100;
24767
24868
  for (let page = 1; page <= 100; page++) {
24869
+ budget.signal.throwIfAborted();
24870
+ if (++budget.requests > 1e3)
24871
+ throw Object.assign(new Error("Cursor request budget"), {
24872
+ code: "CURSOR_REQUEST_LIMIT"
24873
+ });
24768
24874
  const response = await fetchImpl(
24769
24875
  "https://cursor.com/api/dashboard/get-filtered-usage-events",
24770
24876
  {
24771
24877
  method: "POST",
24772
24878
  redirect: "error",
24773
- signal: AbortSignal.timeout(15e3),
24879
+ signal: AbortSignal.any([budget.signal, AbortSignal.timeout(15e3)]),
24774
24880
  headers: {
24775
24881
  "Content-Type": "application/json",
24776
24882
  Origin: "https://cursor.com",
@@ -24790,9 +24896,13 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24790
24896
  });
24791
24897
  const payload = asObj(await response.json());
24792
24898
  const events = payload?.usageEventsDisplay;
24793
- if (!Array.isArray(events) || events.length > pageSize)
24899
+ if (!Array.isArray(events))
24794
24900
  throw Object.assign(new Error("Invalid Cursor page"), {
24795
- code: "CURSOR_INVALID_PAGE"
24901
+ code: "CURSOR_INVALID_PAGE_SHAPE"
24902
+ });
24903
+ if (events.length > pageSize)
24904
+ throw Object.assign(new Error("Cursor page exceeds requested size"), {
24905
+ code: "CURSOR_PAGE_TOO_LARGE"
24796
24906
  });
24797
24907
  if (payload?.totalUsageEventsCount !== void 0) {
24798
24908
  const reported = count(payload.totalUsageEventsCount);
@@ -24801,6 +24911,10 @@ async function fetchWindow(account, from, to, fetchImpl = fetch) {
24801
24911
  code: "CURSOR_PAGE_COUNT_CHANGED"
24802
24912
  });
24803
24913
  total = reported;
24914
+ if (total > 100 * pageSize)
24915
+ throw Object.assign(new Error("Cursor page limit"), {
24916
+ code: "CURSOR_PAGE_LIMIT"
24917
+ });
24804
24918
  }
24805
24919
  if (events.length) {
24806
24920
  const key2 = digest(JSON.stringify(events));
@@ -24891,30 +25005,45 @@ async function saveCache(file, value) {
24891
25005
  await writeFile(temporary, JSON.stringify(value), { mode: 384 });
24892
25006
  await rename(temporary, file);
24893
25007
  }
25008
+ var REFRESH_MS = 3e5;
24894
25009
  var WINDOW_MS = 30 * 864e5;
24895
25010
  async function refreshAccount(input) {
24896
25011
  const { cache, account, now, sessionIds } = input;
24897
- if (!account) return cache;
25012
+ if (!account || !sessionIds.size) return cache;
25013
+ const state = input.state;
25014
+ if (state && state.account !== account.scope) {
25015
+ state.account = account.scope;
25016
+ state.windows = {};
25017
+ state.failedAt = void 0;
25018
+ }
24898
25019
  const changed = cache.account !== account.scope;
24899
25020
  const next = {
24900
25021
  ...cache,
24901
25022
  account: account.scope,
24902
- windows: changed ? {} : { ...cache.windows }
25023
+ windows: { ...changed ? {} : cache.windows, ...state?.windows }
24903
25024
  };
25025
+ if (state?.failedAt !== void 0 && now - state.failedAt < REFRESH_MS)
25026
+ return next;
24904
25027
  for (let from = Math.floor(input.sinceMs / WINDOW_MS) * WINDOW_MS; from <= now; from += WINDOW_MS) {
24905
25028
  const to = Math.min(from + WINDOW_MS, now + 1);
24906
25029
  const key2 = String(from);
24907
25030
  const previous = next.windows[key2];
24908
- if (previous && now - previous.fetchedAt < 3e5) continue;
25031
+ if (previous && now - previous.fetchedAt < REFRESH_MS) continue;
24909
25032
  try {
24910
25033
  const events = (await fetchWindow(account, from, to, input.fetchImpl)).filter((e) => sessionIds.has(e.session));
24911
25034
  if (previous?.events.length && events.length === 0 && to <= now) continue;
24912
25035
  next.windows[key2] = { from, to, fetchedAt: now, events };
24913
25036
  } catch (error) {
24914
- traceError("cursor account enrichment", error, "warn");
25037
+ if (state) state.failedAt = now;
25038
+ traceError(
25039
+ "cursor account usage refresh (using local and previously cached usage)",
25040
+ error,
25041
+ "warn"
25042
+ );
24915
25043
  break;
24916
25044
  }
24917
25045
  }
25046
+ if (state) state.windows = next.windows;
24918
25047
  return next;
24919
25048
  }
24920
25049
  function cachedEvents(cache, sessionIds) {
@@ -25069,6 +25198,7 @@ function projectHistory(options) {
25069
25198
  }
25070
25199
 
25071
25200
  // src/harness/cursor/scan.ts
25201
+ var accountRefreshes = /* @__PURE__ */ new Map();
25072
25202
  async function scan3(options) {
25073
25203
  const root = options.root ?? dataPath();
25074
25204
  const now = options.now ?? Date.now();
@@ -25090,14 +25220,21 @@ async function scan3(options) {
25090
25220
  );
25091
25221
  complete = false;
25092
25222
  }
25093
- const account = await (options.accountImpl ?? existingAccount)(root);
25223
+ const account = ids.size ? await (options.accountImpl ?? existingAccount)(root) : null;
25224
+ const refreshKey = JSON.stringify([root, storeRoot(), file]);
25225
+ let refreshState = accountRefreshes.get(refreshKey);
25226
+ if (!refreshState) {
25227
+ refreshState = {};
25228
+ accountRefreshes.set(refreshKey, refreshState);
25229
+ }
25094
25230
  const cache = await refreshAccount({
25095
25231
  cache: loaded.value,
25096
25232
  account,
25097
25233
  sinceMs: options.sinceMs,
25098
25234
  now,
25099
25235
  sessionIds: ids,
25100
- fetchImpl: options.fetchImpl
25236
+ fetchImpl: options.fetchImpl,
25237
+ state: refreshState
25101
25238
  });
25102
25239
  const api = cachedEvents(cache, ids);
25103
25240
  const native = /* @__PURE__ */ new Set();
@@ -26136,7 +26273,7 @@ function errorClass2(e) {
26136
26273
  var readError2 = (reason) => Object.assign(new Error(reason), { code: reason });
26137
26274
  async function scan5(agg, opts = {}) {
26138
26275
  const stats = emptyScanStats();
26139
- const open3 = await loadSqlite();
26276
+ const open4 = await loadSqlite();
26140
26277
  const sinceMs = opts.sinceMs ?? 0;
26141
26278
  const state = createDbFoldState();
26142
26279
  readConfiguredMcpServers2(agg, state, opts.configFile);
@@ -26145,8 +26282,8 @@ async function scan5(agg, opts = {}) {
26145
26282
  stats.filesFound++;
26146
26283
  agg.files++;
26147
26284
  try {
26148
- if (open3 === null) throw readError2("sqlite-unsupported");
26149
- readDb(agg, state, open3, file, sinceMs);
26285
+ if (open4 === null) throw readError2("sqlite-unsupported");
26286
+ readDb(agg, state, open4, file, sinceMs);
26150
26287
  stats.filesRead++;
26151
26288
  } catch (e) {
26152
26289
  traceError("opencode database read", e);
@@ -26174,8 +26311,8 @@ function checkMigrationCeiling(db) {
26174
26311
  if (!Number.isFinite(prefix)) throw readError2("schema-unversioned");
26175
26312
  if (prefix > OPENCODE_MIGRATION_CEILING) throw readError2("schema-too-new");
26176
26313
  }
26177
- function readDb(agg, state, open3, file, sinceMs) {
26178
- const db = open3(file);
26314
+ function readDb(agg, state, open4, file, sinceMs) {
26315
+ const db = open4(file);
26179
26316
  try {
26180
26317
  checkMigrationCeiling(db);
26181
26318
  noteSessions(
@@ -26375,14 +26512,14 @@ function stripJsonc(text) {
26375
26512
  return out.replace(/,(\s*[}\]])/g, "$1");
26376
26513
  }
26377
26514
  async function detectOpencode(opts) {
26378
- const open3 = await loadSqlite();
26379
- if (open3 === null) return false;
26515
+ const open4 = await loadSqlite();
26516
+ if (open4 === null) return false;
26380
26517
  for (const root of opts.roots ?? opencodeDataDirs()) {
26381
26518
  for (const file of await dbFilesIn(root)) {
26382
26519
  if (!await exists4(file)) continue;
26383
26520
  let db = null;
26384
26521
  try {
26385
- db = open3(file);
26522
+ db = open4(file);
26386
26523
  checkMigrationCeiling(db);
26387
26524
  const probe = (table) => db?.prepare(
26388
26525
  `select 1 as hit from ${table} where time_created >= ? limit 1`
@@ -27098,7 +27235,7 @@ async function createCommand() {
27098
27235
  // src/commands/login.ts
27099
27236
  import { hostname } from "node:os";
27100
27237
  import * as p5 from "@clack/prompts";
27101
- import open2 from "open";
27238
+ import open3 from "open";
27102
27239
  function proposedMachineName(read3 = hostname) {
27103
27240
  try {
27104
27241
  const name = read3().trim().replace(/\.local$/i, "");
@@ -27140,7 +27277,7 @@ async function performLogin(options = {}) {
27140
27277
  p5.log.info(`${dim("CODE")} ${limeBold(session.userCode)}`);
27141
27278
  p5.log.info(`${dim("OPEN")} ${dim(session.authUrl)}`);
27142
27279
  try {
27143
- await open2(session.authUrl);
27280
+ await open3(session.authUrl);
27144
27281
  } catch {
27145
27282
  p5.log.warn(
27146
27283
  "Could not open browser automatically. Please visit the URL above."
@@ -28016,28 +28153,57 @@ function selectDaysToPublish(input) {
28016
28153
 
28017
28154
  // src/workflow/git.ts
28018
28155
  import { execFile, execFileSync as execFileSync2 } from "node:child_process";
28156
+ import { existsSync as existsSync17 } from "node:fs";
28019
28157
  import path12 from "node:path";
28020
28158
  var TEST_FILE_RULE_VERSION = "test-files/v2";
28021
28159
  var FILE_TYPE_RULE_VERSION = "file-types/v3";
28022
28160
  var COMMIT_SET_RULE_VERSION = "commit-set/v1";
28023
- var defaultRunner = (cwd, args) => {
28161
+ function gitDiagnostics() {
28162
+ let missing = 0;
28163
+ let nonRepositories = 0;
28164
+ const report = (error, cwd, args, stderr) => {
28165
+ const details = error;
28166
+ if (args[0] === "rev-parse") {
28167
+ if (details.code === "ENOENT" && !existsSync17(cwd)) {
28168
+ missing++;
28169
+ return;
28170
+ }
28171
+ const message = stderr ?? (typeof details.stderr === "string" ? details.stderr : "");
28172
+ if (/not a git repository/i.test(message)) {
28173
+ nonRepositories++;
28174
+ return;
28175
+ }
28176
+ }
28177
+ traceError(
28178
+ args.includes("log") ? "git history" : "git repository discovery",
28179
+ error,
28180
+ "warn"
28181
+ );
28182
+ };
28183
+ return {
28184
+ report,
28185
+ finish: () => {
28186
+ if (missing || nonRepositories)
28187
+ trace(
28188
+ `git discovery \xB7 skipped ${missing} missing directories, ${nonRepositories} non-repository directories`
28189
+ );
28190
+ }
28191
+ };
28192
+ }
28193
+ var defaultRunner = (cwd, args, report) => {
28024
28194
  try {
28025
28195
  return execFileSync2("git", [...args], {
28026
28196
  cwd,
28027
28197
  encoding: "utf8",
28028
- stdio: ["ignore", "pipe", "ignore"],
28198
+ stdio: ["ignore", "pipe", "pipe"],
28029
28199
  maxBuffer: 64 * 1024 * 1024
28030
28200
  });
28031
28201
  } catch (error) {
28032
- traceError(
28033
- args[0] === "log" ? "git history" : "git repository discovery",
28034
- error,
28035
- "warn"
28036
- );
28202
+ report(error, cwd, args);
28037
28203
  return null;
28038
28204
  }
28039
28205
  };
28040
- var defaultAsyncRunner = (cwd, args) => new Promise((resolve3) => {
28206
+ var defaultAsyncRunner = (cwd, args, report) => new Promise((resolve3) => {
28041
28207
  execFile(
28042
28208
  "git",
28043
28209
  [...args],
@@ -28046,13 +28212,8 @@ var defaultAsyncRunner = (cwd, args) => new Promise((resolve3) => {
28046
28212
  encoding: "utf8",
28047
28213
  maxBuffer: 64 * 1024 * 1024
28048
28214
  },
28049
- (error, stdout) => {
28050
- if (error)
28051
- traceError(
28052
- args[0] === "log" ? "git history" : "git repository discovery",
28053
- error,
28054
- "warn"
28055
- );
28215
+ (error, stdout, stderr) => {
28216
+ if (error) report(error, cwd, args, stderr);
28056
28217
  resolve3(error ? null : stdout);
28057
28218
  }
28058
28219
  );
@@ -28207,29 +28368,46 @@ function isLateNight(hour) {
28207
28368
  return hour >= 23 || hour < 3;
28208
28369
  }
28209
28370
  function extractGitWorkflow(options) {
28210
- const run = options.run ?? defaultRunner;
28371
+ const diagnostics = gitDiagnostics();
28372
+ const run = options.run ?? ((cwd, args) => defaultRunner(cwd, args, diagnostics.report));
28211
28373
  const roots = /* @__PURE__ */ new Map();
28212
28374
  for (const directory of options.workingDirectories) {
28213
28375
  const root = parseRepositoryRoot(run(directory, gitRevParseArgs()));
28214
28376
  if (root && !roots.has(root.key)) roots.set(root.key, root.cwd);
28215
28377
  }
28378
+ diagnostics.finish();
28216
28379
  const histories = [];
28217
28380
  let index = 0;
28218
28381
  for (const cwd of roots.values()) {
28219
28382
  const done = repositoryTimer(++index, roots.size);
28220
- const history = run(cwd, gitLogArgs());
28383
+ const metadata = run(cwd, gitMetadataArgs());
28384
+ const parts = [];
28385
+ let history = metadata === null ? null : "";
28386
+ if (metadata !== null) {
28387
+ for (const args of gitDiffBatches(metadata, options)) {
28388
+ const part = run(cwd, args);
28389
+ if (part === null) {
28390
+ history = null;
28391
+ break;
28392
+ }
28393
+ parts.push(part);
28394
+ }
28395
+ if (history !== null) history = parts.join("");
28396
+ }
28221
28397
  done(history);
28222
28398
  if (history) histories.push(history);
28223
28399
  }
28224
28400
  return reduceGitHistories(histories, options);
28225
28401
  }
28226
28402
  async function extractGitWorkflowAsync(options) {
28227
- const run = options.run ?? defaultAsyncRunner;
28403
+ const diagnostics = gitDiagnostics();
28404
+ const run = options.run ?? ((cwd, args) => defaultAsyncRunner(cwd, args, diagnostics.report));
28228
28405
  const roots = /* @__PURE__ */ new Map();
28229
28406
  for (const directory of options.workingDirectories) {
28230
28407
  const root = parseRepositoryRoot(await run(directory, gitRevParseArgs()));
28231
28408
  if (root && !roots.has(root.key)) roots.set(root.key, root.cwd);
28232
28409
  }
28410
+ diagnostics.finish();
28233
28411
  const queue = [...roots.values()];
28234
28412
  const total = queue.length;
28235
28413
  const histories = [];
@@ -28237,7 +28415,20 @@ async function extractGitWorkflowAsync(options) {
28237
28415
  const worker = async () => {
28238
28416
  for (let cwd = queue.shift(); cwd !== void 0; cwd = queue.shift()) {
28239
28417
  const done = repositoryTimer(++index, total);
28240
- const history = await run(cwd, gitLogArgs());
28418
+ const metadata = await run(cwd, gitMetadataArgs());
28419
+ const parts = [];
28420
+ let history = metadata === null ? null : "";
28421
+ if (metadata !== null) {
28422
+ for (const args of gitDiffBatches(metadata, options)) {
28423
+ const part = await run(cwd, args);
28424
+ if (part === null) {
28425
+ history = null;
28426
+ break;
28427
+ }
28428
+ parts.push(part);
28429
+ }
28430
+ if (history !== null) history = parts.join("");
28431
+ }
28241
28432
  done(history);
28242
28433
  if (history) histories.push(history);
28243
28434
  }
@@ -28277,17 +28468,39 @@ function countCommits(history) {
28277
28468
  }
28278
28469
  return count2;
28279
28470
  }
28280
- function gitLogArgs() {
28281
- return [
28471
+ var GIT_FORMAT = `--format=%x00${COMMIT_MARKER}%x00%H%x00%aI%x00`;
28472
+ var GIT_DIFF_BATCH_SIZE = 128;
28473
+ function gitMetadataArgs() {
28474
+ return ["log", "--all", "--no-merges", GIT_FORMAT, "--no-patch", "-z"];
28475
+ }
28476
+ function* gitDiffBatches(metadata, options) {
28477
+ const fields = metadata.split("\0");
28478
+ let hashes = [];
28479
+ const args = (batch) => [
28282
28480
  "-c",
28283
28481
  `core.bigFileThreshold=${BIG_FILE_THRESHOLD}`,
28284
28482
  "log",
28285
- "--all",
28483
+ "--no-walk=unsorted",
28286
28484
  "--no-merges",
28287
- `--format=%x00${COMMIT_MARKER}%x00%H%x00%aI%x00`,
28485
+ GIT_FORMAT,
28288
28486
  "--numstat",
28289
- "-z"
28487
+ "-z",
28488
+ ...batch,
28489
+ "--"
28290
28490
  ];
28491
+ for (let index = 0; index < fields.length; index++) {
28492
+ if (fields[index]?.replace(/^\n+/, "") !== COMMIT_MARKER) continue;
28493
+ const hash2 = fields[++index] ?? "";
28494
+ const authoredMs = Date.parse(fields[++index] ?? "");
28495
+ if (!/^[a-f0-9]+$/.test(hash2) || !Number.isFinite(authoredMs) || authoredMs < options.fromMs || authoredMs > options.toMs)
28496
+ continue;
28497
+ hashes.push(hash2);
28498
+ if (hashes.length === GIT_DIFF_BATCH_SIZE) {
28499
+ yield args(hashes);
28500
+ hashes = [];
28501
+ }
28502
+ }
28503
+ if (hashes.length) yield args(hashes);
28291
28504
  }
28292
28505
  function reduceGitHistories(histories, options) {
28293
28506
  const days = /* @__PURE__ */ new Map();
@@ -28479,7 +28692,7 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
28479
28692
 
28480
28693
  // src/sync/grokDateCache.ts
28481
28694
  import { createHash as createHash9 } from "node:crypto";
28482
- import { existsSync as existsSync17, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
28695
+ import { existsSync as existsSync18, mkdirSync as mkdirSync8, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "node:fs";
28483
28696
  import { homedir as homedir21 } from "node:os";
28484
28697
  import path13 from "node:path";
28485
28698
  var defaultFile = path13.join(
@@ -28492,7 +28705,7 @@ function grokCacheScope(baseUrl, stack, token) {
28492
28705
  return createHash9("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
28493
28706
  }
28494
28707
  function read2(file) {
28495
- if (!existsSync17(file)) return {};
28708
+ if (!existsSync18(file)) return {};
28496
28709
  try {
28497
28710
  const value = JSON.parse(readFileSync18(file, "utf8"));
28498
28711
  return value && typeof value === "object" ? value : {};
@@ -28865,10 +29078,11 @@ function buildGateSummary(ctx) {
28865
29078
  out.push("", DIVIDER, "", "ALSO PUBLISHING");
28866
29079
  if (body.measuredDays) {
28867
29080
  out.push(...daysBlock(body.measuredDays, ctx.days));
28868
- } else if (ctx.incompleteDayScan) {
29081
+ }
29082
+ if (ctx.incompleteDayScan) {
28869
29083
  out.push(
28870
- "days not published: a historical scan was incomplete",
28871
- " Model breakdown and daily statistics will not update."
29084
+ "coverage partial history: publishing the dated evidence available",
29085
+ " Previously recorded evidence is retained; missing usage is not estimated."
28872
29086
  );
28873
29087
  }
28874
29088
  const workflowDays = (body.measuredDays?.days ?? []).flatMap(
@@ -28941,7 +29155,14 @@ async function stageSync(deps) {
28941
29155
  `${label} \xB7 ${state}${note ? ` \xB7 ${note}` : ""}`,
28942
29156
  level ?? (state === "failed" ? "error" : state === "done" ? "success" : state === "skipped" ? "warn" : "info")
28943
29157
  );
28944
- emit2({ kind: "step", id, label, state, ...note ? { note } : {} });
29158
+ emit2({
29159
+ kind: "step",
29160
+ id,
29161
+ label,
29162
+ state,
29163
+ ...note ? { note } : {},
29164
+ ...level ? { level } : {}
29165
+ });
28945
29166
  };
28946
29167
  let prices = {
28947
29168
  id: BUNDLED_PRICE_TABLE_ID,
@@ -29133,7 +29354,8 @@ async function stageSync(deps) {
29133
29354
  for (const { adapter, history } of readings) {
29134
29355
  if (!history) continue;
29135
29356
  const { aggregate, workflow: workflow2, workflowLocal, scanComplete, sessionDates } = history;
29136
- if (scanComplete === false) dayScansComplete = false;
29357
+ if (scanComplete === false || history.stats.filesUnreadable > 0 || aggregate.parseErrors > 0)
29358
+ dayScansComplete = false;
29137
29359
  if (adapter.name === "grok-build" || adapter.name === "cursor")
29138
29360
  sessionDatesByHarness.set(adapter.name, sessionDates ?? /* @__PURE__ */ new Map());
29139
29361
  workflowScans.push({ aggregate: workflow2, local: workflowLocal });
@@ -29189,7 +29411,7 @@ async function stageSync(deps) {
29189
29411
  dayScansComplete = false;
29190
29412
  acknowledgements.push(() => saveGrokDateHints(scope, current));
29191
29413
  }
29192
- if (acknowledgements.length)
29414
+ if (acknowledgements.length && dayScansComplete)
29193
29415
  acknowledgePublish = () => {
29194
29416
  for (const acknowledge of acknowledgements) acknowledge();
29195
29417
  };
@@ -29199,12 +29421,13 @@ async function stageSync(deps) {
29199
29421
  ...workflow ? { workflow: workflow.days } : {},
29200
29422
  from: utcDate2(daysSinceMs),
29201
29423
  to: utcDate2(now),
29202
- includeDates: correctionDates
29424
+ // A partial scan cannot prove that a formerly dated session disappeared.
29425
+ includeDates: dayScansComplete ? correctionDates : /* @__PURE__ */ new Set()
29203
29426
  }),
29204
29427
  config
29205
29428
  );
29206
29429
  const days = selectDaysToPublish({
29207
- local: dayScansComplete ? localDays : [],
29430
+ local: localDays,
29208
29431
  manifest,
29209
29432
  todayUtc: utcDate2(now)
29210
29433
  });
@@ -29213,8 +29436,9 @@ async function stageSync(deps) {
29213
29436
  config,
29214
29437
  settings.autoSync,
29215
29438
  deps.trigger,
29216
- historical.length > 0 && dayScansComplete ? {
29439
+ historical.length > 0 ? {
29217
29440
  aggregateVersion: MEASURED_DAYS_V1,
29441
+ ...!dayScansComplete ? { partial: true } : {},
29218
29442
  utcOffsetMinutes: workflow?.utcOffsetMinutes ?? machineUtcOffsetMinutes(),
29219
29443
  days: days.send
29220
29444
  } : void 0,
@@ -29223,11 +29447,17 @@ async function stageSync(deps) {
29223
29447
  step("review", "Review", "running");
29224
29448
  const bodyJson = JSON.stringify(body);
29225
29449
  trace(
29226
- `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (a scan was incomplete, no day rows go)"}`,
29450
+ `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (partial history; publishing available evidence)"}`,
29227
29451
  dayScansComplete ? "success" : "warn"
29228
29452
  );
29229
29453
  trace(`body \xB7 ${bodyJson.length} bytes, ${built.length} harness payloads`);
29230
- step("review", "Review", "done", `${days.send.length} days to send`);
29454
+ step(
29455
+ "review",
29456
+ "Review",
29457
+ "done",
29458
+ `${days.send.length} days to send${dayScansComplete ? "" : " \xB7 partial history"}`,
29459
+ dayScansComplete ? "success" : "warn"
29460
+ );
29231
29461
  const keptPrivate = mergeKeptPrivate(built.map((b) => b.keptPrivate));
29232
29462
  const ctx = {
29233
29463
  body,
@@ -29443,6 +29673,7 @@ function applyEvent(rows, event, now) {
29443
29673
  row.label = event.label;
29444
29674
  row.state = event.state;
29445
29675
  row.note = event.note;
29676
+ row.level = event.level;
29446
29677
  if (event.state === "running" && row.startedAt === void 0)
29447
29678
  row.startedAt = now;
29448
29679
  if (event.state === "done" || event.state === "failed") row.endedAt = now;
@@ -29500,7 +29731,7 @@ function renderRows(rows, opts) {
29500
29731
  break;
29501
29732
  }
29502
29733
  case "done":
29503
- icon = lime("\u25CF");
29734
+ icon = row.level === "warn" ? yellow("\u26A0") : lime("\u25CF");
29504
29735
  body = dim(row.note ?? "done");
29505
29736
  break;
29506
29737
  case "skipped":