@use-aistack/cli 0.16.1 → 0.16.2

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
@@ -377,7 +377,7 @@ function apiEquivalentCost(modelKey, t, atMs) {
377
377
  }
378
378
 
379
379
  // src/version.ts
380
- var CLI_VERSION = true ? "0.16.1" : "0.0.0-dev";
380
+ var CLI_VERSION = true ? "0.16.2" : "0.0.0-dev";
381
381
 
382
382
  // src/api.ts
383
383
  var BASE_URL = process.env.AISTACK_URL || "https://aistack.to";
@@ -1846,12 +1846,53 @@ function diffResources(current, existing) {
1846
1846
 
1847
1847
  // src/commands/connect.ts
1848
1848
  import { spawnSync } from "node:child_process";
1849
- import { cpSync, existsSync as existsSync6 } from "node:fs";
1849
+ import { cpSync, existsSync as existsSync7 } from "node:fs";
1850
1850
  import { homedir as homedir14 } from "node:os";
1851
1851
  import { dirname as dirname3, join as join6 } from "node:path";
1852
1852
  import { fileURLToPath } from "node:url";
1853
1853
  import * as p3 from "@clack/prompts";
1854
1854
 
1855
+ // src/trace.ts
1856
+ var sink = null;
1857
+ var startedAtMs = 0;
1858
+ var stderrSink = (line) => {
1859
+ process.stderr.write(`${line}
1860
+ `);
1861
+ };
1862
+ function traceRequestedByEnv(env = process.env) {
1863
+ const value = env.AISTACK_DEBUG?.trim().toLowerCase();
1864
+ return value === "1" || value === "true" || value === "yes";
1865
+ }
1866
+ function enableTrace(write = stderrSink, now = () => performance.now()) {
1867
+ sink = write;
1868
+ startedAtMs = now();
1869
+ }
1870
+ function traceEnabled() {
1871
+ return sink !== null;
1872
+ }
1873
+ function elapsedLabel() {
1874
+ const seconds2 = (performance.now() - startedAtMs) / 1e3;
1875
+ return `+${seconds2.toFixed(seconds2 < 10 ? 2 : 1)}s`;
1876
+ }
1877
+ function trace(message) {
1878
+ if (!sink) return;
1879
+ sink(`[aistack ${elapsedLabel().padStart(7)}] ${message}`);
1880
+ }
1881
+ function traceTimer(label) {
1882
+ if (!sink) return () => {
1883
+ };
1884
+ const started = performance.now();
1885
+ return (note) => {
1886
+ const ms = Math.round(performance.now() - started);
1887
+ trace(`${label} \xB7 ${ms} ms${note ? ` \xB7 ${note}` : ""}`);
1888
+ };
1889
+ }
1890
+ function traceEnvironment(facts) {
1891
+ trace(
1892
+ `aistack ${facts.cliVersion} \xB7 node ${process.versions.node} \xB7 ${process.platform}-${process.arch} \xB7 ${facts.baseUrl}${facts.trigger ? ` \xB7 trigger ${facts.trigger}` : ""}`
1893
+ );
1894
+ }
1895
+
1855
1896
  // src/harness/shared/aggregate.ts
1856
1897
  var asObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
1857
1898
  var asStr = (v) => typeof v === "string" && v.length > 0 ? v : null;
@@ -4991,7 +5032,7 @@ async function scan(agg, opts = {}) {
4991
5032
  const projectDir = rel.split(path2.sep)[0] ?? "(root)";
4992
5033
  agg.files++;
4993
5034
  stats.filesRead++;
4994
- if (opts.onProgress && agg.files % 200 === 0) opts.onProgress(agg.files);
5035
+ if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
4995
5036
  try {
4996
5037
  await ingestFile(
4997
5038
  agg,
@@ -5394,7 +5435,7 @@ async function scan2(agg, opts = {}) {
5394
5435
  }
5395
5436
  agg.files++;
5396
5437
  stats.filesRead++;
5397
- if (opts.onProgress && agg.files % 200 === 0) opts.onProgress(agg.files);
5438
+ if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
5398
5439
  const outcome = ingestWithRetry(agg, file, opts);
5399
5440
  if (!outcome.ok) {
5400
5441
  stats.filesUnreadable++;
@@ -5710,9 +5751,11 @@ function reconcile(local, api) {
5710
5751
  }
5711
5752
 
5712
5753
  // src/harness/cursor/local.ts
5754
+ import { existsSync as existsSync6 } from "node:fs";
5713
5755
  import { stat as stat4 } from "node:fs/promises";
5714
5756
  import { homedir as homedir8 } from "node:os";
5715
5757
  import path4 from "node:path";
5758
+ import { Worker } from "node:worker_threads";
5716
5759
  function dataPath(env = process.env, home = homedir8(), platform4 = process.platform) {
5717
5760
  if (env.CURSOR_DATA_PATH) return path4.resolve(env.CURSOR_DATA_PATH);
5718
5761
  const base = platform4 === "darwin" ? path4.join(home, "Library", "Application Support") : platform4 === "win32" ? env.APPDATA || path4.join(home, "AppData", "Roaming") : env.XDG_CONFIG_HOME || path4.join(home, ".config");
@@ -5795,11 +5838,66 @@ async function sourceStamp(root) {
5795
5838
  );
5796
5839
  return values.join("/");
5797
5840
  }
5841
+ var localReads = /* @__PURE__ */ new Map();
5798
5842
  async function readLocal(root = dataPath(), onProgress) {
5843
+ const held = localReads.get(root);
5844
+ if (held) {
5845
+ trace("cursor \xB7 reusing this run's history read");
5846
+ return held.read;
5847
+ }
5848
+ if (!await hasLocalSource(root)) {
5849
+ trace("cursor \xB7 no local source");
5850
+ return { sessions: [], complete: true, stats: emptyScanStats() };
5851
+ }
5852
+ const stamp = await sourceStamp(root);
5853
+ const read3 = readLocalOffThread(root, stamp, onProgress);
5854
+ localReads.set(root, { stamp, read: read3 });
5855
+ return read3;
5856
+ }
5857
+ function workerFile() {
5858
+ if (process.env.AISTACK_CURSOR_INLINE === "1") return null;
5859
+ const url = new URL("./cursor-worker.js", import.meta.url);
5860
+ return existsSync6(url) ? url : null;
5861
+ }
5862
+ async function readLocalOffThread(root, before, onProgress) {
5863
+ const file = workerFile();
5864
+ if (!file) return readLocalOnce(root, before, onProgress);
5865
+ return new Promise((resolve) => {
5866
+ const fallback = () => resolve(readLocalOnce(root, before, onProgress));
5867
+ let settled = false;
5868
+ const settle = (fn) => {
5869
+ if (settled) return;
5870
+ settled = true;
5871
+ fn();
5872
+ };
5873
+ const worker = new Worker(file, {
5874
+ workerData: { root, before, trace: traceEnabled() }
5875
+ });
5876
+ worker.on("message", (message) => {
5877
+ if (message.kind === "progress")
5878
+ onProgress?.(message.files, message.total);
5879
+ else if (message.kind === "result") settle(() => resolve(message.read));
5880
+ else
5881
+ settle(() => {
5882
+ trace("cursor \xB7 worker failed, reading inline");
5883
+ fallback();
5884
+ });
5885
+ });
5886
+ worker.on("error", () => settle(fallback));
5887
+ worker.on("exit", (code) => {
5888
+ if (code !== 0) settle(fallback);
5889
+ });
5890
+ });
5891
+ }
5892
+ async function readLocalOnce(root, before, onProgress) {
5799
5893
  const stats = emptyScanStats();
5800
5894
  const out = { sessions: [], complete: true, stats };
5801
- if (!await hasLocalSource(root)) return out;
5802
- const before = await sourceStamp(root);
5895
+ if (!await hasLocalSource(root)) {
5896
+ trace("cursor \xB7 no local source");
5897
+ return out;
5898
+ }
5899
+ trace(`cursor \xB7 global database ${await globalDbSize(root)}`);
5900
+ const readDone = traceTimer("cursor history read");
5803
5901
  let context;
5804
5902
  try {
5805
5903
  const reader = await import("cursor-history");
@@ -5815,11 +5913,16 @@ async function readLocal(root = dataPath(), onProgress) {
5815
5913
  const config = { ...options, readContext: context };
5816
5914
  let offset = 0;
5817
5915
  while (true) {
5916
+ const pageDone = traceTimer(
5917
+ offset === 0 ? "cursor session listing" : "cursor session page"
5918
+ );
5818
5919
  const page = await reader.listSessionSummaries({
5819
5920
  ...config,
5820
5921
  offset,
5821
5922
  limit: 100
5822
5923
  });
5924
+ pageDone(`${page.data.length} of ${page.pagination.total} sessions`);
5925
+ if (offset === 0) onProgress?.(0, page.pagination.total);
5823
5926
  for (const summary of page.data) {
5824
5927
  stats.filesFound++;
5825
5928
  if (summary.resolutionState === "ambiguous") {
@@ -5832,7 +5935,7 @@ async function readLocal(root = dataPath(), onProgress) {
5832
5935
  const tokens = await readTokenEvidence(root, session);
5833
5936
  out.sessions.push({ session, tokens });
5834
5937
  stats.filesRead++;
5835
- onProgress?.(stats.filesRead);
5938
+ onProgress?.(stats.filesRead, page.pagination.total);
5836
5939
  } catch {
5837
5940
  out.complete = false;
5838
5941
  stats.filesUnreadable++;
@@ -5858,8 +5961,19 @@ async function readLocal(root = dataPath(), onProgress) {
5858
5961
  }
5859
5962
  }
5860
5963
  if (before !== await sourceStamp(root)) out.complete = false;
5964
+ readDone(
5965
+ `${stats.filesRead}/${stats.filesFound} sessions read, ${stats.filesUnreadable} unreadable${out.complete ? "" : ", incomplete"}`
5966
+ );
5861
5967
  return out;
5862
5968
  }
5969
+ async function globalDbSize(root) {
5970
+ try {
5971
+ const info = await stat4(globalDb(root));
5972
+ return `${(info.size / 1048576).toFixed(0)} MB`;
5973
+ } catch {
5974
+ return "absent";
5975
+ }
5976
+ }
5863
5977
 
5864
5978
  // src/harness/cursor/account.ts
5865
5979
  var digest = (value) => createHash("sha256").update(value).digest("hex");
@@ -7789,7 +7903,7 @@ async function scan6(agg, opts = {}) {
7789
7903
  }
7790
7904
  agg.files++;
7791
7905
  stats.filesRead++;
7792
- if (opts.onProgress && agg.files % 200 === 0) opts.onProgress(agg.files);
7906
+ if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
7793
7907
  try {
7794
7908
  const verdict = await ingestFile3(agg, fold, file, opts.sinceMs);
7795
7909
  if (verdict === "foreign") {
@@ -7927,7 +8041,10 @@ function detectionSinceMs(now = Date.now()) {
7927
8041
  async function detectedAdapters(sinceMs = detectionSinceMs()) {
7928
8042
  const out = [];
7929
8043
  for (const adapter of HARNESS_ADAPTERS) {
7930
- if (await adapter.detect({ sinceMs })) out.push(adapter);
8044
+ const done = traceTimer(`detect ${adapter.name}`);
8045
+ const present = await adapter.detect({ sinceMs });
8046
+ done(present ? "found" : "nothing in window");
8047
+ if (present) out.push(adapter);
7931
8048
  }
7932
8049
  return out;
7933
8050
  }
@@ -7964,7 +8081,7 @@ function findSkillSource(fromDir = dirname3(fileURLToPath(import.meta.url))) {
7964
8081
  let dir = fromDir;
7965
8082
  for (let i = 0; i < 4; i++) {
7966
8083
  const candidate = join6(dir, "skills", "aistack-sync");
7967
- if (existsSync6(join6(candidate, "SKILL.md"))) return candidate;
8084
+ if (existsSync7(join6(candidate, "SKILL.md"))) return candidate;
7968
8085
  const parent = dirname3(dir);
7969
8086
  if (parent === dir) break;
7970
8087
  dir = parent;
@@ -8075,7 +8192,7 @@ async function offerConnectUpsell(deps = {}) {
8075
8192
  }
8076
8193
 
8077
8194
  // src/commands/create.ts
8078
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "node:fs";
8195
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readFileSync as readFileSync8, writeFileSync as writeFileSync2 } from "node:fs";
8079
8196
  import { dirname as dirname4, join as join7 } from "node:path";
8080
8197
  import * as p4 from "@clack/prompts";
8081
8198
  async function createCommand() {
@@ -8136,7 +8253,7 @@ async function createCommand() {
8136
8253
  const skipped = [];
8137
8254
  for (const f of localFiles) {
8138
8255
  const fullPath = join7(cwd, f.path);
8139
- if (existsSync7(fullPath)) {
8256
+ if (existsSync8(fullPath)) {
8140
8257
  const existing = readFileSync8(fullPath, "utf-8");
8141
8258
  skipped.push({ path: f.path, differs: existing !== f.content });
8142
8259
  } else {
@@ -8270,7 +8387,7 @@ import * as p7 from "@clack/prompts";
8270
8387
 
8271
8388
  // src/autosync/codexHook.ts
8272
8389
  import { createHash as createHash3 } from "node:crypto";
8273
- import { existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync9, writeFileSync as writeFileSync3 } from "node:fs";
8390
+ import { existsSync as existsSync9, mkdirSync as mkdirSync3, readFileSync as readFileSync9, writeFileSync as writeFileSync3 } from "node:fs";
8274
8391
  import { homedir as homedir15 } from "node:os";
8275
8392
  import { dirname as dirname5, join as join8 } from "node:path";
8276
8393
  import { parse } from "smol-toml";
@@ -8288,7 +8405,7 @@ function isOurs(entry) {
8288
8405
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
8289
8406
  }
8290
8407
  function readHooksJson(file) {
8291
- if (!existsSync8(file)) return { settings: {} };
8408
+ if (!existsSync9(file)) return { settings: {} };
8292
8409
  try {
8293
8410
  const raw = JSON.parse(readFileSync9(file, "utf-8"));
8294
8411
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -8321,7 +8438,7 @@ function installCodexAutoSyncHook(file = codexHooksFile()) {
8321
8438
  return { ok: true, message: CODEX_TRUST_INSTRUCTION };
8322
8439
  }
8323
8440
  function removeCodexAutoSyncHook(file = codexHooksFile()) {
8324
- if (!existsSync8(file))
8441
+ if (!existsSync9(file))
8325
8442
  return { ok: true, message: "no Codex hook to remove" };
8326
8443
  const read3 = readHooksJson(file);
8327
8444
  if ("error" in read3) return { ok: false, message: read3.error };
@@ -8415,12 +8532,12 @@ function canonicalJson2(value) {
8415
8532
  import * as p6 from "@clack/prompts";
8416
8533
 
8417
8534
  // src/autosync/cursorHook.ts
8418
- import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
8535
+ import { existsSync as existsSync11, mkdirSync as mkdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
8419
8536
  import { homedir as homedir17, platform as platform2 } from "node:os";
8420
8537
  import { dirname as dirname7, join as join10 } from "node:path";
8421
8538
 
8422
8539
  // src/autosync/hook.ts
8423
- import { existsSync as existsSync9, mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync4 } from "node:fs";
8540
+ import { existsSync as existsSync10, mkdirSync as mkdirSync4, readFileSync as readFileSync10, writeFileSync as writeFileSync4 } from "node:fs";
8424
8541
  import { homedir as homedir16 } from "node:os";
8425
8542
  import { dirname as dirname6, join as join9 } from "node:path";
8426
8543
  var CLAUDE_SETTINGS_FILE = join9(homedir16(), ".claude", "settings.json");
@@ -8429,7 +8546,7 @@ function isOurs2(entry) {
8429
8546
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
8430
8547
  }
8431
8548
  function readClaudeSettings(file) {
8432
- if (!existsSync9(file)) return { settings: {} };
8549
+ if (!existsSync10(file)) return { settings: {} };
8433
8550
  try {
8434
8551
  const raw = JSON.parse(readFileSync10(file, "utf-8"));
8435
8552
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -8460,7 +8577,7 @@ function installAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
8460
8577
  return { ok: true, message: `SessionStart hook written to ${file}` };
8461
8578
  }
8462
8579
  function removeAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
8463
- if (!existsSync9(file)) return { ok: true, message: "no hook to remove" };
8580
+ if (!existsSync10(file)) return { ok: true, message: "no hook to remove" };
8464
8581
  const read3 = readClaudeSettings(file);
8465
8582
  if ("error" in read3) return { ok: false, message: read3.error };
8466
8583
  const settings = read3.settings;
@@ -8506,7 +8623,7 @@ function cursorHookCommand(os = platform2()) {
8506
8623
  return `${detach} sh -c 'export AISTACK_HOOK_SOURCE=cursor; ${AUTO_SYNC_HOOK_COMMAND}' </dev/null >/dev/null 2>&1 &`;
8507
8624
  }
8508
8625
  function read(file) {
8509
- if (!existsSync10(file)) return {};
8626
+ if (!existsSync11(file)) return {};
8510
8627
  const value = JSON.parse(readFileSync11(file, "utf8"));
8511
8628
  if (!value || typeof value !== "object" || Array.isArray(value))
8512
8629
  throw new Error("expected a JSON object");
@@ -8570,7 +8687,7 @@ function cursorAutoSyncHookInstalled(file = CURSOR_HOOK_FILE) {
8570
8687
 
8571
8688
  // src/autosync/grokHook.ts
8572
8689
  import {
8573
- existsSync as existsSync11,
8690
+ existsSync as existsSync12,
8574
8691
  mkdirSync as mkdirSync6,
8575
8692
  readFileSync as readFileSync12,
8576
8693
  unlinkSync,
@@ -8594,7 +8711,7 @@ function grokHookCommand(os = platform3()) {
8594
8711
  return `setsid nohup sh -c 'export AISTACK_HOOK_SOURCE=grok; ${SYNC_COMMAND}' >/dev/null 2>&1 &`;
8595
8712
  }
8596
8713
  function readHookFile(file) {
8597
- if (!existsSync11(file)) return { value: {} };
8714
+ if (!existsSync12(file)) return { value: {} };
8598
8715
  try {
8599
8716
  const value = JSON.parse(readFileSync12(file, "utf-8"));
8600
8717
  if (value && typeof value === "object" && !Array.isArray(value)) {
@@ -8653,7 +8770,7 @@ function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform3()) {
8653
8770
  };
8654
8771
  }
8655
8772
  function removeGrokAutoSyncHook(file = GROK_HOOK_FILE) {
8656
- if (!existsSync11(file))
8773
+ if (!existsSync12(file))
8657
8774
  return { ok: true, message: "no Grok Build hook to remove" };
8658
8775
  const read3 = readHookFile(file);
8659
8776
  if ("error" in read3) return { ok: false, message: read3.error };
@@ -9501,7 +9618,7 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
9501
9618
 
9502
9619
  // src/sync/grokDateCache.ts
9503
9620
  import { createHash as createHash4 } from "node:crypto";
9504
- import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "node:fs";
9621
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "node:fs";
9505
9622
  import { homedir as homedir19 } from "node:os";
9506
9623
  import path13 from "node:path";
9507
9624
  var defaultFile = path13.join(
@@ -9514,7 +9631,7 @@ function grokCacheScope(baseUrl, stack, token) {
9514
9631
  return createHash4("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
9515
9632
  }
9516
9633
  function read2(file) {
9517
- if (!existsSync12(file)) return {};
9634
+ if (!existsSync13(file)) return {};
9518
9635
  try {
9519
9636
  const value = JSON.parse(readFileSync13(file, "utf8"));
9520
9637
  return value && typeof value === "object" ? value : {};
@@ -9799,13 +9916,13 @@ function workflowBlock(workflowDays, utcOffsetMinutes, host) {
9799
9916
  out.push(
9800
9917
  ` ${workflowDays.length} day${workflowDays.length === 1 ? "" : "s"}${first && last ? ` \xB7 ${first} to ${last}` : ""}`
9801
9918
  );
9802
- const seconds = PHASE_ORDER.map(
9919
+ const seconds2 = PHASE_ORDER.map(
9803
9920
  (phase) => withPlaybook.reduce((a, h) => a + (h.phase?.phaseSec[phase] ?? 0), 0)
9804
9921
  );
9805
- const total = seconds.reduce((a, b) => a + b, 0);
9922
+ const total = seconds2.reduce((a, b) => a + b, 0);
9806
9923
  if (total > 0) {
9807
9924
  const mix = PHASE_ORDER.map(
9808
- (phase, i) => `${phase} ${fmtPct((seconds[i] ?? 0) / total)}`
9925
+ (phase, i) => `${phase} ${fmtPct((seconds2[i] ?? 0) / total)}`
9809
9926
  ).join(" \xB7 ");
9810
9927
  out.push(` ${mix} \xB7 ${ruleVersions.join(", ")}`);
9811
9928
  }
@@ -9946,43 +10063,90 @@ async function stageSync(deps) {
9946
10063
  const now = (deps.now ?? Date.now)();
9947
10064
  const token = (deps.getTokenImpl ?? getToken)();
9948
10065
  const loadConfig = deps.loadConfigImpl ?? loadSyncConfig;
9949
- const adapters = deps.adaptersImpl ?? detectedAdapters;
10066
+ const adapters = deps.adaptersImpl ?? (() => HARNESS_ADAPTERS);
9950
10067
  const windowDays = deps.windowDays ?? DEFAULT_WINDOW_DAYS;
9951
10068
  const projectWorkspaceId = deps.getProjectWorkspaceIdImpl ?? getProjectWorkspaceId;
9952
10069
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
9953
10070
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
9954
- const progress = deps.onProgress ?? (() => {
9955
- });
10071
+ const emit = (event) => deps.onEvent?.(event);
10072
+ const step = (id, label, state, note) => {
10073
+ if (state !== "waiting")
10074
+ trace(`${label} \xB7 ${state}${note ? ` \xB7 ${note}` : ""}`);
10075
+ emit({ kind: "step", id, label, state, ...note ? { note } : {} });
10076
+ };
9956
10077
  let prices = {
9957
10078
  id: BUNDLED_PRICE_TABLE_ID,
9958
10079
  origin: "bundled"
9959
10080
  };
9960
- progress("Checking prices");
9961
- try {
9962
- const table = await fetchPrices(deps.baseUrl);
9963
- if (table) {
9964
- setActivePricer(layeredPricer(table));
9965
- prices = { id: table.id, origin: "served" };
9966
- } else {
10081
+ step("prices", "Prices", "running");
10082
+ step("settings", "Stack settings", "running");
10083
+ if (token) step("manifest", "Synced days", "running");
10084
+ const readPrices = async () => {
10085
+ const done = traceTimer("prices");
10086
+ try {
10087
+ const table = await fetchPrices(deps.baseUrl);
10088
+ if (table) {
10089
+ setActivePricer(layeredPricer(table));
10090
+ prices = { id: table.id, origin: "served" };
10091
+ done(`served ${table.id}`);
10092
+ step("prices", "Prices", "done", "current");
10093
+ } else {
10094
+ setActivePricer(null);
10095
+ done("server has no price route, bundled table");
10096
+ step("prices", "Prices", "done", "bundled table");
10097
+ }
10098
+ } catch (error) {
9967
10099
  setActivePricer(null);
10100
+ done(`fetch failed (${describeError(error)}), bundled table`);
10101
+ step("prices", "Prices", "done", "unreachable, bundled table");
9968
10102
  }
9969
- } catch {
9970
- setActivePricer(null);
9971
- }
9972
- progress("Checking stack settings");
9973
- const { config, source } = await loadConfig({
9974
- baseUrl: deps.baseUrl,
9975
- ...token ? { token } : {}
9976
- });
9977
- let manifest = null;
9978
- if (token) {
9979
- progress("Checking previously synced days");
10103
+ };
10104
+ const readSettings = async () => {
10105
+ const done = traceTimer("stack settings");
10106
+ const loaded = await loadConfig({
10107
+ baseUrl: deps.baseUrl,
10108
+ ...token ? { token } : {}
10109
+ });
10110
+ done(
10111
+ `${loaded.source}${loaded.config.stack ? ", stack resolved" : ", no stack"}, publishWorkflow ${loaded.config.publishWorkflow}, publishCost ${loaded.config.publishCost}`
10112
+ );
10113
+ step(
10114
+ "settings",
10115
+ "Stack settings",
10116
+ "done",
10117
+ loaded.source === "fetched" ? loaded.config.stack?.name ?? "no stack" : "unreachable"
10118
+ );
10119
+ return loaded;
10120
+ };
10121
+ const readManifest = async () => {
10122
+ if (!token) {
10123
+ trace("day manifest \xB7 skipped, this machine holds no token");
10124
+ return null;
10125
+ }
10126
+ const done = traceTimer("day manifest");
9980
10127
  try {
9981
- manifest = await fetchManifest(deps.baseUrl, token);
9982
- } catch {
9983
- manifest = null;
10128
+ const manifest2 = await fetchManifest(deps.baseUrl, token);
10129
+ done(
10130
+ manifest2 ? `${manifest2.days.length} days held, retention ${manifest2.retentionDays}` : "server has no manifest route, whole window goes"
10131
+ );
10132
+ step(
10133
+ "manifest",
10134
+ "Synced days",
10135
+ "done",
10136
+ manifest2 ? `${manifest2.days.length} held` : "none"
10137
+ );
10138
+ return manifest2;
10139
+ } catch (error) {
10140
+ done(`fetch failed (${describeError(error)}), whole window goes`);
10141
+ step("manifest", "Synced days", "done", "unreachable, whole window");
10142
+ return null;
9984
10143
  }
9985
- }
10144
+ };
10145
+ const [, { config, source }, manifest] = await Promise.all([
10146
+ readPrices(),
10147
+ readSettings(),
10148
+ readManifest()
10149
+ ]);
9986
10150
  const retentionDays = Math.max(
9987
10151
  1,
9988
10152
  Math.min(manifest?.retentionDays ?? MAX_DAY_WINDOW, MAX_DAY_WINDOW)
@@ -9993,18 +10157,83 @@ async function stageSync(deps) {
9993
10157
  const usageScans = [];
9994
10158
  const sinceMs = windowStartMs(now, windowDays);
9995
10159
  const daysSinceMs = windowStartMs(now, retentionDays);
9996
- progress("Detecting local harnesses");
9997
- const active2 = await adapters(sinceMs);
9998
- const historical = await adapters(daysSinceMs);
10160
+ const candidates = await adapters();
10161
+ for (const adapter of candidates)
10162
+ step(`harness:${adapter.name}`, harnessLabel2(adapter.name), "waiting");
10163
+ const readings = await Promise.all(
10164
+ candidates.map((adapter) => readHarness(adapter))
10165
+ );
10166
+ async function readHarness(adapter) {
10167
+ const id = `harness:${adapter.name}`;
10168
+ const label = harnessLabel2(adapter.name);
10169
+ const started = performance.now();
10170
+ const elapsed = () => `${((performance.now() - started) / 1e3).toFixed(1)} s`;
10171
+ step(id, label, "running", "checking history");
10172
+ const detectDone = traceTimer(`detect ${adapter.name}`);
10173
+ const active3 = await adapter.detect({ sinceMs });
10174
+ const historical2 = active3 || await adapter.detect({ sinceMs: daysSinceMs });
10175
+ detectDone(
10176
+ active3 ? "found" : historical2 ? "found (older than the window)" : "nothing in window"
10177
+ );
10178
+ const reading = { adapter, active: active3, historical: historical2 };
10179
+ if (!historical2) {
10180
+ step(id, label, "skipped", "nothing in window");
10181
+ return reading;
10182
+ }
10183
+ let seen = 0;
10184
+ const progress = (phase) => (files2, total) => {
10185
+ seen = files2;
10186
+ emit({
10187
+ kind: "progress",
10188
+ id,
10189
+ done: files2,
10190
+ ...total !== void 0 ? { total } : {},
10191
+ unit: "files",
10192
+ note: phase
10193
+ });
10194
+ };
10195
+ if (active3) {
10196
+ step(id, label, "running", "recent usage");
10197
+ const scanDone2 = traceTimer(`scan ${adapter.name} (recent)`);
10198
+ reading.recent = await adapter.scan({
10199
+ sinceMs,
10200
+ publishWorkflow: false,
10201
+ onProgress: progress("recent usage")
10202
+ });
10203
+ scanDone2(describeScan(reading.recent.stats));
10204
+ }
10205
+ step(id, label, "running", "history");
10206
+ const scanDone = traceTimer(`scan ${adapter.name} (historical)`);
10207
+ reading.history = await adapter.scan({
10208
+ sinceMs: daysSinceMs,
10209
+ publishWorkflow: config.publishWorkflow,
10210
+ onProgress: progress("history")
10211
+ });
10212
+ scanDone(
10213
+ `${describeScan(reading.history.stats)}${reading.history.scanComplete === false ? ", incomplete" : ""}`
10214
+ );
10215
+ const files = Math.max(seen, reading.history.stats.filesRead);
10216
+ step(
10217
+ id,
10218
+ label,
10219
+ "done",
10220
+ `${files} ${files === 1 ? "file" : "files"} \xB7 ${elapsed()}`
10221
+ );
10222
+ return reading;
10223
+ }
10224
+ const active2 = readings.filter((r) => r.active).map((r) => r.adapter);
10225
+ const historical = readings.filter((r) => r.historical).map((r) => r.adapter);
10226
+ trace(
10227
+ `active harnesses (${windowDays} days): ${active2.map((a) => a.name).join(", ") || "none"}`
10228
+ );
10229
+ trace(
10230
+ `historical harnesses (${retentionDays} days): ${historical.map((a) => a.name).join(", ") || "none"}`
10231
+ );
9999
10232
  let dayScansComplete = true;
10000
10233
  const sessionDatesByHarness = /* @__PURE__ */ new Map();
10001
- for (const adapter of active2) {
10002
- progress(`Scanning recent ${adapter.name} usage`);
10003
- const { aggregate, stats } = await adapter.scan({
10004
- sinceMs,
10005
- publishWorkflow: false,
10006
- onProgress: (files) => progress(`Scanning recent ${adapter.name} usage \xB7 ${files} files`)
10007
- });
10234
+ for (const { adapter, recent } of readings) {
10235
+ if (!recent) continue;
10236
+ const { aggregate, stats } = recent;
10008
10237
  scanStats[adapter.name] = stats;
10009
10238
  built.push(
10010
10239
  buildPayload({
@@ -10019,13 +10248,9 @@ async function stageSync(deps) {
10019
10248
  })
10020
10249
  );
10021
10250
  }
10022
- for (const adapter of historical) {
10023
- progress(`Reading historical ${adapter.name} days`);
10024
- const { aggregate, workflow: workflow2, workflowLocal, scanComplete, sessionDates } = await adapter.scan({
10025
- sinceMs: daysSinceMs,
10026
- publishWorkflow: config.publishWorkflow,
10027
- onProgress: (files) => progress(`Reading historical ${adapter.name} days \xB7 ${files} files`)
10028
- });
10251
+ for (const { adapter, history } of readings) {
10252
+ if (!history) continue;
10253
+ const { aggregate, workflow: workflow2, workflowLocal, scanComplete, sessionDates } = history;
10029
10254
  if (scanComplete === false) dayScansComplete = false;
10030
10255
  if (adapter.name === "grok-build" || adapter.name === "cursor")
10031
10256
  sessionDatesByHarness.set(adapter.name, sessionDates ?? /* @__PURE__ */ new Map());
@@ -10042,7 +10267,8 @@ async function stageSync(deps) {
10042
10267
  const settings = (deps.getSettingsImpl ?? getSettings)();
10043
10268
  let workflow;
10044
10269
  if (workflowScans.length > 0 && config.publishWorkflow) {
10045
- progress("Reading Git history");
10270
+ step("git", "Git history", "running");
10271
+ const gitDone = traceTimer("git history");
10046
10272
  workflow = deps.gitRunnerImpl ? extractLocalWorkflow({
10047
10273
  harnesses: workflowScans,
10048
10274
  fromMs: daysSinceMs,
@@ -10053,6 +10279,12 @@ async function stageSync(deps) {
10053
10279
  fromMs: daysSinceMs,
10054
10280
  toMs: now
10055
10281
  });
10282
+ gitDone(`${workflow.days.length} days`);
10283
+ step("git", "Git history", "done", `${workflow.days.length} days`);
10284
+ } else {
10285
+ trace(
10286
+ `git history \xB7 skipped (${config.publishWorkflow ? "no harness scanned" : "publishWorkflow off"})`
10287
+ );
10056
10288
  }
10057
10289
  const correctionDates = /* @__PURE__ */ new Set();
10058
10290
  let acknowledgePublish;
@@ -10106,8 +10338,13 @@ async function stageSync(deps) {
10106
10338
  } : void 0,
10107
10339
  CLI_VERSION
10108
10340
  );
10109
- progress("Preparing review");
10341
+ step("review", "Review", "running");
10110
10342
  const bodyJson = JSON.stringify(body);
10343
+ trace(
10344
+ `days \xB7 ${days.mode}, ${days.send.length} to send${dayScansComplete ? "" : " (a scan was incomplete, no day rows go)"}`
10345
+ );
10346
+ trace(`body \xB7 ${bodyJson.length} bytes, ${built.length} harness payloads`);
10347
+ step("review", "Review", "done", `${days.send.length} days to send`);
10111
10348
  const keptPrivate = mergeKeptPrivate(built.map((b) => b.keptPrivate));
10112
10349
  const ctx = {
10113
10350
  body,
@@ -10146,6 +10383,15 @@ async function stageSync(deps) {
10146
10383
  ...acknowledgePublish ? { acknowledgePublish } : {}
10147
10384
  };
10148
10385
  }
10386
+ function describeError(error) {
10387
+ if (error instanceof Error) {
10388
+ return error.name === "TimeoutError" ? "timed out" : error.message;
10389
+ }
10390
+ return String(error);
10391
+ }
10392
+ function describeScan(stats) {
10393
+ return `${stats.filesRead}/${stats.filesFound} files read, ${stats.filesUnreadable} unreadable`;
10394
+ }
10149
10395
 
10150
10396
  // src/autosync/run.ts
10151
10397
  var SYNC_LOG_FILE = join12(homedir20(), ".config", "aistack", "sync.log");
@@ -10303,8 +10549,159 @@ async function runAutoSync(deps) {
10303
10549
  }
10304
10550
  }
10305
10551
 
10552
+ // src/sync/board.ts
10553
+ var BAR_CELLS = 12;
10554
+ var FILLED = "\u2588";
10555
+ var EMPTY = "\u2591";
10556
+ var PREFIX = "\u2502 ";
10557
+ function applyEvent(rows, event, now) {
10558
+ const row = rows.get(event.id) ?? {
10559
+ id: event.id,
10560
+ label: event.kind === "step" ? event.label : event.id,
10561
+ state: "waiting"
10562
+ };
10563
+ if (event.kind === "step") {
10564
+ row.label = event.label;
10565
+ row.state = event.state;
10566
+ row.note = event.note;
10567
+ if (event.state === "running" && row.startedAt === void 0)
10568
+ row.startedAt = now;
10569
+ if (event.state === "done" || event.state === "failed") row.endedAt = now;
10570
+ if (event.state === "running" && row.note !== void 0) {
10571
+ row.done = void 0;
10572
+ row.total = void 0;
10573
+ }
10574
+ } else {
10575
+ row.done = event.done;
10576
+ row.total = event.total;
10577
+ row.unit = event.unit;
10578
+ if (event.note !== void 0) row.note = event.note;
10579
+ if (row.state === "waiting") row.state = "running";
10580
+ if (row.startedAt === void 0) row.startedAt = now;
10581
+ }
10582
+ rows.set(event.id, row);
10583
+ }
10584
+ function bar(done, total, frame) {
10585
+ if (total !== void 0 && total > 0) {
10586
+ const filled = Math.max(
10587
+ 0,
10588
+ Math.min(BAR_CELLS, Math.round(done / total * BAR_CELLS))
10589
+ );
10590
+ return `${lime(FILLED.repeat(filled))}${dim(EMPTY.repeat(BAR_CELLS - filled))}`;
10591
+ }
10592
+ const span = BAR_CELLS - 3;
10593
+ const at = frame % (span * 2);
10594
+ const start = at < span ? at : span * 2 - at;
10595
+ return [...Array(BAR_CELLS).keys()].map((i) => i >= start && i < start + 3 ? lime(FILLED) : dim(EMPTY)).join("");
10596
+ }
10597
+ var seconds = (ms) => `${(ms / 1e3).toFixed(1)} s`;
10598
+ function renderRows(rows, opts) {
10599
+ const labelWidth = Math.max(0, ...rows.map((r) => r.label.length));
10600
+ return rows.map((row) => {
10601
+ const label = row.label.padEnd(labelWidth);
10602
+ let icon;
10603
+ let body;
10604
+ switch (row.state) {
10605
+ case "waiting":
10606
+ icon = dim("\u25CB");
10607
+ body = dim("waiting");
10608
+ break;
10609
+ case "running": {
10610
+ icon = lime("\u25D0");
10611
+ const parts = [bar(row.done ?? 0, row.total, opts.frame)];
10612
+ if (row.done !== void 0) {
10613
+ parts.push(
10614
+ row.total !== void 0 ? `${row.done}/${row.total} ${row.unit ?? ""}`.trimEnd() : `${row.done} ${row.unit ?? ""}`.trimEnd()
10615
+ );
10616
+ }
10617
+ if (row.note) parts.push(dim(row.note));
10618
+ if (row.startedAt !== void 0)
10619
+ parts.push(dim(seconds(opts.now - row.startedAt)));
10620
+ body = parts.join(" ");
10621
+ break;
10622
+ }
10623
+ case "done":
10624
+ icon = lime("\u25CF");
10625
+ body = dim(row.note ?? "done");
10626
+ break;
10627
+ case "skipped":
10628
+ icon = dim("\u25CB");
10629
+ body = dim(row.note ?? "skipped");
10630
+ break;
10631
+ case "failed":
10632
+ icon = red("\u2717");
10633
+ body = red(row.note ?? "failed");
10634
+ break;
10635
+ }
10636
+ return fit(`${dim(PREFIX)}${icon} ${label} ${body}`, opts.width);
10637
+ });
10638
+ }
10639
+ function fit(line, width) {
10640
+ if (width <= 0) return line;
10641
+ let visible = 0;
10642
+ let out = "";
10643
+ for (const part of line.split(/(\x1b\[[0-9;]*m)/)) {
10644
+ if (part.startsWith("\x1B[")) {
10645
+ out += part;
10646
+ continue;
10647
+ }
10648
+ const room = width - 1 - visible;
10649
+ if (room <= 0) break;
10650
+ const slice = [...part].slice(0, room).join("");
10651
+ out += slice;
10652
+ visible += [...slice].length;
10653
+ }
10654
+ return `${out}\x1B[0m`;
10655
+ }
10656
+ function createBoard(opts) {
10657
+ const rows = /* @__PURE__ */ new Map();
10658
+ const now = opts.now ?? (() => Date.now());
10659
+ const columns = opts.columns ?? (() => process.stdout.columns ?? 80);
10660
+ let painted = 0;
10661
+ let frame = 0;
10662
+ let stopped = false;
10663
+ const paint = () => {
10664
+ const lines2 = renderRows([...rows.values()], {
10665
+ now: now(),
10666
+ width: columns(),
10667
+ frame
10668
+ });
10669
+ frame++;
10670
+ const up = painted > 0 ? `\x1B[${painted}A` : "";
10671
+ opts.write(`${up}${lines2.map((line) => `\x1B[2K\r${line}`).join("\n")}
10672
+ `);
10673
+ painted = lines2.length;
10674
+ };
10675
+ const timer = opts.interactive ? setInterval(paint, opts.frameMs ?? 80) : null;
10676
+ return {
10677
+ handle: (event) => {
10678
+ if (stopped) return;
10679
+ applyEvent(rows, event, now());
10680
+ },
10681
+ stop: () => {
10682
+ if (stopped) return;
10683
+ stopped = true;
10684
+ if (timer) clearInterval(timer);
10685
+ if (opts.interactive) paint();
10686
+ else
10687
+ opts.write(
10688
+ `${renderRows([...rows.values()], { now: now(), width: columns(), frame: 0 }).join("\n")}
10689
+ `
10690
+ );
10691
+ }
10692
+ };
10693
+ }
10694
+
10306
10695
  // src/commands/sync.ts
10307
10696
  async function syncCommand(options = {}) {
10697
+ if (options.verbose || traceRequestedByEnv()) {
10698
+ enableTrace();
10699
+ traceEnvironment({
10700
+ cliVersion: CLI_VERSION,
10701
+ baseUrl: BASE_URL,
10702
+ trigger: options.auto === true ? "auto" : "manual"
10703
+ });
10704
+ }
10308
10705
  if (options.auto === true) {
10309
10706
  await runAutoSync({ baseUrl: BASE_URL });
10310
10707
  return;
@@ -10397,23 +10794,27 @@ async function syncCommand(options = {}) {
10397
10794
  }
10398
10795
  const destinationToken = token;
10399
10796
  const destinationConfig = loaded;
10400
- const s = p7.spinner();
10401
- s.start("Scanning local agent transcripts");
10797
+ p7.log.step("Scanning local history");
10798
+ const board = createBoard({
10799
+ write: (text) => process.stdout.write(text),
10800
+ interactive: !traceEnabled()
10801
+ });
10402
10802
  let staged;
10403
10803
  try {
10404
10804
  staged = await stageSync({
10405
10805
  baseUrl: BASE_URL,
10406
10806
  getTokenImpl: () => destinationToken,
10407
10807
  loadConfigImpl: async () => destinationConfig,
10408
- onProgress: (message) => s.message(message)
10808
+ onEvent: board.handle
10409
10809
  });
10410
10810
  } catch (e) {
10411
- s.stop("Scan failed");
10811
+ board.stop();
10412
10812
  outroError(e instanceof Error ? e.message : String(e));
10413
10813
  process.exitCode = 1;
10414
10814
  return;
10415
10815
  }
10416
- s.stop("Scan complete");
10816
+ board.stop();
10817
+ const s = p7.spinner();
10417
10818
  p7.log.message(staged.summary.split("\n").map(styleSummaryLine).join("\n"));
10418
10819
  if (staged.blockedReason !== null) {
10419
10820
  outroError(staged.blockedReason);
@@ -10792,6 +11193,9 @@ program.command("sync").description("Scan, preview, and publish measured usage (
10792
11193
  ).option(
10793
11194
  "--every <hours>",
10794
11195
  "with --auto on: hours between auto-syncs (default 6)"
11196
+ ).option(
11197
+ "--verbose",
11198
+ "print every phase with its duration to stderr, for a sync that looks stuck (same as AISTACK_DEBUG=1)"
10795
11199
  ).action((options) => syncCommand(options));
10796
11200
  program.command("connect").description("Install the in-session sync surface (MCP server + Skill)").argument("<harness>", 'the harness to connect ("claude")').action(connectCommand);
10797
11201
  if (!supportsNodeVersion(process.versions.node)) {