tokenusage-cli 0.4.7 → 0.5.1

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.
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+
3
+ // Detected repository URLs for projects (docs/cli-contract.md §2.4 `projects`,
4
+ // contract v3, 2026-11-06). The CLI only ever reports public GitHub / Gitee
5
+ // remotes it already canonicalised, and only the entries that differ from what
6
+ // this device last had confirmed — the server stores one row per
7
+ // (user, device, project_key), so sending the full map on every sync would
8
+ // rewrite rows for unchanged projects.
9
+ //
10
+ // Wire rules mirrored from the contract (the server validates and drops
11
+ // non-conforming entries instead of failing the batch):
12
+ // • https://github.com/<owner>/<repo> or https://gitee.com/<owner>/<repo>
13
+ // • exactly two path segments of [A-Za-z0-9._-], no credentials/port/query
14
+ // • `null` clears this device's previously reported value for the project
15
+
16
+ const fs = require("node:fs");
17
+ const fsp = require("node:fs/promises");
18
+ const path = require("node:path");
19
+ const crypto = require("node:crypto");
20
+
21
+ const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
22
+
23
+ const INGEST_SLUG = "token-usage-ingest";
24
+ const STATE_VERSION = 1;
25
+ const MAX_PROJECTS_PER_BATCH = 200;
26
+ const REPO_HOSTS = new Set(["github.com", "gitee.com"]);
27
+ const PATH_SEGMENT = /^[A-Za-z0-9._-]{1,100}$/;
28
+
29
+ /**
30
+ * Canonicalise a git remote into the contract's only accepted shape.
31
+ * Returns null for anything that is not a public GitHub / Gitee repository
32
+ * (self-hosted GitLab, enterprise hosts, local paths, credentials, ports).
33
+ */
34
+ function normalizeRepoUrl(value) {
35
+ if (typeof value !== "string") return null;
36
+ let raw = value.trim();
37
+ if (!raw) return null;
38
+
39
+ const scp = raw.match(/^[A-Za-z0-9._-]+@([^:/\\]+):(.+)$/);
40
+ if (scp) {
41
+ raw = `https://${scp[1]}/${scp[2]}`;
42
+ } else if (/^ssh:\/\//i.test(raw)) {
43
+ try {
44
+ const parsed = new URL(raw);
45
+ raw = `https://${parsed.hostname}${parsed.pathname}`;
46
+ } catch {
47
+ return null;
48
+ }
49
+ } else if (/^git:\/\//i.test(raw)) {
50
+ raw = `https://${raw.slice("git://".length)}`;
51
+ }
52
+
53
+ let parsed;
54
+ try {
55
+ parsed = new URL(raw);
56
+ } catch {
57
+ return null;
58
+ }
59
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
60
+ if (parsed.username || parsed.password || parsed.port) return null;
61
+ if (parsed.search || parsed.hash) return null;
62
+
63
+ const host = parsed.hostname.toLowerCase();
64
+ if (!REPO_HOSTS.has(host)) return null;
65
+
66
+ const segments = parsed.pathname.split("/").filter((segment) => segment.length > 0);
67
+ if (segments.length !== 2) return null;
68
+
69
+ const owner = segments[0];
70
+ let repo = segments[1];
71
+ if (/\.git$/i.test(repo)) repo = repo.slice(0, -4);
72
+ if (!PATH_SEGMENT.test(owner) || !PATH_SEGMENT.test(repo)) return null;
73
+ if (owner === "." || owner === ".." || repo === "." || repo === "..") return null;
74
+
75
+ const canonical = `https://${host}/${owner}/${repo}`;
76
+ return canonical.length <= 200 ? canonical : null;
77
+ }
78
+
79
+ function emptyState() {
80
+ return { version: STATE_VERSION, confirmed: {} };
81
+ }
82
+
83
+ function loadProjectRepoState(filePath) {
84
+ try {
85
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
86
+ if (!parsed || typeof parsed !== "object") return emptyState();
87
+ const confirmed = {};
88
+ for (const [key, value] of Object.entries(
89
+ parsed.confirmed && typeof parsed.confirmed === "object" ? parsed.confirmed : {},
90
+ )) {
91
+ if (typeof key !== "string" || !key) continue;
92
+ if (value === null || typeof value === "string") confirmed[key] = value;
93
+ }
94
+ return { version: STATE_VERSION, confirmed };
95
+ } catch {
96
+ return emptyState();
97
+ }
98
+ }
99
+
100
+ async function saveProjectRepoState(filePath, state) {
101
+ const payload = {
102
+ version: STATE_VERSION,
103
+ confirmed: Object.fromEntries(
104
+ Object.entries(state.confirmed).sort(([a], [b]) => a.localeCompare(b)),
105
+ ),
106
+ };
107
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
108
+ const tmp = `${filePath}.${crypto.randomBytes(4).toString("hex")}.tmp`;
109
+ await fsp.writeFile(tmp, JSON.stringify(payload, null, 2) + "\n", { mode: 0o600 });
110
+ await fsp.rename(tmp, filePath);
111
+ await fsp.chmod(filePath, 0o600).catch(() => {});
112
+ }
113
+
114
+ /**
115
+ * Entries this device should (re)report: new detections, moved repositories,
116
+ * and clears (a project whose remote disappeared or moved off GitHub/Gitee).
117
+ * Projects that were never confirmed and still have no repository are skipped —
118
+ * sending `null` for every local-only project would only burn requests.
119
+ */
120
+ function collectProjectRepoChanges({ projects, confirmed = {} }) {
121
+ const entries = [];
122
+ for (const [key, meta] of Object.entries(
123
+ projects && typeof projects === "object" ? projects : {},
124
+ )) {
125
+ if (typeof key !== "string" || !key || !meta || typeof meta !== "object") continue;
126
+ const hasConfirmed = Object.prototype.hasOwnProperty.call(confirmed, key);
127
+ const previous = hasConfirmed ? confirmed[key] : undefined;
128
+ const status = typeof meta.status === "string" ? meta.status : null;
129
+ const detected = status === "public_verified" || status == null
130
+ ? normalizeRepoUrl(meta.project_ref)
131
+ : null;
132
+
133
+ if (detected) {
134
+ if (detected !== previous) entries.push({ project_key: key, repo_url: detected });
135
+ continue;
136
+ }
137
+ if (hasConfirmed && previous !== null) {
138
+ entries.push({ project_key: key, repo_url: null });
139
+ }
140
+ }
141
+ return entries;
142
+ }
143
+
144
+ /** New confirmed map after the server acknowledged these entries. */
145
+ function applyProjectRepoConfirmation(confirmed, sent) {
146
+ const next = { ...confirmed };
147
+ for (const entry of sent) next[entry.project_key] = entry.repo_url;
148
+ return next;
149
+ }
150
+
151
+ async function postProjects({
152
+ baseUrl,
153
+ anonKey,
154
+ deviceToken,
155
+ entries,
156
+ fetchImpl,
157
+ signal,
158
+ }) {
159
+ const headers = {
160
+ "Content-Type": "application/json",
161
+ Accept: "application/json",
162
+ Authorization: `Bearer ${deviceToken}`,
163
+ };
164
+ if (anonKey) headers.apikey = anonKey;
165
+
166
+ return fetchFunctionResponse(
167
+ functionUrlFor(baseUrl, INGEST_SLUG),
168
+ {
169
+ method: "POST",
170
+ headers,
171
+ ...(signal ? { signal } : {}),
172
+ body: JSON.stringify({ projects: entries }),
173
+ },
174
+ fetchImpl,
175
+ );
176
+ }
177
+
178
+ /**
179
+ * Upload pending repository changes in batches of <=200. Returns
180
+ * `unsupported: true` (and leaves the state untouched) when the backend
181
+ * predates contract v3 — an old server answers a projects-only request with
182
+ * `400 No usage buckets provided`, and a retired route with 404/405. Both are
183
+ * "retry later after upgrading the backend", never a sync failure.
184
+ */
185
+ async function uploadProjectRepos({
186
+ baseUrl,
187
+ anonKey,
188
+ deviceToken,
189
+ projects,
190
+ statePath,
191
+ canUpload = () => true,
192
+ batchSize = MAX_PROJECTS_PER_BATCH,
193
+ fetchImpl,
194
+ signal,
195
+ }) {
196
+ const state = loadProjectRepoState(statePath);
197
+ const pending = collectProjectRepoChanges({
198
+ projects,
199
+ confirmed: state.confirmed,
200
+ });
201
+ if (pending.length === 0) return { pending: 0, uploaded: 0, skipped: 0, batches: 0 };
202
+ if (!canUpload()) return { pending: pending.length, uploaded: 0, skipped: 0, batches: 0, paused: true };
203
+
204
+ const limit = Math.min(Math.max(1, Math.trunc(Number(batchSize) || 1)), MAX_PROJECTS_PER_BATCH);
205
+ let uploaded = 0;
206
+ let skipped = 0;
207
+ let batches = 0;
208
+
209
+ for (let index = 0; index < pending.length; index += limit) {
210
+ const batch = pending.slice(index, index + limit);
211
+ if (!canUpload()) break;
212
+ const res = await postProjects({ baseUrl, anonKey, deviceToken, entries: batch, fetchImpl, signal });
213
+
214
+ if (!res.ok) {
215
+ const text = await res.text().catch(() => "");
216
+ if (
217
+ res.status === 404 ||
218
+ res.status === 405 ||
219
+ (res.status === 400 && text.includes("No usage buckets provided"))
220
+ ) {
221
+ return { pending: pending.length, uploaded, skipped, batches, unsupported: true };
222
+ }
223
+ const error = new Error(`repo upload failed (HTTP ${res.status}): ${text.slice(0, 300)}`);
224
+ error.status = res.status;
225
+ throw error;
226
+ }
227
+
228
+ const data = await res.json().catch(() => null);
229
+ const isCount = (value) =>
230
+ (typeof value === "number" || typeof value === "string") &&
231
+ value !== "" &&
232
+ Number.isFinite(Number(value));
233
+ if (!data || typeof data !== "object" || !isCount(data.projects_upserted)) {
234
+ const error = new Error(
235
+ `repo upload was not confirmed (HTTP ${res.status}): unexpected response body`,
236
+ );
237
+ error.status = res.status;
238
+ throw error;
239
+ }
240
+
241
+ state.confirmed = applyProjectRepoConfirmation(state.confirmed, batch);
242
+ await saveProjectRepoState(statePath, state);
243
+ uploaded += batch.length;
244
+ skipped += Number(data.projects_skipped || 0);
245
+ batches += 1;
246
+ }
247
+
248
+ return { pending: pending.length, uploaded, skipped, batches };
249
+ }
250
+
251
+ module.exports = {
252
+ MAX_PROJECTS_PER_BATCH,
253
+ applyProjectRepoConfirmation,
254
+ collectProjectRepoChanges,
255
+ loadProjectRepoState,
256
+ normalizeRepoUrl,
257
+ saveProjectRepoState,
258
+ uploadProjectRepos,
259
+ };
@@ -11314,6 +11314,34 @@ const WORKBUDDY_VARIANTS = {
11314
11314
  "workbuddy-ai": { dir: ".workbuddy-ai", envVar: "WORKBUDDY_AI_HOME" },
11315
11315
  };
11316
11316
 
11317
+ // Bump when the project pass changes how it derives a bucket's model. Version 2
11318
+ // pairs project usage with the hourly model, which is what enqueueTouchedBuckets
11319
+ // needs to emit project + residual rows; version-1 buckets have no model and can
11320
+ // never be split. An install below the current version resets only WorkBuddy's
11321
+ // project cursors and drops those model-less buckets — the totals cursors stay
11322
+ // untouched, so history is re-attributed without re-counting a single token.
11323
+ const WORKBUDDY_PROJECT_ATTRIBUTION_VERSION = 2;
11324
+
11325
+ // Remove project buckets written before the model dimension existed. Only the
11326
+ // buckets owned by the given WorkBuddy variant are touched; other sources and
11327
+ // every model-bearing bucket are left exactly as they are.
11328
+ function dropLegacyWorkbuddyProjectBuckets(projectState, variant) {
11329
+ if (!projectState || !projectState.buckets || typeof projectState.buckets !== "object") {
11330
+ return 0;
11331
+ }
11332
+ const source = normalizeSourceInput(variant) || DEFAULT_SOURCE;
11333
+ let removed = 0;
11334
+ for (const [key, bucket] of Object.entries(projectState.buckets)) {
11335
+ if (!bucket || typeof bucket !== "object") continue;
11336
+ // A legacy bucket is exactly the one getProjectBucket wrote with model == null.
11337
+ if (bucket.model != null) continue;
11338
+ if ((normalizeSourceInput(bucket.source) || DEFAULT_SOURCE) !== source) continue;
11339
+ delete projectState.buckets[key];
11340
+ removed += 1;
11341
+ }
11342
+ return removed;
11343
+ }
11344
+
11317
11345
  function resolveWorkbuddyVariant(variant) {
11318
11346
  return Object.prototype.hasOwnProperty.call(WORKBUDDY_VARIANTS, variant)
11319
11347
  ? variant
@@ -11617,13 +11645,27 @@ async function parseWorkbuddyIncremental({
11617
11645
  const projectTouchedBuckets = projectEnabled ? new Set() : null;
11618
11646
  const projectMetaCache = projectEnabled ? new Map() : null;
11619
11647
  const publicRepoCache = projectEnabled ? new Map() : null;
11648
+ // Version 2 pairs every project bucket with the hourly model so the split in
11649
+ // enqueueTouchedBuckets can emit project rows (a model-less bucket is never
11650
+ // splittable). An install still carrying version-1 state rescan its WorkBuddy
11651
+ // history in the project pass alone — the totals cursors are untouched, so no
11652
+ // token is counted twice.
11653
+ const projectAttributionNeedsRescan =
11654
+ Number(workbuddyState.projectAttributionVersion || 0) < WORKBUDDY_PROJECT_ATTRIBUTION_VERSION;
11620
11655
  const projectSeenIds = new Set(
11621
- Array.isArray(workbuddyState.projectSeenIds) ? workbuddyState.projectSeenIds : [],
11656
+ !projectAttributionNeedsRescan && Array.isArray(workbuddyState.projectSeenIds)
11657
+ ? workbuddyState.projectSeenIds
11658
+ : [],
11622
11659
  );
11623
11660
  const projectFileOffsets =
11624
- workbuddyState.projectFileOffsets && typeof workbuddyState.projectFileOffsets === "object"
11661
+ !projectAttributionNeedsRescan &&
11662
+ workbuddyState.projectFileOffsets &&
11663
+ typeof workbuddyState.projectFileOffsets === "object"
11625
11664
  ? { ...workbuddyState.projectFileOffsets }
11626
11665
  : {};
11666
+ if (projectState && projectAttributionNeedsRescan) {
11667
+ dropLegacyWorkbuddyProjectBuckets(projectState, variant);
11668
+ }
11627
11669
  let projectBucketsQueued = 0;
11628
11670
  let projectCursorUpdated = false;
11629
11671
 
@@ -11644,6 +11686,7 @@ async function parseWorkbuddyIncremental({
11644
11686
  if (files.length === 0 && !dbExists) {
11645
11687
  cursors[variant] = {
11646
11688
  ...workbuddyState,
11689
+ projectAttributionVersion: WORKBUDDY_PROJECT_ATTRIBUTION_VERSION,
11647
11690
  seenIds: Array.from(seenIds),
11648
11691
  seenTraceIds: Array.from(seenTraceIds),
11649
11692
  tracedSessionIds: Array.from(tracedSessionIds),
@@ -11919,16 +11962,27 @@ async function parseWorkbuddyIncremental({
11919
11962
  const bucketStart = toUtcHalfHourStart(new Date(tsMs).toISOString());
11920
11963
  if (!bucketStart) return;
11921
11964
 
11965
+ // Same model expression as the totals pass, so the project bucket and
11966
+ // the hourly bucket it belongs to always share one model key. Without
11967
+ // this the split can never match the hour and WorkBuddy usage stays
11968
+ // unattributed forever.
11969
+ const projectModel =
11970
+ normalizeModelInput(provider.model) ||
11971
+ normalizeModelInput(provider.requestModelId) ||
11972
+ normalizeModelInput(entry.model) ||
11973
+ fallbackModel;
11922
11974
  const projectBucket = getProjectBucket(
11923
11975
  projectState,
11924
11976
  projectKey,
11925
11977
  source,
11926
- null,
11978
+ projectModel,
11927
11979
  bucketStart,
11928
11980
  projectRef,
11929
11981
  );
11930
11982
  addTotals(projectBucket.totals, delta);
11931
- projectTouchedBuckets.add(projectBucketKey(projectKey, source, null, bucketStart));
11983
+ projectTouchedBuckets.add(
11984
+ projectBucketKey(projectKey, source, projectModel, bucketStart),
11985
+ );
11932
11986
  },
11933
11987
  );
11934
11988
 
@@ -12236,6 +12290,7 @@ async function parseWorkbuddyIncremental({
12236
12290
  }
12237
12291
  cursors[variant] = {
12238
12292
  ...workbuddyState,
12293
+ projectAttributionVersion: WORKBUDDY_PROJECT_ATTRIBUTION_VERSION,
12239
12294
  seenIds: cappedSeen,
12240
12295
  seenTraceIds: cappedSeenTraceIds,
12241
12296
  tracedSessionIds: cappedTracedSessionIds,
@@ -26309,4 +26364,8 @@ module.exports = {
26309
26364
  commandCodeUsageToTotals,
26310
26365
  extractCommandCodeSessionUsage,
26311
26366
  parseCommandCodeIncremental,
26367
+
26368
+ // WorkBuddy project attribution (v2: project buckets carry the hourly model)
26369
+ WORKBUDDY_PROJECT_ATTRIBUTION_VERSION,
26370
+ dropLegacyWorkbuddyProjectBuckets,
26312
26371
  };
@@ -227,6 +227,24 @@ function formatTaskStartBoundary(now = new Date()) {
227
227
  return `${next.getFullYear()}-${pad(next.getMonth() + 1)}-${pad(next.getDate())}T${pad(next.getHours())}:00:00`;
228
228
  }
229
229
 
230
+ /**
231
+ * The user a logon trigger fires for. `schtasks` resolves a `<LogonTrigger>`
232
+ * without `<UserId>` to "any user" and then refuses the definition with
233
+ * "Access is denied" unless the caller is elevated — which turned the whole
234
+ * definition into a plain hourly task on a normal install (2026-11-06,
235
+ * DESKTOP-MHFON1J). Naming the current user keeps the catch-up/retry
236
+ * definition registrable without admin.
237
+ */
238
+ function windowsUserId({ env = process.env } = {}) {
239
+ if (env.USERDOMAIN && env.USERNAME) return `${env.USERDOMAIN}\\${env.USERNAME}`;
240
+ try {
241
+ const name = os.userInfo().username;
242
+ return name ? `${os.hostname()}\\${name}` : "";
243
+ } catch {
244
+ return "";
245
+ }
246
+ }
247
+
230
248
  /**
231
249
  * Task definition registered with `schtasks /Create /XML`. Compared to the
232
250
  * plain `-SC HOURLY` registration this adds:
@@ -237,7 +255,7 @@ function formatTaskStartBoundary(now = new Date()) {
237
255
  * MultipleInstancesPolicy=IgnoreNew keeps a second pass from racing the first
238
256
  * (the CLI also holds sync.lock; this is the outer guard).
239
257
  */
240
- function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary() }) {
258
+ function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary(), userId, logonTrigger = true }) {
241
259
  // Element order mirrors what `schtasks /Query /XML` exports, so the
242
260
  // definition passes the scheduler's validation on every Windows build.
243
261
  return [
@@ -260,9 +278,14 @@ function buildWindowsTaskXml({ vbsPath, startBoundary = formatTaskStartBoundary(
260
278
  " <DaysInterval>1</DaysInterval>",
261
279
  " </ScheduleByDay>",
262
280
  " </CalendarTrigger>",
263
- " <LogonTrigger>",
264
- " <Enabled>true</Enabled>",
265
- " </LogonTrigger>",
281
+ ...(logonTrigger
282
+ ? [
283
+ " <LogonTrigger>",
284
+ ...(userId ? [` <UserId>${xmlEscape(userId)}</UserId>`] : []),
285
+ " <Enabled>true</Enabled>",
286
+ " </LogonTrigger>",
287
+ ]
288
+ : []),
266
289
  " </Triggers>",
267
290
  " <Principals>",
268
291
  ' <Principal id="Author">',
@@ -377,8 +400,12 @@ function buildSystemdTimer({ intervalSeconds = SCHEDULE_INTERVAL_SECONDS } = {})
377
400
  ].join("\n");
378
401
  }
379
402
 
403
+ function runCapture(command, args) {
404
+ return execFileSync(command, args, { stdio: "pipe", windowsHide: true });
405
+ }
406
+
380
407
  function run(command, args) {
381
- execFileSync(command, args, { stdio: "pipe", windowsHide: true });
408
+ runCapture(command, args);
382
409
  }
383
410
 
384
411
  // `stdio: "pipe"` keeps the child's own output on `error.stderr` / `stdout`,
@@ -484,35 +511,54 @@ function registerAutoSyncSchedule({
484
511
  return { registered: false, platform: kind, label, reason: "unsupported_platform" };
485
512
  }
486
513
 
487
- function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs, now = new Date() }) {
514
+ function registerWindowsScheduledTask({ binDir, cliJs = cliEntryPath(), nodeExe = process.execPath, fallbackCliJs, now = new Date(), userId = windowsUserId() }) {
488
515
  if (!isWindows()) return { registered: false, reason: "not_windows" };
489
516
  try {
490
517
  const vbsPath = writeHiddenRunner({ binDir, nodeExe, cliJs, fallbackCliJs });
491
518
  const xmlPath = taskXmlPathFor(binDir);
492
- const xml = buildWindowsTaskXml({ vbsPath, startBoundary: formatTaskStartBoundary(now) });
519
+ const startBoundary = formatTaskStartBoundary(now);
493
520
  // schtasks only accepts a Unicode (UTF-16) definition file.
494
- fs.writeFileSync(xmlPath, `\uFEFF${xml}`, { encoding: "utf16le", mode: 0o600 });
495
- try {
521
+ const createFromXml = (options) => {
522
+ const xml = buildWindowsTaskXml({ vbsPath, startBoundary, ...options });
523
+ fs.writeFileSync(xmlPath, `\uFEFF${xml}`, { encoding: "utf16le", mode: 0o600 });
496
524
  run("schtasks", ["/Create", "/F", "/TN", TASK_NAME, "/XML", xmlPath]);
525
+ };
526
+ try {
527
+ createFromXml({ userId });
497
528
  return { registered: true, vbsPath, xmlPath };
498
- } catch (xmlError) {
499
- // Locked-down policies and older builds can reject a custom definition;
500
- // fall back to the plain hourly trigger (loses catch-up/retry but still
501
- // collects), and say so instead of reporting a clean install.
502
- run("schtasks", [
503
- "/Create", "/F",
504
- "/SC", "HOURLY", "/MO", "1",
505
- "/TN", TASK_NAME,
506
- "/TR", `wscript.exe "${vbsPath}"`,
507
- ]);
508
- return {
509
- registered: true,
510
- degraded: true,
511
- reason: "xml_rejected",
512
- detail: errorText(xmlError),
513
- vbsPath,
514
- xmlPath,
515
- };
529
+ } catch (logonError) {
530
+ // A policy or older build can still refuse the logon trigger outright.
531
+ // Retry with the hourly definition alone: catch-up and retry survive,
532
+ // only the logon pass is gone — better than the plain hourly task.
533
+ try {
534
+ createFromXml({ userId, logonTrigger: false });
535
+ return {
536
+ registered: true,
537
+ degraded: true,
538
+ reason: "logon_trigger_rejected",
539
+ detail: errorText(logonError),
540
+ vbsPath,
541
+ xmlPath,
542
+ };
543
+ } catch (xmlError) {
544
+ // Locked-down policies and older builds can reject a custom definition;
545
+ // fall back to the plain hourly trigger (loses catch-up/retry but still
546
+ // collects), and say so instead of reporting a clean install.
547
+ run("schtasks", [
548
+ "/Create", "/F",
549
+ "/SC", "HOURLY", "/MO", "1",
550
+ "/TN", TASK_NAME,
551
+ "/TR", `wscript.exe "${vbsPath}"`,
552
+ ]);
553
+ return {
554
+ registered: true,
555
+ degraded: true,
556
+ reason: "xml_rejected",
557
+ detail: errorText(xmlError),
558
+ vbsPath,
559
+ xmlPath,
560
+ };
561
+ }
516
562
  }
517
563
  } catch (error) {
518
564
  return { registered: false, reason: errorText(error) };
@@ -587,6 +633,88 @@ function scheduleState({ home = os.homedir(), platform = process.platform } = {}
587
633
  return "unknown";
588
634
  }
589
635
 
636
+ /**
637
+ * What the *registered* schedule actually does. `init` prints the summary once,
638
+ * but a downgraded definition only shows up later as a missed catch-up after
639
+ * sleep — 0.5.0 silently fell back to the plain hourly task on every
640
+ * non-elevated Windows install, and `doctor` had no way to say so. Read the
641
+ * live definition (not the on-disk copy, which a later `init` may have
642
+ * rewritten) and report the reduced feature set.
643
+ */
644
+ function inspectAutoSyncSchedule({
645
+ home = os.homedir(),
646
+ platform = process.platform,
647
+ exec = runCapture,
648
+ exists = fs.existsSync,
649
+ readFile = (file) => fs.readFileSync(file, "utf8"),
650
+ } = {}) {
651
+ const kind = schedulePlatform(platform);
652
+ const label = scheduleLabel(platform);
653
+ if (kind === "windows") {
654
+ let xml;
655
+ try {
656
+ xml = decodeStream(exec("schtasks", ["/Query", "/TN", TASK_NAME, "/XML"]));
657
+ } catch (error) {
658
+ return { platform: kind, label, state: "missing", detail: errorText(error) };
659
+ }
660
+ const features = {
661
+ catchUp: /<StartWhenAvailable>\s*true\s*</i.test(xml),
662
+ logon: /<LogonTrigger>/.test(xml),
663
+ retry: /<RestartOnFailure>/.test(xml),
664
+ unlimited: /<ExecutionTimeLimit>\s*PT0S\s*</i.test(xml),
665
+ };
666
+ const missing = [];
667
+ if (!features.catchUp) missing.push("catch-up");
668
+ if (!features.logon) missing.push("logon trigger");
669
+ if (!features.retry) missing.push("retry");
670
+ if (!features.unlimited) missing.push("unlimited runtime");
671
+ return {
672
+ platform: kind,
673
+ label,
674
+ state: "registered",
675
+ enhanced: missing.length === 0,
676
+ missing,
677
+ detail: missing.length
678
+ ? `reduced definition (no ${missing.join(", ")})`
679
+ : "enhanced definition (catch-up, logon, retry)",
680
+ };
681
+ }
682
+ if (kind === "macos") {
683
+ const plistPath = launchAgentPath(home);
684
+ if (!exists(plistPath)) return { platform: kind, label, state: "missing", path: plistPath };
685
+ return {
686
+ platform: kind,
687
+ label,
688
+ state: "registered",
689
+ enhanced: true,
690
+ missing: [],
691
+ path: plistPath,
692
+ detail: "launchd agent installed",
693
+ };
694
+ }
695
+ if (kind === "linux") {
696
+ const timerPath = systemdTimerPath(home);
697
+ if (!exists(timerPath)) return { platform: kind, label, state: "missing", path: timerPath };
698
+ let timer = "";
699
+ try {
700
+ timer = readFile(timerPath);
701
+ } catch {
702
+ /* unreadable is reported below as the reduced state */
703
+ }
704
+ const persistent = /Persistent\s*=\s*true/i.test(timer);
705
+ return {
706
+ platform: kind,
707
+ label,
708
+ state: "registered",
709
+ enhanced: persistent,
710
+ missing: persistent ? [] : ["persistent timer"],
711
+ path: timerPath,
712
+ detail: persistent ? "user timer (Persistent=true)" : "user timer (no Persistent=true)",
713
+ };
714
+ }
715
+ return { platform: kind, label, state: "unsupported" };
716
+ }
717
+
590
718
  /**
591
719
  * Best-effort enable/disable of the registered schedule (pause/resume).
592
720
  * "Not registered" is an expected, non-fatal state: the pause flag still
@@ -724,13 +852,21 @@ function scheduleDetailLine(value, max = 100) {
724
852
  return clipLine(firstLine(value), max);
725
853
  }
726
854
 
855
+ // What each degraded registration actually lost, so the summary names the
856
+ // real cost instead of one blanket "no catch-up/retry".
857
+ const DEGRADED_NOTES = {
858
+ xml_rejected: "no catch-up/retry settings",
859
+ logon_trigger_rejected: "catch-up/retry kept, no logon trigger",
860
+ };
861
+
727
862
  function formatScheduleRegistration(outcome) {
728
863
  if (!outcome) return "not registered";
729
864
  if (outcome.registered) {
730
865
  const when = "hourly, hidden window";
731
866
  if (outcome.degraded) {
732
867
  const why = scheduleDetailLine(outcome.detail);
733
- return `${outcome.label}: ${when} (degraded: ${outcome.reason}${why ? ` — ${why}` : ""}; no catch-up/retry settings)`;
868
+ const note = DEGRADED_NOTES[outcome.reason] || "reduced scheduling settings";
869
+ return `${outcome.label}: ${when} (degraded: ${outcome.reason}${why ? ` — ${why}` : ""}; ${note})`;
734
870
  }
735
871
  return `${outcome.label}: ${when} (pause/resume toggles it)`;
736
872
  }
@@ -786,11 +922,13 @@ module.exports = {
786
922
  buildSystemdService,
787
923
  buildSystemdTimer,
788
924
  formatTaskStartBoundary,
925
+ windowsUserId,
789
926
  registerAutoSyncSchedule,
790
927
  registerWindowsScheduledTask,
791
928
  registerLaunchAgent,
792
929
  registerSystemdTimer,
793
930
  scheduleState,
931
+ inspectAutoSyncSchedule,
794
932
  scheduleLabel,
795
933
  setAutoSyncEnabled,
796
934
  deleteAutoSyncSchedule,