@magicpixelart/cli 0.3.3 → 0.4.0

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.
@@ -1,16 +1,19 @@
1
1
  import kleur from 'kleur';
2
2
  import ora from 'ora';
3
3
  import { createHash } from 'node:crypto';
4
- import { mkdir, writeFile, unlink, readdir, rm, rename } from 'node:fs/promises';
4
+ import { mkdir, writeFile, unlink, rename } from 'node:fs/promises';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { dirname, relative, resolve } from 'node:path';
7
7
  import { loadConfig, loadState, saveState } from '../config.js';
8
8
  import { fetchAllManifest, fetchAssetBytes, ApiError } from '../api.js';
9
9
  import { fileSha256 } from '../util/hash.js';
10
- import { assetDiskPath, assetDiskPathFromKey } from '../util/paths.js';
10
+ import { assetDiskPath, assetDiskPathFromKey, pruneEmptyDirs, walkOutDirPngs } from '../util/paths.js';
11
11
  import { createLimit } from '../util/limit.js';
12
12
  import { emitTypedIndex, ensureAgentsDoc, scanDiskAssets } from '../util/emitIndex.js';
13
13
  import { assertPathInsideRoot, tmpPathFor } from '../util/security.js';
14
+ import { friendlyFsError } from '../util/errors.js';
15
+ import { maxIsoTimestamp } from '../util/iso.js';
16
+ import { formatBytes } from '../util/format.js';
14
17
  export async function syncCommand(opts) {
15
18
  if (opts.watch) {
16
19
  await watchLoop(opts);
@@ -23,9 +26,9 @@ async function watchLoop(opts) {
23
26
  // sprites in MagicPixel and watching them refresh in their game's dev
24
27
  // server. Incremental polls send `?since=<lastSync>` so an empty manifest
25
28
  // round-trip is cheap (a single HTTP HEAD-sized response with `count: 0`).
26
- // Floor stays at 2s to keep accidental thrashing in check; users who need
27
- // less can pass `--watch 5`.
28
- const intervalSec = typeof opts.watch === 'string' ? Math.max(2, parseInt(opts.watch, 10) || 2) : 2;
29
+ // Commander already validated the numeric value (2–3600); the `?? 2`
30
+ // covers the bare boolean `-w` form.
31
+ const intervalSec = typeof opts.watch === 'string' ? parseInt(opts.watch, 10) : 2;
29
32
  // Header — print once on start. Project/asset count is best-effort; if the
30
33
  // first manifest fetch fails we still want the loop to come up and retry.
31
34
  let headerCount = null;
@@ -40,43 +43,84 @@ async function watchLoop(opts) {
40
43
  console.log(` Edit at: ${kleur.cyan('https://magicpixel.art')}`);
41
44
  if (headerCount !== null)
42
45
  console.log(kleur.dim(` Sprites: ${headerCount}`));
43
- console.log(kleur.dim(` Polling: every ${intervalSec}s · Stop: Ctrl+C`));
46
+ console.log(kleur.dim(` Polling: every ${intervalSec}s (slows when idle) · Stop: Ctrl+C`));
44
47
  console.log();
45
48
  let stopping = false;
46
49
  let inFlight = false;
47
- let resolveIdle = null;
48
50
  let backoffSec = intervalSec;
49
51
  let pausedForAuth = false;
52
+ // Mirrors pausedForAuth for the network-offline path: once we've told the
53
+ // user "MagicPixel is offline", the next successful tick prints a single
54
+ // "back online" recovery line. Without this flag a user who walked away
55
+ // during an outage has no signal that things are healthy again.
56
+ let pausedForNetwork = false;
57
+ // After this many consecutive 401/403s we give up and exit non-zero so a
58
+ // parent process (Vite plugin, systemd, pm2) can tell the watcher is
59
+ // genuinely broken (revoked key) rather than transiently blipped.
60
+ const MAX_AUTH_FAILURES = 5;
61
+ let consecutiveAuthFailures = 0;
50
62
  // Adaptive idle backoff: after a few minutes of nothing-to-do we slow the
51
- // poll from 2s → 5s → 10s so a dev who walked away isn't hammering the
52
- // manifest endpoint. ANY change OR error resets this back to intervalSec,
63
+ // poll from intervalSec → 5s → 10s so a dev who walked away isn't hammering
64
+ // the manifest endpoint. ANY change OR error resets this back to intervalSec,
53
65
  // so the "edit → see it" promise stays intact the moment the user comes
54
66
  // back. Error backoff (2→60s) is separate and continues to win.
55
67
  let consecutiveIdleTicks = 0;
56
- const onSigint = () => {
68
+ // Thresholds in seconds (NOT ticks) so a `--watch 10` user gets the same
69
+ // ~3 min / ~15 min UX as a default `--watch 2` user. Previously these were
70
+ // tick counts (90 / 300) which made the slowdown timing scale with intervalSec.
71
+ const IDLE_SOFT_BACKOFF_SECONDS = 180;
72
+ const IDLE_HARD_BACKOFF_SECONDS = 900;
73
+ // Cancellable idle sleep — `onStopSignal` calls `wakeStop()` so the next
74
+ // tick exits immediately instead of waiting out the full backoff (which can
75
+ // be 60s at the error ceiling). Initialised to a no-op so the first
76
+ // pre-loop `await tick()` is safe even before the first sleep.
77
+ let wakeStop = () => { };
78
+ // Handle both SIGINT (Ctrl+C) and SIGTERM (`kill`, `docker stop`, systemd,
79
+ // pm2). Without the SIGTERM listener a supervisor-managed watcher would die
80
+ // mid-sync without draining in-flight work or preserving the exit code.
81
+ const onStopSignal = (signal) => {
57
82
  if (stopping)
58
83
  return;
59
84
  stopping = true;
85
+ wakeStop();
60
86
  process.stdout.write('\x1b[2K\r');
61
87
  if (inFlight) {
62
- console.log(kleur.dim('[watch] finishing current sync… (Ctrl+C again to force quit)'));
63
- process.once('SIGINT', () => process.exit(130));
88
+ console.log(kleur.dim(`[watch] finishing current sync… (${signal} again to force quit)`));
89
+ process.once(signal, () => process.exit(signal === 'SIGINT' ? 130 : 143));
64
90
  }
65
91
  else {
66
- console.log(kleur.dim('[watch] stopped.'));
67
- process.exit(0);
92
+ if (!opts.quiet)
93
+ console.log(kleur.dim('[watch] stopped.'));
94
+ // Preserve any exit code already set by a prior failed tick.
95
+ process.exit(process.exitCode ?? 0);
68
96
  }
69
97
  };
70
- process.on('SIGINT', onSigint);
98
+ process.on('SIGINT', onStopSignal);
99
+ process.on('SIGTERM', onStopSignal);
71
100
  const tick = async () => {
72
101
  if (inFlight || stopping)
73
102
  return;
74
103
  inFlight = true;
75
104
  try {
76
105
  const r = await runOnce({ ...opts, watch: false }, { watchMode: true });
77
- // Reset backoff + auth-pause flags on any successful tick.
106
+ // Reset backoff on any successful tick. Resume message fires once when
107
+ // we recover from an auth pause — `getApiKey()` re-reads
108
+ // .magicpixel/credentials on every call, so a `magicpixel login` in
109
+ // another terminal is picked up automatically by the next tick.
110
+ const wasPausedForAuth = pausedForAuth;
111
+ const wasPausedForNetwork = pausedForNetwork;
78
112
  backoffSec = intervalSec;
79
113
  pausedForAuth = false;
114
+ pausedForNetwork = false;
115
+ consecutiveAuthFailures = 0;
116
+ if (wasPausedForAuth && !opts.quiet) {
117
+ process.stdout.write('\x1b[2K\r');
118
+ console.log(`${kleur.dim(timestamp())} ${kleur.green('✓')} Key accepted again — resuming.`);
119
+ }
120
+ if (wasPausedForNetwork && !wasPausedForAuth && !opts.quiet) {
121
+ process.stdout.write('\x1b[2K\r');
122
+ console.log(`${kleur.dim(timestamp())} ${kleur.green('✓')} Back online — resuming.`);
123
+ }
80
124
  const changedCount = r.added.length + r.modified.length + r.removed.length + r.renamed.length;
81
125
  if (changedCount > 0) {
82
126
  // Snap back to the fast interval the moment anything changes.
@@ -85,11 +129,10 @@ async function watchLoop(opts) {
85
129
  }
86
130
  else {
87
131
  consecutiveIdleTicks++;
88
- // Thresholds in *ticks*; at intervalSec=2 these are ~3 min and ~15 min.
89
- if (consecutiveIdleTicks >= 300)
90
- backoffSec = Math.max(intervalSec, 10);
91
- else if (consecutiveIdleTicks >= 90)
92
- backoffSec = Math.max(intervalSec, 5);
132
+ backoffSec = nextBackoffForIdle(consecutiveIdleTicks, intervalSec, {
133
+ softSec: IDLE_SOFT_BACKOFF_SECONDS,
134
+ hardSec: IDLE_HARD_BACKOFF_SECONDS,
135
+ });
93
136
  }
94
137
  if (opts.quiet)
95
138
  return;
@@ -111,54 +154,139 @@ async function watchLoop(opts) {
111
154
  process.stdout.write('\x1b[2K\r');
112
155
  // Any error breaks the idle streak so we come back fast once it clears.
113
156
  consecutiveIdleTicks = 0;
114
- if (apiErr && (apiErr.status === 401 || apiErr.status === 403)) {
157
+ const decision = classifyTickError(err, {
158
+ backoffSec,
159
+ pausedForAuth,
160
+ pausedForNetwork,
161
+ consecutiveAuthFailures,
162
+ maxAuthFailures: MAX_AUTH_FAILURES,
163
+ });
164
+ if (decision.kind === 'auth') {
115
165
  if (!pausedForAuth) {
116
- console.log(`${kleur.dim(timestamp())} ${kleur.red('✗')} Your key looks invalid or rotated.`);
166
+ // Surface the request id (from B1) so the user can paste it into a
167
+ // support thread and we can correlate against edge function logs.
168
+ const idSuffix = apiErr?.requestId ? kleur.dim(` (request id: ${apiErr.requestId})`) : '';
169
+ console.log(`${kleur.dim(timestamp())} ${kleur.red('✗')} Your key looks invalid or rotated.${idSuffix}`);
117
170
  console.log(kleur.dim(' Fix: run `magicpixel login` (this watcher will keep retrying every 30s).'));
118
171
  }
119
172
  pausedForAuth = true;
120
- backoffSec = 30;
173
+ consecutiveAuthFailures = decision.consecutiveAuthFailures;
174
+ backoffSec = decision.nextBackoffSec;
175
+ if (decision.giveUp) {
176
+ console.log(`${kleur.dim(timestamp())} ${kleur.red('✗')} Giving up after ${MAX_AUTH_FAILURES} consecutive auth failures.`);
177
+ console.log(kleur.dim(' Fix: run `magicpixel login` with a fresh key, then restart the watcher.'));
178
+ // Surface this to /admin/errors — persistent watcher auth failure
179
+ // means a key is mass-rejected (revoked, project deleted, edge
180
+ // misconfig) and we want visibility without waiting for a support
181
+ // ping. Awaited so the report flushes before exit.
182
+ const { reportAndExit } = await import('../util/telemetry.js');
183
+ await reportAndExit(err, 'sync (watch)', 2);
184
+ }
121
185
  }
122
- else if (isNetworkError(err)) {
123
- if (backoffSec < 30) {
186
+ else if (decision.kind === 'network') {
187
+ consecutiveAuthFailures = 0;
188
+ if (decision.printMessage) {
189
+ const idSuffix = apiErr?.requestId ? kleur.dim(` (request id: ${apiErr.requestId})`) : '';
124
190
  console.log(`${kleur.dim(timestamp())} ${kleur.yellow('!')} MagicPixel is offline or your internet is. ` +
125
- `Sprites you already have still work. Retrying in ${Math.min(backoffSec * 2, 60)}s.`);
191
+ `Sprites you already have still work. Retrying in ${decision.nextBackoffSec}s.${idSuffix}`);
126
192
  }
127
- backoffSec = Math.min(backoffSec * 2, 60);
193
+ pausedForNetwork = true;
194
+ backoffSec = decision.nextBackoffSec;
128
195
  }
129
196
  else {
130
- console.log(`${kleur.dim(timestamp())} ${kleur.red('!')} ${firstLine}`);
131
- backoffSec = Math.min(backoffSec * 2, 60);
197
+ consecutiveAuthFailures = 0;
198
+ const idSuffix = apiErr?.requestId ? kleur.dim(` (request id: ${apiErr.requestId})`) : '';
199
+ console.log(`${kleur.dim(timestamp())} ${kleur.red('!')} ${firstLine}${idSuffix}`);
200
+ backoffSec = decision.nextBackoffSec;
132
201
  }
133
202
  }
134
203
  finally {
135
204
  inFlight = false;
136
- resolveIdle?.();
137
- resolveIdle = null;
138
205
  }
139
206
  };
140
207
  await tick();
141
208
  while (!stopping) {
142
- await new Promise((r) => setTimeout(r, backoffSec * 1000));
209
+ // Race the sleep against a stop signal so Ctrl+C during a long error-
210
+ // backoff (up to 60s) exits within a tick instead of after the full wait.
211
+ await new Promise((resolve) => {
212
+ const timer = setTimeout(() => {
213
+ wakeStop = () => { };
214
+ resolve();
215
+ }, backoffSec * 1000);
216
+ wakeStop = () => {
217
+ clearTimeout(timer);
218
+ wakeStop = () => { };
219
+ resolve();
220
+ };
221
+ });
143
222
  if (stopping)
144
223
  break;
224
+ // `await tick()` only returns once its `finally` runs (clearing
225
+ // `inFlight`), so the loop naturally drains the in-flight sync on Ctrl+C
226
+ // before we exit — no separate idle-promise dance required.
145
227
  await tick();
146
228
  }
147
- if (inFlight) {
148
- await new Promise((r) => {
149
- resolveIdle = r;
150
- });
151
- }
152
- console.log(kleur.dim('[watch] stopped.'));
153
- process.exit(0);
229
+ if (!opts.quiet)
230
+ console.log(kleur.dim('[watch] stopped.'));
231
+ // Preserve any non-zero exit code set by a failed tick — don't mask a
232
+ // download failure with a clean exit just because the user pressed Ctrl+C.
233
+ process.exit(process.exitCode ?? 0);
154
234
  }
155
235
  function isNetworkError(err) {
156
236
  // The api layer wraps fetch failures as `manifest: network error (...)`;
157
237
  // bare ENOTFOUND/ETIMEDOUT/etc. also surface here from `fetchAssetBytes`.
238
+ // Include 502/504 strings — corporate proxies often surface upstream gateway
239
+ // failures as terse text rather than as ApiError (e.g. 502 from a TLS
240
+ // terminator before our edge function ever sees the request).
158
241
  const msg = err.message;
159
242
  return (/network error/i.test(msg) ||
160
- /ENOTFOUND|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN/i.test(msg) ||
161
- /fetch failed/i.test(msg));
243
+ /ENOTFOUND|ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH/i.test(msg) ||
244
+ /fetch failed/i.test(msg) ||
245
+ /\b(502|504)\b.*\b(bad gateway|gateway timeout)\b/i.test(msg));
246
+ }
247
+ /**
248
+ * Pure helper: given how many consecutive idle ticks we've seen and the
249
+ * configured poll interval, return the next backoff in seconds. Exported so
250
+ * the watch-mode regression test can guard the "ticks vs seconds" bug fixed
251
+ * in 0.4.0 without exercising the full watch loop.
252
+ */
253
+ export function nextBackoffForIdle(consecutiveIdleTicks, intervalSec, thresholds = { softSec: 180, hardSec: 900 }) {
254
+ const idleSeconds = consecutiveIdleTicks * intervalSec;
255
+ if (idleSeconds >= thresholds.hardSec)
256
+ return Math.max(intervalSec, 10);
257
+ if (idleSeconds >= thresholds.softSec)
258
+ return Math.max(intervalSec, 5);
259
+ return intervalSec;
260
+ }
261
+ /**
262
+ * Pure helper: classify a per-tick error and compute the next backoff +
263
+ * counter updates. Extracted so the auth-failure watchdog and the
264
+ * network-recovery message can be unit-tested without spinning up signals or
265
+ * mocking timers.
266
+ *
267
+ * Caller is responsible for performing side effects (logging, `process.exit`,
268
+ * assigning the returned values back onto loop state).
269
+ */
270
+ export function classifyTickError(err, state) {
271
+ const apiErr = err instanceof ApiError ? err : null;
272
+ if (apiErr && (apiErr.status === 401 || apiErr.status === 403)) {
273
+ const next = state.consecutiveAuthFailures + 1;
274
+ return {
275
+ kind: 'auth',
276
+ nextBackoffSec: 30,
277
+ consecutiveAuthFailures: next,
278
+ giveUp: next >= state.maxAuthFailures,
279
+ };
280
+ }
281
+ if (isNetworkError(err)) {
282
+ const nextBackoffSec = Math.min(state.backoffSec * 2, 60);
283
+ // Print on the first offline tick, then again whenever backoff changes —
284
+ // capped at 60s so users who walked away still see periodic confirmation
285
+ // the watcher is alive and retrying.
286
+ const printMessage = !state.pausedForNetwork || nextBackoffSec !== state.backoffSec;
287
+ return { kind: 'network', nextBackoffSec, printMessage };
288
+ }
289
+ return { kind: 'other', nextBackoffSec: Math.min(state.backoffSec * 2, 60) };
162
290
  }
163
291
  async function runOnce(opts, runOpts = {}) {
164
292
  const config = await loadConfig();
@@ -192,13 +320,28 @@ async function runOnce(opts, runOpts = {}) {
192
320
  renamed.push({ id: entry.id, oldKey: prevKey, newKey: entry.key });
193
321
  }
194
322
  }
195
- // Diff against disk
323
+ // Compute the disk path once per entry and reuse it across the diff /
324
+ // orphan / download loops — saves three resolves + two security asserts
325
+ // per asset on large projects. Every entry in `manifest` is pre-seeded, so
326
+ // the lookup never misses; non-null assertion is safe.
327
+ const diskPathById = new Map();
328
+ for (const entry of manifest) {
329
+ diskPathById.set(entry.id, assetDiskPath(config.outDir, entry));
330
+ }
331
+ const pathFor = (entry) => diskPathById.get(entry.id);
332
+ // Diff against disk. SHA pre-check runs through the same concurrency pool
333
+ // used for downloads — on a 1k-asset project that's all-unchanged this is
334
+ // the dominant wall-clock cost of an incremental sync. We cache each result
335
+ // so the download loop can reuse it for `If-None-Match` ETags instead of
336
+ // re-hashing the same file moments later.
337
+ const diffLimit = createLimit(concurrency);
338
+ const shaByEntryId = new Map();
196
339
  const toDownload = [];
197
340
  let bytesSaved = 0;
198
341
  let unchanged = 0;
199
- for (const entry of manifest) {
200
- const diskPath = assetDiskPath(config.outDir, entry);
201
- const localSha = await fileSha256(diskPath);
342
+ await Promise.all(manifest.map((entry) => diffLimit(async () => {
343
+ const localSha = await fileSha256(pathFor(entry));
344
+ shaByEntryId.set(entry.id, localSha);
202
345
  if (entry.sha256 && localSha && entry.sha256 === localSha) {
203
346
  unchanged++;
204
347
  if (entry.size_bytes)
@@ -207,14 +350,14 @@ async function runOnce(opts, runOpts = {}) {
207
350
  else {
208
351
  toDownload.push(entry);
209
352
  }
210
- }
353
+ })));
211
354
  // Orphan detection only when we have the full picture.
212
355
  // (Renames also produce a stale path on disk — collected separately below.)
213
356
  let orphans = [];
214
357
  if (!since) {
215
- const remoteDiskPaths = new Set(manifest.map((e) => assetDiskPath(config.outDir, e)));
216
- orphans = (await findLocalPngs(resolve(process.cwd(), config.outDir)))
217
- .filter((p) => !remoteDiskPaths.has(p));
358
+ const remoteDiskPaths = new Set(manifest.map((e) => pathFor(e)));
359
+ const localPngs = await walkOutDirPngs(config.outDir);
360
+ orphans = localPngs.map((a) => a.abs).filter((p) => !remoteDiskPaths.has(p));
218
361
  }
219
362
  // Stale paths from detected renames (always pruned, even in incremental mode —
220
363
  // otherwise the old PNG silently lingers next to the renamed copy).
@@ -278,13 +421,25 @@ async function runOnce(opts, runOpts = {}) {
278
421
  const run = createLimit(concurrency);
279
422
  let done = 0;
280
423
  await Promise.all(toDownload.map((entry) => run(async () => {
281
- const diskPath = assetDiskPath(config.outDir, entry);
424
+ const diskPath = pathFor(entry);
282
425
  const existedBefore = existsSync(diskPath);
283
426
  try {
284
- const localSha = await fileSha256(diskPath);
427
+ // Reuse the SHA computed during the diff pre-check — re-hashing the
428
+ // same file moments later was a measurable cost on large projects.
429
+ const localSha = shaByEntryId.get(entry.id) ?? null;
285
430
  const bytes = await fetchAssetBytes(config, entry.key, localSha);
286
431
  if (bytes === null) {
432
+ // Server returned 304 (ETag matched). Credit the asset's manifest
433
+ // size to bytesSaved so the end-of-sync summary reflects the
434
+ // bandwidth the conditional GET avoided.
435
+ //
436
+ // Invariant: we only reach here for entries that made it into
437
+ // `toDownload`, i.e. the disk-SHA pre-check above did NOT credit
438
+ // them (typically because `entry.sha256` was null in the manifest
439
+ // but the ETag still matched server-side). So no double-counting.
287
440
  result.unchanged++;
441
+ if (entry.size_bytes)
442
+ result.bytesSaved += entry.size_bytes;
288
443
  }
289
444
  else {
290
445
  if (entry.sha256) {
@@ -293,11 +448,22 @@ async function runOnce(opts, runOpts = {}) {
293
448
  throw new Error(`sha256 mismatch (expected ${entry.sha256.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`);
294
449
  }
295
450
  }
296
- await mkdir(dirname(diskPath), { recursive: true });
297
- const tmp = tmpPathFor(diskPath);
298
- assertPathInsideRoot(tmp, resolve(process.cwd(), config.outDir), 'outDir');
299
- await writeFile(tmp, bytes);
300
- await rename(tmp, diskPath);
451
+ // Wrap any of mkdir/writeFile/rename so the user sees a friendly
452
+ // multi-line diagnostic instead of a raw `EACCES: permission denied`.
453
+ try {
454
+ await mkdir(dirname(diskPath), { recursive: true });
455
+ const tmp = tmpPathFor(diskPath);
456
+ assertPathInsideRoot(tmp, resolve(process.cwd(), config.outDir), 'outDir');
457
+ await writeFile(tmp, bytes);
458
+ await rename(tmp, diskPath);
459
+ }
460
+ catch (fsErr) {
461
+ throw friendlyFsError(fsErr, {
462
+ operation: `Writing asset`,
463
+ path: diskPath,
464
+ hint: `Sync can't continue until outDir (${config.outDir}) is writable.`,
465
+ });
466
+ }
301
467
  if (existedBefore)
302
468
  result.modified.push(entry.key);
303
469
  else
@@ -308,7 +474,17 @@ async function runOnce(opts, runOpts = {}) {
308
474
  catch (e) {
309
475
  result.failed++;
310
476
  progress?.stop();
311
- console.log(` ${kleur.red('!')} ${entry.key}: ${e.message.split('\n')[0]}`);
477
+ // Multi-line messages come from friendlyFsError — print all lines
478
+ // so the user sees the fix hint. Single-line errors stay terse.
479
+ const msg = e.message ?? String(e);
480
+ if (msg.includes('\n')) {
481
+ console.log(` ${kleur.red('!')} ${entry.key}:`);
482
+ for (const line of msg.split('\n'))
483
+ console.log(` ${line}`);
484
+ }
485
+ else {
486
+ console.log(` ${kleur.red('!')} ${entry.key}: ${msg}`);
487
+ }
312
488
  progress?.start();
313
489
  }
314
490
  finally {
@@ -366,7 +542,27 @@ async function runOnce(opts, runOpts = {}) {
366
542
  }
367
543
  const nextState = { ...state, assets: nextAssets };
368
544
  if (result.failed === 0) {
369
- nextState.lastSync = startedAt;
545
+ // Advance the cursor to the newest row we actually observed, NOT the
546
+ // wall-clock time the sync started. Using startedAt silently skipped
547
+ // rows whose `updated_at` lived in the gap between the manifest snapshot
548
+ // and the next poll (notably when only metadata changed — e.g. artboard
549
+ // renames — and the row updated between fetch start and save).
550
+ const maxUpdatedAt = maxIsoTimestamp(manifest.map((e) => e.updated_at));
551
+ if (maxUpdatedAt) {
552
+ // Take the later of: newest row we saw, or the prior cursor. Never
553
+ // rewind — an incremental sync that returned 0 rows must keep the
554
+ // existing lastSync (otherwise we'd re-download history next tick).
555
+ nextState.lastSync =
556
+ state.lastSync && state.lastSync > maxUpdatedAt ? state.lastSync : maxUpdatedAt;
557
+ }
558
+ else if (state.lastSync) {
559
+ nextState.lastSync = state.lastSync;
560
+ }
561
+ else {
562
+ // No prior cursor and an empty manifest (fresh project): fall back to
563
+ // startedAt so future incremental polls have a baseline.
564
+ nextState.lastSync = startedAt;
565
+ }
370
566
  delete nextState.lastError;
371
567
  }
372
568
  else {
@@ -388,18 +584,20 @@ async function runOnce(opts, runOpts = {}) {
388
584
  const indexPath = await emitTypedIndex(config.outDir, diskEntries);
389
585
  if (verbose)
390
586
  console.log(kleur.dim(` index → ${relative(process.cwd(), indexPath)}`));
391
- // Nudge AI tools toward the typed index. Idempotent — `ensureAgentsDoc`
392
- // no-ops once our marker section is present.
393
- try {
394
- const agentsResult = await ensureAgentsDoc(config.outDir);
395
- if (verbose && agentsResult !== 'unchanged') {
396
- console.log(kleur.dim(` AGENTS.md ${agentsResult}`));
397
- }
398
- }
399
- catch {
400
- // Never let an AGENTS.md write failure break sync.
587
+ }
588
+ // AGENTS.md hint is always written — `public/` and `static/` users
589
+ // (emitIndex: false) need the absolute-URL snippet just as much as
590
+ // bundler-importable outDir users need the ES-import one.
591
+ // `ensureAgentsDoc` no-ops once our marker section is present.
592
+ try {
593
+ const agentsResult = await ensureAgentsDoc(config.outDir);
594
+ if (verbose && agentsResult !== 'unchanged') {
595
+ console.log(kleur.dim(` AGENTS.md ${agentsResult}`));
401
596
  }
402
597
  }
598
+ catch {
599
+ // Never let an AGENTS.md write failure break sync.
600
+ }
403
601
  await saveState(nextState);
404
602
  if (result.failed > 0 && verbose) {
405
603
  console.log(kleur.yellow(`\n${result.failed} download${result.failed === 1 ? '' : 's'} failed — lastSync not advanced. Re-run to retry.`));
@@ -413,7 +611,10 @@ async function runOnce(opts, runOpts = {}) {
413
611
  (renamed.length ? `, renamed ${renamed.length}` : '') +
414
612
  (result.failed ? `, failed ${result.failed}` : '');
415
613
  console.log(result.failed ? kleur.yellow(`done with errors. ${summary}`) : kleur.green(`✓ done. ${summary}`));
416
- printChanges(result, ' ');
614
+ // Per-file change list. Suppress renames here — printRenames below owns
615
+ // the rename block (it adds the import-update hints). Letting both fire
616
+ // would print each rename twice.
617
+ printChanges(result, ' ', { includeRenames: renamed.length === 0 });
417
618
  if (renamed.length > 0)
418
619
  printRenames(renamed, { withHints: true });
419
620
  }
@@ -422,14 +623,16 @@ async function runOnce(opts, runOpts = {}) {
422
623
  return result;
423
624
  }
424
625
  const CHANGE_PRINT_CAP = 50;
425
- function printChanges(r, indent) {
626
+ function printChanges(r, indent, opts = { includeRenames: true }) {
426
627
  const lines = [];
427
628
  for (const k of r.added)
428
629
  lines.push(`${indent}${kleur.green('+')} ${k}`);
429
630
  for (const k of r.modified)
430
631
  lines.push(`${indent}${kleur.cyan('~')} ${k}`);
431
- for (const r2 of r.renamed)
432
- lines.push(`${indent}${kleur.cyan('↪')} ${r2.oldKey} → ${r2.newKey}`);
632
+ if (opts.includeRenames) {
633
+ for (const r2 of r.renamed)
634
+ lines.push(`${indent}${kleur.cyan('↪')} ${r2.oldKey} → ${r2.newKey}`);
635
+ }
433
636
  for (const k of r.removed)
434
637
  lines.push(`${indent}${kleur.red('-')} ${k}`);
435
638
  if (lines.length === 0)
@@ -464,13 +667,6 @@ function progressText(done, total, bytes) {
464
667
  const bar = '█'.repeat(filled) + '░'.repeat(barWidth - filled);
465
668
  return `${bar} ${done}/${total} ${kleur.dim(formatBytes(bytes))}`;
466
669
  }
467
- function formatBytes(n) {
468
- if (n < 1024)
469
- return `${n} B`;
470
- if (n < 1024 * 1024)
471
- return `${(n / 1024).toFixed(1)} KB`;
472
- return `${(n / (1024 * 1024)).toFixed(1)} MB`;
473
- }
474
670
  function timestamp() {
475
671
  const d = new Date();
476
672
  return `[${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}]`;
@@ -489,68 +685,7 @@ function printOrphans(orphans) {
489
685
  for (const p of orphans) {
490
686
  console.log(` ${kleur.dim('?')} ${relative(process.cwd(), p)}`);
491
687
  }
492
- console.log(kleur.dim(' Pruning is on by default. Re-run without --no-prune to delete them.'));
493
- }
494
- async function findLocalPngs(dir) {
495
- if (!existsSync(dir))
496
- return [];
497
- const root = resolve(dir);
498
- const out = [];
499
- async function walk(d) {
500
- const entries = await readdir(d, { withFileTypes: true });
501
- for (const ent of entries) {
502
- if (ent.isSymbolicLink())
503
- continue;
504
- const full = resolve(d, ent.name);
505
- try {
506
- assertPathInsideRoot(full, root, 'outDir');
507
- }
508
- catch {
509
- continue;
510
- }
511
- if (ent.isDirectory()) {
512
- if (ent.name.startsWith('.'))
513
- continue;
514
- await walk(full);
515
- }
516
- else if (ent.isFile() && ent.name.toLowerCase().endsWith('.png')) {
517
- out.push(full);
518
- }
519
- }
520
- }
521
- await walk(root);
522
- return out;
523
- }
524
- async function pruneEmptyDirs(root) {
525
- if (!existsSync(root))
526
- return;
527
- async function walk(d) {
528
- const entries = await readdir(d, { withFileTypes: true });
529
- let isEmpty = true;
530
- for (const ent of entries) {
531
- const full = resolve(d, ent.name);
532
- if (ent.isDirectory()) {
533
- const childEmpty = await walk(full);
534
- if (childEmpty) {
535
- await rm(full, { recursive: true, force: true });
536
- }
537
- else {
538
- isEmpty = false;
539
- }
540
- }
541
- else {
542
- isEmpty = false;
543
- }
544
- }
545
- return isEmpty;
546
- }
547
- const entries = await readdir(root, { withFileTypes: true });
548
- for (const ent of entries) {
549
- if (ent.isDirectory()) {
550
- const full = resolve(root, ent.name);
551
- const empty = await walk(full);
552
- if (empty)
553
- await rm(full, { recursive: true, force: true });
554
- }
555
- }
688
+ console.log(kleur.dim(' You passed --no-prune, so these were kept. Remove the flag to delete them.'));
556
689
  }
690
+ // Note: orphan scan delegates to `walkOutDirPngs` in util/paths.ts (shared
691
+ // with the typed-index emitter). `maxIsoTimestamp` lives in util/iso.ts.