@use-aistack/cli 0.16.0 → 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,10 +377,11 @@ function apiEquivalentCost(modelKey, t, atMs) {
377
377
  }
378
378
 
379
379
  // src/version.ts
380
- var CLI_VERSION = true ? "0.16.0" : "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";
384
+ var STARTUP_READ_TIMEOUT_MS = 5e3;
384
385
  async function request(path14, options = {}) {
385
386
  return fetch(`${BASE_URL}${path14}`, {
386
387
  ...options,
@@ -501,6 +502,7 @@ async function syncPublish(token, bodyJson) {
501
502
  }
502
503
  async function fetchDayManifest(baseUrl, token) {
503
504
  const res = await fetch(`${baseUrl}/api/cli/sync-manifest`, {
505
+ signal: AbortSignal.timeout(STARTUP_READ_TIMEOUT_MS),
504
506
  headers: { "Content-Type": "application/json", ...authHeaders(token) }
505
507
  });
506
508
  if (res.status === 404) return null;
@@ -524,6 +526,7 @@ async function fetchDayManifest(baseUrl, token) {
524
526
  }
525
527
  async function fetchPriceTable(baseUrl) {
526
528
  const res = await fetch(`${baseUrl}/api/prices`, {
529
+ signal: AbortSignal.timeout(STARTUP_READ_TIMEOUT_MS),
527
530
  headers: { Accept: "application/json" }
528
531
  });
529
532
  if (res.status === 404) return null;
@@ -1843,12 +1846,53 @@ function diffResources(current, existing) {
1843
1846
 
1844
1847
  // src/commands/connect.ts
1845
1848
  import { spawnSync } from "node:child_process";
1846
- import { cpSync, existsSync as existsSync6 } from "node:fs";
1849
+ import { cpSync, existsSync as existsSync7 } from "node:fs";
1847
1850
  import { homedir as homedir14 } from "node:os";
1848
1851
  import { dirname as dirname3, join as join6 } from "node:path";
1849
1852
  import { fileURLToPath } from "node:url";
1850
1853
  import * as p3 from "@clack/prompts";
1851
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
+
1852
1896
  // src/harness/shared/aggregate.ts
1853
1897
  var asObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
1854
1898
  var asStr = (v) => typeof v === "string" && v.length > 0 ? v : null;
@@ -4988,7 +5032,7 @@ async function scan(agg, opts = {}) {
4988
5032
  const projectDir = rel.split(path2.sep)[0] ?? "(root)";
4989
5033
  agg.files++;
4990
5034
  stats.filesRead++;
4991
- if (opts.onProgress && agg.files % 200 === 0) opts.onProgress(agg.files);
5035
+ if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
4992
5036
  try {
4993
5037
  await ingestFile(
4994
5038
  agg,
@@ -5391,7 +5435,7 @@ async function scan2(agg, opts = {}) {
5391
5435
  }
5392
5436
  agg.files++;
5393
5437
  stats.filesRead++;
5394
- if (opts.onProgress && agg.files % 200 === 0) opts.onProgress(agg.files);
5438
+ if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
5395
5439
  const outcome = ingestWithRetry(agg, file, opts);
5396
5440
  if (!outcome.ok) {
5397
5441
  stats.filesUnreadable++;
@@ -5707,9 +5751,11 @@ function reconcile(local, api) {
5707
5751
  }
5708
5752
 
5709
5753
  // src/harness/cursor/local.ts
5754
+ import { existsSync as existsSync6 } from "node:fs";
5710
5755
  import { stat as stat4 } from "node:fs/promises";
5711
5756
  import { homedir as homedir8 } from "node:os";
5712
5757
  import path4 from "node:path";
5758
+ import { Worker } from "node:worker_threads";
5713
5759
  function dataPath(env = process.env, home = homedir8(), platform4 = process.platform) {
5714
5760
  if (env.CURSOR_DATA_PATH) return path4.resolve(env.CURSOR_DATA_PATH);
5715
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");
@@ -5792,11 +5838,66 @@ async function sourceStamp(root) {
5792
5838
  );
5793
5839
  return values.join("/");
5794
5840
  }
5841
+ var localReads = /* @__PURE__ */ new Map();
5795
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) {
5796
5893
  const stats = emptyScanStats();
5797
5894
  const out = { sessions: [], complete: true, stats };
5798
- if (!await hasLocalSource(root)) return out;
5799
- 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");
5800
5901
  let context;
5801
5902
  try {
5802
5903
  const reader = await import("cursor-history");
@@ -5812,11 +5913,16 @@ async function readLocal(root = dataPath(), onProgress) {
5812
5913
  const config = { ...options, readContext: context };
5813
5914
  let offset = 0;
5814
5915
  while (true) {
5916
+ const pageDone = traceTimer(
5917
+ offset === 0 ? "cursor session listing" : "cursor session page"
5918
+ );
5815
5919
  const page = await reader.listSessionSummaries({
5816
5920
  ...config,
5817
5921
  offset,
5818
5922
  limit: 100
5819
5923
  });
5924
+ pageDone(`${page.data.length} of ${page.pagination.total} sessions`);
5925
+ if (offset === 0) onProgress?.(0, page.pagination.total);
5820
5926
  for (const summary of page.data) {
5821
5927
  stats.filesFound++;
5822
5928
  if (summary.resolutionState === "ambiguous") {
@@ -5829,7 +5935,7 @@ async function readLocal(root = dataPath(), onProgress) {
5829
5935
  const tokens = await readTokenEvidence(root, session);
5830
5936
  out.sessions.push({ session, tokens });
5831
5937
  stats.filesRead++;
5832
- onProgress?.(stats.filesRead);
5938
+ onProgress?.(stats.filesRead, page.pagination.total);
5833
5939
  } catch {
5834
5940
  out.complete = false;
5835
5941
  stats.filesUnreadable++;
@@ -5855,8 +5961,19 @@ async function readLocal(root = dataPath(), onProgress) {
5855
5961
  }
5856
5962
  }
5857
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
+ );
5858
5967
  return out;
5859
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
+ }
5860
5977
 
5861
5978
  // src/harness/cursor/account.ts
5862
5979
  var digest = (value) => createHash("sha256").update(value).digest("hex");
@@ -7786,7 +7903,7 @@ async function scan6(agg, opts = {}) {
7786
7903
  }
7787
7904
  agg.files++;
7788
7905
  stats.filesRead++;
7789
- if (opts.onProgress && agg.files % 200 === 0) opts.onProgress(agg.files);
7906
+ if (opts.onProgress && agg.files % 20 === 0) opts.onProgress(agg.files);
7790
7907
  try {
7791
7908
  const verdict = await ingestFile3(agg, fold, file, opts.sinceMs);
7792
7909
  if (verdict === "foreign") {
@@ -7924,7 +8041,10 @@ function detectionSinceMs(now = Date.now()) {
7924
8041
  async function detectedAdapters(sinceMs = detectionSinceMs()) {
7925
8042
  const out = [];
7926
8043
  for (const adapter of HARNESS_ADAPTERS) {
7927
- 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);
7928
8048
  }
7929
8049
  return out;
7930
8050
  }
@@ -7961,7 +8081,7 @@ function findSkillSource(fromDir = dirname3(fileURLToPath(import.meta.url))) {
7961
8081
  let dir = fromDir;
7962
8082
  for (let i = 0; i < 4; i++) {
7963
8083
  const candidate = join6(dir, "skills", "aistack-sync");
7964
- if (existsSync6(join6(candidate, "SKILL.md"))) return candidate;
8084
+ if (existsSync7(join6(candidate, "SKILL.md"))) return candidate;
7965
8085
  const parent = dirname3(dir);
7966
8086
  if (parent === dir) break;
7967
8087
  dir = parent;
@@ -8072,7 +8192,7 @@ async function offerConnectUpsell(deps = {}) {
8072
8192
  }
8073
8193
 
8074
8194
  // src/commands/create.ts
8075
- 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";
8076
8196
  import { dirname as dirname4, join as join7 } from "node:path";
8077
8197
  import * as p4 from "@clack/prompts";
8078
8198
  async function createCommand() {
@@ -8133,7 +8253,7 @@ async function createCommand() {
8133
8253
  const skipped = [];
8134
8254
  for (const f of localFiles) {
8135
8255
  const fullPath = join7(cwd, f.path);
8136
- if (existsSync7(fullPath)) {
8256
+ if (existsSync8(fullPath)) {
8137
8257
  const existing = readFileSync8(fullPath, "utf-8");
8138
8258
  skipped.push({ path: f.path, differs: existing !== f.content });
8139
8259
  } else {
@@ -8267,7 +8387,7 @@ import * as p7 from "@clack/prompts";
8267
8387
 
8268
8388
  // src/autosync/codexHook.ts
8269
8389
  import { createHash as createHash3 } from "node:crypto";
8270
- 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";
8271
8391
  import { homedir as homedir15 } from "node:os";
8272
8392
  import { dirname as dirname5, join as join8 } from "node:path";
8273
8393
  import { parse } from "smol-toml";
@@ -8285,7 +8405,7 @@ function isOurs(entry) {
8285
8405
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
8286
8406
  }
8287
8407
  function readHooksJson(file) {
8288
- if (!existsSync8(file)) return { settings: {} };
8408
+ if (!existsSync9(file)) return { settings: {} };
8289
8409
  try {
8290
8410
  const raw = JSON.parse(readFileSync9(file, "utf-8"));
8291
8411
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -8318,7 +8438,7 @@ function installCodexAutoSyncHook(file = codexHooksFile()) {
8318
8438
  return { ok: true, message: CODEX_TRUST_INSTRUCTION };
8319
8439
  }
8320
8440
  function removeCodexAutoSyncHook(file = codexHooksFile()) {
8321
- if (!existsSync8(file))
8441
+ if (!existsSync9(file))
8322
8442
  return { ok: true, message: "no Codex hook to remove" };
8323
8443
  const read3 = readHooksJson(file);
8324
8444
  if ("error" in read3) return { ok: false, message: read3.error };
@@ -8412,12 +8532,12 @@ function canonicalJson2(value) {
8412
8532
  import * as p6 from "@clack/prompts";
8413
8533
 
8414
8534
  // src/autosync/cursorHook.ts
8415
- 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";
8416
8536
  import { homedir as homedir17, platform as platform2 } from "node:os";
8417
8537
  import { dirname as dirname7, join as join10 } from "node:path";
8418
8538
 
8419
8539
  // src/autosync/hook.ts
8420
- 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";
8421
8541
  import { homedir as homedir16 } from "node:os";
8422
8542
  import { dirname as dirname6, join as join9 } from "node:path";
8423
8543
  var CLAUDE_SETTINGS_FILE = join9(homedir16(), ".claude", "settings.json");
@@ -8426,7 +8546,7 @@ function isOurs2(entry) {
8426
8546
  return typeof entry.command === "string" && entry.command.includes("@use-aistack/cli") && entry.command.includes("sync --auto");
8427
8547
  }
8428
8548
  function readClaudeSettings(file) {
8429
- if (!existsSync9(file)) return { settings: {} };
8549
+ if (!existsSync10(file)) return { settings: {} };
8430
8550
  try {
8431
8551
  const raw = JSON.parse(readFileSync10(file, "utf-8"));
8432
8552
  if (raw && typeof raw === "object" && !Array.isArray(raw)) {
@@ -8457,7 +8577,7 @@ function installAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
8457
8577
  return { ok: true, message: `SessionStart hook written to ${file}` };
8458
8578
  }
8459
8579
  function removeAutoSyncHook(file = CLAUDE_SETTINGS_FILE) {
8460
- if (!existsSync9(file)) return { ok: true, message: "no hook to remove" };
8580
+ if (!existsSync10(file)) return { ok: true, message: "no hook to remove" };
8461
8581
  const read3 = readClaudeSettings(file);
8462
8582
  if ("error" in read3) return { ok: false, message: read3.error };
8463
8583
  const settings = read3.settings;
@@ -8503,7 +8623,7 @@ function cursorHookCommand(os = platform2()) {
8503
8623
  return `${detach} sh -c 'export AISTACK_HOOK_SOURCE=cursor; ${AUTO_SYNC_HOOK_COMMAND}' </dev/null >/dev/null 2>&1 &`;
8504
8624
  }
8505
8625
  function read(file) {
8506
- if (!existsSync10(file)) return {};
8626
+ if (!existsSync11(file)) return {};
8507
8627
  const value = JSON.parse(readFileSync11(file, "utf8"));
8508
8628
  if (!value || typeof value !== "object" || Array.isArray(value))
8509
8629
  throw new Error("expected a JSON object");
@@ -8567,7 +8687,7 @@ function cursorAutoSyncHookInstalled(file = CURSOR_HOOK_FILE) {
8567
8687
 
8568
8688
  // src/autosync/grokHook.ts
8569
8689
  import {
8570
- existsSync as existsSync11,
8690
+ existsSync as existsSync12,
8571
8691
  mkdirSync as mkdirSync6,
8572
8692
  readFileSync as readFileSync12,
8573
8693
  unlinkSync,
@@ -8591,7 +8711,7 @@ function grokHookCommand(os = platform3()) {
8591
8711
  return `setsid nohup sh -c 'export AISTACK_HOOK_SOURCE=grok; ${SYNC_COMMAND}' >/dev/null 2>&1 &`;
8592
8712
  }
8593
8713
  function readHookFile(file) {
8594
- if (!existsSync11(file)) return { value: {} };
8714
+ if (!existsSync12(file)) return { value: {} };
8595
8715
  try {
8596
8716
  const value = JSON.parse(readFileSync12(file, "utf-8"));
8597
8717
  if (value && typeof value === "object" && !Array.isArray(value)) {
@@ -8650,7 +8770,7 @@ function installGrokAutoSyncHook(file = GROK_HOOK_FILE, os = platform3()) {
8650
8770
  };
8651
8771
  }
8652
8772
  function removeGrokAutoSyncHook(file = GROK_HOOK_FILE) {
8653
- if (!existsSync11(file))
8773
+ if (!existsSync12(file))
8654
8774
  return { ok: true, message: "no Grok Build hook to remove" };
8655
8775
  const read3 = readHookFile(file);
8656
8776
  if ("error" in read3) return { ok: false, message: read3.error };
@@ -9498,7 +9618,7 @@ function buildWorkflowExtraction(harnessWorkflows, git, utcOffsetMinutes = machi
9498
9618
 
9499
9619
  // src/sync/grokDateCache.ts
9500
9620
  import { createHash as createHash4 } from "node:crypto";
9501
- 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";
9502
9622
  import { homedir as homedir19 } from "node:os";
9503
9623
  import path13 from "node:path";
9504
9624
  var defaultFile = path13.join(
@@ -9511,7 +9631,7 @@ function grokCacheScope(baseUrl, stack, token) {
9511
9631
  return createHash4("sha256").update(`${baseUrl}\0${stack}\0${token}`).digest("hex");
9512
9632
  }
9513
9633
  function read2(file) {
9514
- if (!existsSync12(file)) return {};
9634
+ if (!existsSync13(file)) return {};
9515
9635
  try {
9516
9636
  const value = JSON.parse(readFileSync13(file, "utf8"));
9517
9637
  return value && typeof value === "object" ? value : {};
@@ -9796,13 +9916,13 @@ function workflowBlock(workflowDays, utcOffsetMinutes, host) {
9796
9916
  out.push(
9797
9917
  ` ${workflowDays.length} day${workflowDays.length === 1 ? "" : "s"}${first && last ? ` \xB7 ${first} to ${last}` : ""}`
9798
9918
  );
9799
- const seconds = PHASE_ORDER.map(
9919
+ const seconds2 = PHASE_ORDER.map(
9800
9920
  (phase) => withPlaybook.reduce((a, h) => a + (h.phase?.phaseSec[phase] ?? 0), 0)
9801
9921
  );
9802
- const total = seconds.reduce((a, b) => a + b, 0);
9922
+ const total = seconds2.reduce((a, b) => a + b, 0);
9803
9923
  if (total > 0) {
9804
9924
  const mix = PHASE_ORDER.map(
9805
- (phase, i) => `${phase} ${fmtPct((seconds[i] ?? 0) / total)}`
9925
+ (phase, i) => `${phase} ${fmtPct((seconds2[i] ?? 0) / total)}`
9806
9926
  ).join(" \xB7 ");
9807
9927
  out.push(` ${mix} \xB7 ${ruleVersions.join(", ")}`);
9808
9928
  }
@@ -9943,41 +10063,90 @@ async function stageSync(deps) {
9943
10063
  const now = (deps.now ?? Date.now)();
9944
10064
  const token = (deps.getTokenImpl ?? getToken)();
9945
10065
  const loadConfig = deps.loadConfigImpl ?? loadSyncConfig;
9946
- const adapters = deps.adaptersImpl ?? detectedAdapters;
10066
+ const adapters = deps.adaptersImpl ?? (() => HARNESS_ADAPTERS);
9947
10067
  const windowDays = deps.windowDays ?? DEFAULT_WINDOW_DAYS;
9948
10068
  const projectWorkspaceId = deps.getProjectWorkspaceIdImpl ?? getProjectWorkspaceId;
9949
10069
  const fetchManifest = deps.fetchManifestImpl ?? fetchDayManifest;
9950
10070
  const fetchPrices = deps.fetchPricesImpl ?? fetchPriceTable;
9951
- const progress = deps.onProgress ?? (() => {
9952
- });
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
+ };
9953
10077
  let prices = {
9954
10078
  id: BUNDLED_PRICE_TABLE_ID,
9955
10079
  origin: "bundled"
9956
10080
  };
9957
- progress("Checking prices and stack settings");
9958
- try {
9959
- const table = await fetchPrices(deps.baseUrl);
9960
- if (table) {
9961
- setActivePricer(layeredPricer(table));
9962
- prices = { id: table.id, origin: "served" };
9963
- } 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) {
9964
10099
  setActivePricer(null);
10100
+ done(`fetch failed (${describeError(error)}), bundled table`);
10101
+ step("prices", "Prices", "done", "unreachable, bundled table");
9965
10102
  }
9966
- } catch {
9967
- setActivePricer(null);
9968
- }
9969
- const { config, source } = await loadConfig({
9970
- baseUrl: deps.baseUrl,
9971
- ...token ? { token } : {}
9972
- });
9973
- let manifest = null;
9974
- if (token) {
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");
9975
10127
  try {
9976
- manifest = await fetchManifest(deps.baseUrl, token);
9977
- } catch {
9978
- 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;
9979
10143
  }
9980
- }
10144
+ };
10145
+ const [, { config, source }, manifest] = await Promise.all([
10146
+ readPrices(),
10147
+ readSettings(),
10148
+ readManifest()
10149
+ ]);
9981
10150
  const retentionDays = Math.max(
9982
10151
  1,
9983
10152
  Math.min(manifest?.retentionDays ?? MAX_DAY_WINDOW, MAX_DAY_WINDOW)
@@ -9988,17 +10157,83 @@ async function stageSync(deps) {
9988
10157
  const usageScans = [];
9989
10158
  const sinceMs = windowStartMs(now, windowDays);
9990
10159
  const daysSinceMs = windowStartMs(now, retentionDays);
9991
- const active2 = await adapters(sinceMs);
9992
- 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
+ );
9993
10232
  let dayScansComplete = true;
9994
10233
  const sessionDatesByHarness = /* @__PURE__ */ new Map();
9995
- for (const adapter of active2) {
9996
- progress(`Scanning recent ${adapter.name} usage`);
9997
- const { aggregate, stats } = await adapter.scan({
9998
- sinceMs,
9999
- publishWorkflow: false,
10000
- onProgress: (files) => progress(`Scanning recent ${adapter.name} usage \xB7 ${files} files`)
10001
- });
10234
+ for (const { adapter, recent } of readings) {
10235
+ if (!recent) continue;
10236
+ const { aggregate, stats } = recent;
10002
10237
  scanStats[adapter.name] = stats;
10003
10238
  built.push(
10004
10239
  buildPayload({
@@ -10013,13 +10248,9 @@ async function stageSync(deps) {
10013
10248
  })
10014
10249
  );
10015
10250
  }
10016
- for (const adapter of historical) {
10017
- progress(`Reading historical ${adapter.name} days`);
10018
- const { aggregate, workflow: workflow2, workflowLocal, scanComplete, sessionDates } = await adapter.scan({
10019
- sinceMs: daysSinceMs,
10020
- publishWorkflow: config.publishWorkflow,
10021
- onProgress: (files) => progress(`Reading historical ${adapter.name} days \xB7 ${files} files`)
10022
- });
10251
+ for (const { adapter, history } of readings) {
10252
+ if (!history) continue;
10253
+ const { aggregate, workflow: workflow2, workflowLocal, scanComplete, sessionDates } = history;
10023
10254
  if (scanComplete === false) dayScansComplete = false;
10024
10255
  if (adapter.name === "grok-build" || adapter.name === "cursor")
10025
10256
  sessionDatesByHarness.set(adapter.name, sessionDates ?? /* @__PURE__ */ new Map());
@@ -10036,7 +10267,8 @@ async function stageSync(deps) {
10036
10267
  const settings = (deps.getSettingsImpl ?? getSettings)();
10037
10268
  let workflow;
10038
10269
  if (workflowScans.length > 0 && config.publishWorkflow) {
10039
- progress("Reading Git history");
10270
+ step("git", "Git history", "running");
10271
+ const gitDone = traceTimer("git history");
10040
10272
  workflow = deps.gitRunnerImpl ? extractLocalWorkflow({
10041
10273
  harnesses: workflowScans,
10042
10274
  fromMs: daysSinceMs,
@@ -10047,6 +10279,12 @@ async function stageSync(deps) {
10047
10279
  fromMs: daysSinceMs,
10048
10280
  toMs: now
10049
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
+ );
10050
10288
  }
10051
10289
  const correctionDates = /* @__PURE__ */ new Set();
10052
10290
  let acknowledgePublish;
@@ -10100,8 +10338,13 @@ async function stageSync(deps) {
10100
10338
  } : void 0,
10101
10339
  CLI_VERSION
10102
10340
  );
10103
- progress("Preparing review");
10341
+ step("review", "Review", "running");
10104
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`);
10105
10348
  const keptPrivate = mergeKeptPrivate(built.map((b) => b.keptPrivate));
10106
10349
  const ctx = {
10107
10350
  body,
@@ -10140,6 +10383,15 @@ async function stageSync(deps) {
10140
10383
  ...acknowledgePublish ? { acknowledgePublish } : {}
10141
10384
  };
10142
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
+ }
10143
10395
 
10144
10396
  // src/autosync/run.ts
10145
10397
  var SYNC_LOG_FILE = join12(homedir20(), ".config", "aistack", "sync.log");
@@ -10297,8 +10549,159 @@ async function runAutoSync(deps) {
10297
10549
  }
10298
10550
  }
10299
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
+
10300
10695
  // src/commands/sync.ts
10301
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
+ }
10302
10705
  if (options.auto === true) {
10303
10706
  await runAutoSync({ baseUrl: BASE_URL });
10304
10707
  return;
@@ -10391,23 +10794,27 @@ async function syncCommand(options = {}) {
10391
10794
  }
10392
10795
  const destinationToken = token;
10393
10796
  const destinationConfig = loaded;
10394
- const s = p7.spinner();
10395
- 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
+ });
10396
10802
  let staged;
10397
10803
  try {
10398
10804
  staged = await stageSync({
10399
10805
  baseUrl: BASE_URL,
10400
10806
  getTokenImpl: () => destinationToken,
10401
10807
  loadConfigImpl: async () => destinationConfig,
10402
- onProgress: (message) => s.message(message)
10808
+ onEvent: board.handle
10403
10809
  });
10404
10810
  } catch (e) {
10405
- s.stop("Scan failed");
10811
+ board.stop();
10406
10812
  outroError(e instanceof Error ? e.message : String(e));
10407
10813
  process.exitCode = 1;
10408
10814
  return;
10409
10815
  }
10410
- s.stop("Scan complete");
10816
+ board.stop();
10817
+ const s = p7.spinner();
10411
10818
  p7.log.message(staged.summary.split("\n").map(styleSummaryLine).join("\n"));
10412
10819
  if (staged.blockedReason !== null) {
10413
10820
  outroError(staged.blockedReason);
@@ -10786,6 +11193,9 @@ program.command("sync").description("Scan, preview, and publish measured usage (
10786
11193
  ).option(
10787
11194
  "--every <hours>",
10788
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)"
10789
11199
  ).action((options) => syncCommand(options));
10790
11200
  program.command("connect").description("Install the in-session sync surface (MCP server + Skill)").argument("<harness>", 'the harness to connect ("claude")').action(connectCommand);
10791
11201
  if (!supportsNodeVersion(process.versions.node)) {